diff --git a/docs/en/guide/user-page.md b/docs/en/guide/user-page.md index 16c936957..4e12c4cb4 100644 --- a/docs/en/guide/user-page.md +++ b/docs/en/guide/user-page.md @@ -23,7 +23,7 @@ From top to bottom: - **With an app** (the names come from the apps list; only link apps are listed, never a key app): the app, then install it (with the store or download button and the card's description) and **Add to Happ**, the one-tap link from the app's template. "Won't open? Copy the link" sits right under it. "All your servers (4) appear in Happ — pick any". A QR code of the link, for connecting a phone, when **QR for a second device** is on. "Connected with the subscription" says when the apps on the link last fetched it. Opening the page does not update this time, and does not add a device; only an app fetch does. - **With a key**: install AmneziaVPN, **Add a device** (the key form opens), paste the key. When self-service is off the step says "Ask for a key". 5. **Telegram proxy** and **TrustTunnel**, when the owner switched them on for the person, under the servers (see [Telegram proxy](#telegram-proxy)). -6. **My devices**: one list with the apps on the link and the person's keys, and one **Add a device** button for both ways (see [My devices](#my-devices)). +6. **My devices**: one list with the apps on the link and the person's keys, and one **Add a device** button for both ways (see [My devices](#my-devices)). Under the list, when the owner has set a bot for people, the block **Notifications in Telegram** (see [Notifications in Telegram](#notifications-in-telegram)). 7. **Support**: "Something not working?" with a button to the support link, when **Support button** is on and a link is set. 8. A line at the bottom: "This link is personal — don't share it. Works while the subscription is active." @@ -138,6 +138,19 @@ Limits: only an active person can add a device, show a key or replace one; the d A person whose subscription is not active still sees their AmneziaVPN keys, and can rename and remove them; adding new ones is not possible. +## Notifications in Telegram + +When the owner has set the bot of the notifications for people (a bot of its own, never the one the admin uses), a person can connect their own Telegram to it from the page. The block sits on the devices tab under the list. It is not on the page when no such bot is set, when **Devices on the page** is off (the block follows that switch and its limits) or in the owner's preview. + +- **Not connected**: a short warning, "Telegram will know you use this service", the button **Connect Telegram**, and an example of what the bot writes (the term is ending, the traffic is running out, the servers do not work). +- **Connect Telegram** makes a link `t.me/?start=`: one-time, valid for 15 minutes, one pending link per person (a new one replaces the old). The page shows the time left and **Open Telegram**; the person presses **Start** in the chat. While the page is open it asks the panel every few seconds, so it notices the chat and changes to "Connected" by itself. **Cancel** withdraws the link. A link that ran out says "Link expired" and offers a **New link**. The panel keeps only a hash of the code, and the page has the link only in memory: after a reload a pending link is not shown, and the person asks for a new one. +- **Connected**: "Connected 2 of 3" and a row for each chat with its language, since when, the switch **Announcements** and **Disconnect**. The switch is the same as `/mute` in the chat and concerns the owner's announcements only; the notices about the term, the traffic and failures keep coming. `/stop` in the chat disconnects it. The commands are told on the page. +- **How many chats**: 3 by default for a person; the owner changes it for everybody (1 to 10) or for one person. At the limit **Connect another one** is not shown, and a link made earlier is refused by the bot with a reason. A new chat is told to the person's other chats ("another Telegram was connected, if it was not you, disconnect it"). +- A change (a link, cancel, disconnect, the switch) counts against the same hourly limit as the other actions of the page (20 per client network, 100 per link); reading the block, which the page does while it waits for Telegram, does not. The page needs the page password like every call under the link. +- The page learns the bot's username, the row id of each chat, its language, the date and whether announcements are on. It never gets the Telegram chat id or the bot's token. The audit log has `user_telegram_link_begin`, `user_telegram_link_cancel`, `user_telegram_unlink` and `user_telegram_mute` with the person's id. + +**Privacy.** Connecting a chat ties the person to a Telegram account: the panel keeps that link (the chat id is encrypted) and Telegram sees that this account talks to a bot of the service. The bot has a neutral name and neutral words, never sends a link and asks for nothing. Do not offer it to people for whom it matters that a Telegram account is tied to their use of the service, and do not push it: the page asks first, and the person chooses. + ## DNS When the owner turns on **DNS choice on the page** (see below), a person picks on their page: diff --git a/docs/fa/guide/user-page.md b/docs/fa/guide/user-page.md index 8030a5467..55675cdc4 100644 --- a/docs/fa/guide/user-page.md +++ b/docs/fa/guide/user-page.md @@ -23,7 +23,7 @@ description: فرد وقتی لینکش را در مرورگر باز می‌ک - **با برنامه** (نام‌ها از فهرست برنامه‌ها می‌آید؛ فقط برنامه‌های لینکی فهرست می‌شوند، هرگز برنامهٔ کلیدی): برنامه، سپس نصبش (با دکمهٔ فروشگاه یا دانلود و توضیح کارت) و **افزودن به Happ**، لینک یک‌لمسی از قالب برنامه. «باز نمی‌شود؟ کپی لینک» درست زیر آن است. «همهٔ سرورهای شما (4) آنجا هستند — هر کدام را خواستید انتخاب کنید». یک کد QR از لینک، برای وصل کردن گوشی، وقتی **QR برای دستگاه دوم** روشن است. «با اشتراک وصل شد» می‌گوید برنامه‌های روی لینک آخرین بار کِی آن را گرفتند. باز کردن صفحه این زمان را به‌روز نمی‌کند و دستگاهی اضافه نمی‌کند؛ فقط دریافت توسط برنامه چنین می‌کند. - **با کلید**: AmneziaVPN را نصب کنید، **افزودن دستگاه** (فرم کلید باز می‌شود)، کلید را بچسبانید. وقتی خودخدمتی خاموش است مرحله «کلید بخواهید» می‌گوید. 5. **پروکسی Telegram**، وقتی مالک Telegram را برای فرد روشن کرده، زیر سرورها (به [پروکسی Telegram](#پروکسی-telegram) نگاه کنید). -6. **دستگاه‌های من**: یک فهرست با برنامه‌های روی لینک و کلیدهای فرد، و یک دکمهٔ **افزودن دستگاه** برای هر دو راه (به [دستگاه‌های من](#دستگاههای-من) نگاه کنید). +6. **دستگاه‌های من**: یک فهرست با برنامه‌های روی لینک و کلیدهای فرد، و یک دکمهٔ **افزودن دستگاه** برای هر دو راه (به [دستگاه‌های من](#دستگاههای-من) نگاه کنید). زیر فهرست، وقتی مالک رباتی برای افراد تنظیم کرده باشد، بخش **اعلان‌ها در Telegram** (به [اعلان‌ها در Telegram](#اعلانها-در-telegram) نگاه کنید). 7. **پشتیبانی**: «چیزی کار نمی‌کند؟» با دکمه‌ای به لینک پشتیبانی، وقتی **دکمهٔ پشتیبانی** روشن است و لینکی تعیین شده. 8. خطی در پایین: «این لینک شخصی است — آن را برای کسی نفرستید. تا وقتی اشتراک فعال است کار می‌کند.» @@ -124,6 +124,19 @@ description: فرد وقتی لینکش را در مرورگر باز می‌ک فردی که اشتراکش فعال نیست باز هم کلیدهای AmneziaVPN خودش را می‌بیند، و می‌تواند تغییر نامشان دهد و حذفشان کند؛ افزودن کلید تازه ممکن نیست. +## اعلان‌ها در Telegram + +وقتی مالک ربات اعلان‌ها را برای افراد تنظیم کرده باشد (رباتی جداگانه، هرگز همان رباتی که مدیریت استفاده می‌کند)، فرد می‌تواند Telegram خودش را از صفحه به آن وصل کند. این بخش در زبانهٔ دستگاه‌ها زیر فهرست قرار دارد. اگر چنین رباتی تنظیم نشده باشد، اگر **دستگاه‌ها در صفحه** خاموش باشد (این بخش از همان کلید و محدودیت‌هایش پیروی می‌کند) یا در پیش‌نمایش مالک، روی صفحه نیست. + +- **وصل نیست**: یک هشدار کوتاه، «Telegram خواهد دانست که از این سرویس استفاده می‌کنید»، دکمهٔ **وصل کردن Telegram** و نمونه‌ای از آنچه ربات می‌نویسد (مهلت رو به پایان است، ترافیک رو به اتمام است، سرورها کار نمی‌کنند). +- **وصل کردن Telegram** یک لینک `t.me/?start=` می‌سازد: یک‌بارمصرف، با اعتبار ۱۵ دقیقه، یک لینک در انتظار برای هر فرد (لینک تازه جای قبلی را می‌گیرد). صفحه زمان باقی‌مانده و **باز کردن Telegram** را نشان می‌دهد؛ فرد در گفتگو **Start** را می‌زند. تا وقتی صفحه باز است، هر چند ثانیه از پنل می‌پرسد، پس گفتگو را تشخیص می‌دهد و خودش به «وصل شد» تغییر می‌کند. **لغو** لینک را پس می‌گیرد. لینکی که منقضی شده می‌گوید «لینک منقضی شد» و **لینک تازه** پیشنهاد می‌کند. پنل فقط هش کد را نگه می‌دارد و صفحه لینک را فقط در حافظه دارد: پس از بارگذاری دوباره، لینک در انتظار نشان داده نمی‌شود و فرد لینک تازه می‌خواهد. +- **وصل شد**: «۲ از ۳ وصل است» و برای هر گفتگو یک ردیف با زبانش، از چه زمانی، کلید **اعلان‌ها** و **قطع اتصال**. این کلید همان `/mute` در گفتگو است و فقط به اعلان‌های مالک مربوط است؛ پیام‌های مربوط به مهلت، ترافیک و خرابی‌ها همچنان می‌رسند. `/stop` در گفتگو اتصال آن را قطع می‌کند. دستورها روی صفحه گفته شده‌اند. +- **چند گفتگو**: به‌طور پیش‌فرض ۳ برای هر فرد؛ مالک آن را برای همه (۱ تا ۱۰) یا برای یک فرد تغییر می‌دهد. در سقف، **وصل کردن یکی دیگر** نشان داده نمی‌شود و ربات لینکی را که پیش‌تر ساخته شده با ذکر دلیل رد می‌کند. گفتگوی تازه به دیگر گفتگوهای فرد اطلاع داده می‌شود («Telegram دیگری وصل شد، اگر شما نبودید، اتصالش را قطع کنید»). +- هر تغییر (لینک، لغو، قطع اتصال، کلید) از همان سقف ساعتی دیگر کارهای صفحه کم می‌شود (۲۰ برای هر شبکهٔ کلاینت، ۱۰۰ برای هر لینک)؛ خواندن این بخش، که صفحه هنگام انتظار برای Telegram انجام می‌دهد، کم نمی‌شود. مانند هر درخواست زیر لینک، صفحه به رمز عبور صفحه نیاز دارد. +- صفحه نام کاربری ربات، شناسهٔ ردیف هر گفتگو، زبان، تاریخ و روشن یا خاموش بودن اعلان‌ها را می‌گیرد. هرگز شناسهٔ گفتگوی Telegram یا توکن ربات را نمی‌گیرد. در گزارش ممیزی `user_telegram_link_begin`، `user_telegram_link_cancel`، `user_telegram_unlink` و `user_telegram_mute` با شناسهٔ فرد ثبت می‌شود. + +**حریم خصوصی.** وصل کردن یک گفتگو فرد را به یک حساب Telegram گره می‌زند: پنل این پیوند را نگه می‌دارد (شناسهٔ گفتگو رمزگذاری شده است) و Telegram می‌بیند که این حساب با رباتی از این سرویس گفتگو می‌کند. ربات نام و واژه‌های بی‌طرف دارد، هرگز لینک نمی‌فرستد و چیزی نمی‌پرسد. آن را به کسانی که برایشان مهم است حساب Telegram به استفاده‌شان از سرویس گره بخورد پیشنهاد نکنید و اصرار نکنید: صفحه اول می‌پرسد و فرد انتخاب می‌کند. + ## DNS وقتی مالک **انتخاب DNS در صفحه** را روشن کند (پایین را ببینید)، فرد در صفحه‌اش انتخاب می‌کند: diff --git a/docs/ru/guide/user-page.md b/docs/ru/guide/user-page.md index 7da079306..590090077 100644 --- a/docs/ru/guide/user-page.md +++ b/docs/ru/guide/user-page.md @@ -23,7 +23,7 @@ description: Что видит человек, когда открывает с - **Через приложение** (названия берутся из списка приложений; в списке только приложения по ссылке, ключевых там нет): выбрать приложение, установить его (кнопка магазина или скачивания и описание с карточки) и **Добавить в Happ** — ссылка в одно касание по шаблону приложения. Прямо под ней «Не открывается? Скопировать ссылку». «В Happ появятся все ваши серверы (4) — выберите любой». QR-код ссылки, чтобы подключить телефон, если включено **QR для второго устройства**. «Подключено через подписку» говорит, когда приложения по ссылке последний раз забирали подписку. Если вы или пользователь откроете эту страницу, время не изменится и устройство не добавится: учитывается только запрос приложения. - **Ключом**: установить AmneziaVPN, **Добавить устройство** (откроется форма ключа), вставить ключ. Если самообслуживание выключено, шаг говорит «Попросите ключ». 5. **Telegram-прокси** и **TrustTunnel**, если владелец включил их для человека, под серверами (см. [Telegram-прокси](#telegram-прокси)). -6. **Мои устройства**: один список из приложений по ссылке и ключей человека и одна кнопка **Добавить устройство** для обоих способов (см. [Мои устройства](#мои-устройства)). +6. **Мои устройства**: один список из приложений по ссылке и ключей человека и одна кнопка **Добавить устройство** для обоих способов (см. [Мои устройства](#мои-устройства)). Под списком, если владелец задал бота для людей, блок **Уведомления в Telegram** (см. [Уведомления в Telegram](#уведомления-в-telegram)). 7. **Поддержка**: «Что-то не работает?» с кнопкой, ведущей по ссылке на поддержку, если включена **Кнопка поддержки** и ссылка задана. 8. Строка внизу: «Ссылка личная — не пересылайте её. Работает, пока подписка активна.» @@ -138,6 +138,19 @@ description: Что видит человек, когда открывает с Человек с неактивной подпиской по-прежнему видит свои ключи AmneziaVPN, может их переименовать и удалить; добавить новые нельзя. +## Уведомления в Telegram + +Если владелец задал бота уведомлений для людей (отдельного, не того, которым пользуется админ), человек может подключить к нему свой Telegram прямо на странице. Блок стоит на вкладке устройств под списком. Его нет на странице, когда такого бота не задано, когда выключено **Устройства на странице** (блок идёт за этим переключателем и его лимитами) и в предпросмотре владельца. + +- **Не подключено**: короткое предупреждение «Telegram будет знать, что вы пользуетесь этим сервисом», кнопка **Подключить Telegram** и пример того, что пишет бот (подходит конец срока, заканчивается трафик, не работают серверы). +- **Подключить Telegram** делает ссылку `t.me/<бот>?start=<код>`: одноразовую, на 15 минут, одна ожидающая ссылка на человека (новая заменяет старую). Страница показывает, сколько осталось, и кнопку **Открыть Telegram**; человек нажимает в чате «Запустить». Пока страница открыта, она раз в несколько секунд спрашивает панель, сама замечает чат и переходит в «Подключено». **Отмена** отзывает ссылку. Ссылка, которая закончилась, подписана «Ссылка устарела» и предлагает **Новую ссылку**. Панель хранит только хэш кода, а у страницы ссылка лишь в памяти: после перезагрузки ожидающая ссылка не показывается, и человек просит новую. +- **Подключено**: «Подключено 2 из 3» и строка на каждый чат: язык, с какого числа, переключатель **Объявления** и **Отключить**. Переключатель то же, что `/mute` в чате, и касается только объявлений владельца; уведомления о сроке, трафике и сбоях приходят как раньше. `/stop` в чате отключает его. Команды написаны на странице. +- **Сколько чатов**: по умолчанию 3 на человека; владелец меняет это для всех (от 1 до 10) или для одного человека. На пределе **Подключить ещё один** не показывается, а ссылку, сделанную раньше, бот отклоняет с объяснением. О новом чате сообщается остальным чатам человека («подключили ещё один Telegram, если это не вы, отключите»). +- Любое изменение (ссылка, отмена, отключение, переключатель) идёт в тот же часовой лимит, что и остальные действия страницы (20 с клиентской сети, 100 на ссылку); чтение блока, которое страница делает, пока ждёт Telegram, лимит не тратит. Нужен пароль страницы, как для любого вызова под ссылкой. +- Страница узнаёт имя бота, идентификатор строки каждого чата, его язык, дату и включены ли объявления. Идентификатор чата в Telegram и токен бота она не получает никогда. В журнале аудита: `user_telegram_link_begin`, `user_telegram_link_cancel`, `user_telegram_unlink` и `user_telegram_mute` с идентификатором человека. + +**Приватность.** Подключив чат, человек связывает себя с аккаунтом Telegram: панель хранит эту связь (идентификатор чата зашифрован), а Telegram видит, что этот аккаунт переписывается с ботом сервиса. У бота нейтральное имя и слова, он не присылает ссылок и ничего не спрашивает. Прямо: не предлагайте подключение тем, для кого важно, чтобы аккаунт Telegram не был связан с их пользованием сервисом (например, аккаунт оформлен на их имя и номер, а сервис им нужен там, где это опасно), и не уговаривайте: страница спрашивает, выбор за человеком. + ## DNS Когда владелец включает **Выбор DNS на странице** (см. ниже), человек выбирает на своей странице: diff --git a/docs/tr/guide/user-page.md b/docs/tr/guide/user-page.md index 4dcdb6704..5ff35718b 100644 --- a/docs/tr/guide/user-page.md +++ b/docs/tr/guide/user-page.md @@ -21,7 +21,7 @@ Yukarıdan aşağıya: - **Uygulamayla** (adlar uygulama listesinden gelir; yalnızca bağlantı uygulamaları listelenir, anahtar uygulamaları asla): uygulama, sonra onu kurmak (mağaza ya da indirme düğmesi ve kartın açıklamasıyla) ve **Happ'e ekle**, uygulamanın şablonundan gelen tek dokunuşluk bağlantı. Hemen altında “Açılmıyor mu? Bağlantıyı kopyalayın”. “Tüm sunucularınız (4) zaten orada — istediğinizi seçin”. **İkinci cihaz için QR** açıksa bir telefonu bağlamak için bağlantının QR kodu. “Uygulama aboneliği en son aldı” bağlantıdaki uygulamaların onu en son ne zaman çektiğini söyler. Sayfayı açmak bu zamanı güncellemez ve cihaz eklemez; yalnızca bir uygulamanın çekmesi güncelleme yapar. - **Anahtarla**: AmneziaVPN'i kurun, **Cihaz ekle** (anahtar formu açılır), anahtarı yapıştırın. Kendi kendine yönetim kapalıysa adım “Anahtar isteyin” der. 5. **Telegram proxy'si**, sahip Telegram'ı kişi için açtıysa, sunucuların altında ([Telegram proxy'si](#telegram-proxysi) bölümüne bakın). -6. **Cihazlarım**: bağlantıdaki uygulamaların ve kişinin anahtarlarının tek listesi ve her iki yol için tek bir **Cihaz ekle** düğmesi ([Cihazlarım](#cihazlarım) bölümüne bakın). +6. **Cihazlarım**: bağlantıdaki uygulamaların ve kişinin anahtarlarının tek listesi ve her iki yol için tek bir **Cihaz ekle** düğmesi ([Cihazlarım](#cihazlarım) bölümüne bakın). Listenin altında, sahip kişiler için bir bot kurduysa, **Telegram bildirimleri** bloğu ([Telegram bildirimleri](#telegram-bildirimleri) bölümüne bakın). 7. **Destek**: “Bir şey çalışmıyor mu?” ve, **Destek düğmesi** açıksa ve bir bağlantı ayarlıysa, destek bağlantısına giden bir düğme. 8. Altta bir satır: “Bu bağlantı size özel — kimseyle paylaşmayın. Abonelik etkin olduğu sürece çalışır.” @@ -122,6 +122,19 @@ Sınırlar: yalnızca etkin bir kişi cihaz ekleyebilir, anahtar gösterebilir y Aboneliği etkin olmayan bir kişi AmneziaVPN anahtarlarını yine görür ve onları yeniden adlandırıp kaldırabilir; yeni anahtar eklemek mümkün değildir. +## Telegram bildirimleri + +Sahip, kişiler için bildirim botunu kurduğunda (kendine ait bir bot, yönetimin kullandığı bot asla değil) kişi kendi Telegram'ını sayfadan bu bota bağlayabilir. Blok, cihazlar sekmesinde listenin altında durur. Böyle bir bot yoksa, **Sayfada cihazlar** kapalıysa (blok bu anahtarı ve sınırlarını izler) ya da sahibin önizlemesinde sayfada görünmez. + +- **Bağlı değil**: kısa bir uyarı, "Telegram bu hizmeti kullandığınızı bilecek", **Telegram'ı bağla** düğmesi ve botun neler yazdığına bir örnek (süre bitiyor, trafik azalıyor, sunucular çalışmıyor). +- **Telegram'ı bağla** bir `t.me/?start=` bağlantısı oluşturur: tek kullanımlık, 15 dakika geçerli, kişi başına bekleyen tek bağlantı (yenisi eskisinin yerini alır). Sayfa kalan süreyi ve **Telegram'ı aç** düğmesini gösterir; kişi sohbette **Başlat**'a basar. Sayfa açıkken birkaç saniyede bir panele sorar, böylece sohbeti fark eder ve kendiliğinden "Bağlandı" durumuna geçer. **İptal** bağlantıyı geri çeker. Süresi dolan bağlantı "Bağlantının süresi doldu" der ve **Yeni bağlantı** önerir. Panel kodun yalnızca özetini (hash) tutar, sayfa da bağlantıyı yalnızca bellekte tutar: sayfa yenilenince bekleyen bağlantı gösterilmez ve kişi yenisini ister. +- **Bağlandı**: "3 sohbetten 2'si bağlı" ve her sohbet için dili, ne zamandan beri bağlı olduğu, **Duyurular** anahtarı ve **Bağlantıyı kes** içeren bir satır. Anahtar, sohbetteki `/mute` ile aynıdır ve yalnızca sahibin duyurularını etkiler; süre, trafik ve arızalarla ilgili bildirimler gelmeye devam eder. Sohbette `/stop` o sohbetin bağlantısını keser. Komutlar sayfada yazılıdır. +- **Kaç sohbet**: kişi başına varsayılan 3; sahip bunu herkes için (1 ile 10 arası) ya da tek bir kişi için değiştirir. Sınıra ulaşıldığında **Bir tane daha bağla** gösterilmez ve daha önce oluşturulmuş bir bağlantıyı bot gerekçesiyle reddeder. Yeni bir sohbet, kişinin diğer sohbetlerine bildirilir ("başka bir Telegram bağlandı, siz değilseniz bağlantısını kesin"). +- Bir değişiklik (bağlantı, iptal, bağlantı kesme, anahtar) sayfanın diğer işlemleriyle aynı saatlik sınırdan düşer (istemci ağı başına 20, bağlantı başına 100); sayfanın Telegram'ı beklerken yaptığı blok okuması düşmez. Bağlantının altındaki her çağrı gibi sayfa parolası gerekir. +- Sayfa botun kullanıcı adını, her sohbetin satır kimliğini, dilini, tarihini ve duyuruların açık olup olmadığını öğrenir. Telegram sohbet kimliğini ya da botun token'ını asla almaz. Denetim günlüğünde kişinin kimliğiyle `user_telegram_link_begin`, `user_telegram_link_cancel`, `user_telegram_unlink` ve `user_telegram_mute` bulunur. + +**Gizlilik.** Bir sohbeti bağlamak kişiyi bir Telegram hesabına bağlar: panel bu bağı tutar (sohbet kimliği şifrelidir) ve Telegram bu hesabın hizmetin bir botuyla konuştuğunu görür. Botun adı ve sözcükleri nötrdür, asla bağlantı göndermez ve hiçbir şey sormaz. Bir Telegram hesabının hizmeti kullanmalarına bağlanması kendileri için önemli olan kişilere bunu önermeyin ve dayatmayın: sayfa önce sorar, kişi seçer. + ## DNS Sahip **Sayfada DNS seçimi** seçeneğini açtığında (aşağıya bakın), kişi sayfasında şunları seçer: diff --git a/docs/zh/guide/user-page.md b/docs/zh/guide/user-page.md index ab4d7ecec..2328d7056 100644 --- a/docs/zh/guide/user-page.md +++ b/docs/zh/guide/user-page.md @@ -23,7 +23,7 @@ description: 用户在浏览器中打开订阅链接时会看到什么、页面 - **通过应用**(名称来自应用列表;只列出订阅类应用,不列出使用密钥的应用):选择应用,然后安装应用(使用应用商店或下载按钮,以及卡片说明),再点击**添加到 Happ**,使用应用的链接模板打开应用。「无法打开?复制链接」会显示在按钮下方。「所有服务器(4)都会显示在 Happ 中,可任选一台。」开启**用于第二台设备的二维码**时,还会显示用于手机连接的链接二维码。「已通过订阅链接连接」会显示订阅类应用上次获取链接的时间。打开页面不会更新时间,也不会添加设备;只有应用获取链接时才会更新。 - **使用 AmneziaVPN 密钥**:安装 AmneziaVPN,点击**添加设备**(打开密钥表单),然后粘贴密钥。关闭自助服务时,此步骤会显示「向管理员申请密钥」。 5. **Telegram 代理**和 **TrustTunnel**:所有者为用户开启后显示,位于服务器下方(参见 [Telegram 代理](#telegram-代理))。 -6. **我的设备**:一个列表显示订阅类应用和用户的密钥;两种方式共用一个**添加设备**按钮(参见[我的设备](#我的设备))。 +6. **我的设备**:一个列表显示订阅类应用和用户的密钥;两种方式共用一个**添加设备**按钮(参见[我的设备](#我的设备))。列表下方,如果所有者设置了面向用户的机器人,会有**Telegram 通知**块(参见 [Telegram 通知](#telegram-通知))。 7. **支持**:开启**联系按钮**且已设置链接时,会显示「遇到问题?」和打开支持链接的按钮。 8. 页面底部会显示:「这是你的个人链接,请勿分享。订阅有效期间可用。」 @@ -138,6 +138,19 @@ description: 用户在浏览器中打开订阅链接时会看到什么、页面 订阅已失效的用户仍能查看自己的 AmneziaVPN 密钥,也可以重命名和移除密钥,但不能添加新密钥。 +## Telegram 通知 + +如果所有者设置了面向用户的通知机器人(专用机器人,不是管理员使用的那个),用户可以直接在页面上把自己的 Telegram 连接到它。该块位于设备标签页的列表下方。没有设置此类机器人、关闭了**页面上的设备**(该块跟随此开关及其限额),以及在所有者的预览中,页面上都没有它。 + +- **未连接**:一条简短的提示“Telegram 会知道您在使用此服务”、按钮**连接 Telegram**,以及机器人会发什么的示例(有效期临近、流量用完、服务器无法使用)。 +- **连接 Telegram** 会生成链接 `t.me/<机器人>?start=<代码>`:一次性,有效期 15 分钟,每人同时只有一个待用链接(新链接会替换旧的)。页面显示剩余时间和**打开 Telegram**;用户在聊天中点击“开始”。页面打开期间每隔几秒询问一次面板,自己发现聊天并切换为“已连接”。**取消**会撤回链接。过期的链接显示“链接已过期”,并提供**新链接**。面板只保存代码的哈希,页面也只在内存中持有链接:刷新页面后不再显示待用链接,需要重新获取。 +- **已连接**:“已连接 2 / 3”,每个聊天一行:语言、连接时间、开关**公告**和**断开**。该开关与聊天中的 `/mute` 相同,只涉及所有者的公告;有效期、流量和故障通知照常发送。在聊天中发送 `/stop` 可断开该聊天。页面上写明了这些命令。 +- **聊天数量**:每人默认 3 个;所有者可以为所有人(1 到 10)或为某个用户修改。达到上限后不再显示**再连接一个**,更早生成的链接会被机器人拒绝并说明原因。新聊天会通知该用户的其他聊天(“又连接了一个 Telegram,如果不是您本人,请断开”)。 +- 任何更改(链接、取消、断开、开关)都计入页面其他操作共用的每小时限额(每个客户端网络 20 次,每个链接 100 次);页面等待 Telegram 时对该块的读取不计入。与链接下的其他调用一样,需要页面密码。 +- 页面只会得到机器人的用户名、每个聊天的行 ID、语言、日期和公告是否开启,永远得不到 Telegram 聊天 ID 或机器人令牌。审计日志中有 `user_telegram_link_begin`、`user_telegram_link_cancel`、`user_telegram_unlink` 和 `user_telegram_mute`,带有该用户的 ID。 + +**隐私。** 连接聊天会把用户与一个 Telegram 账号关联起来:面板保存这一关联(聊天 ID 已加密),Telegram 会看到该账号在与服务的机器人通信。机器人使用中性的名称和措辞,从不发送链接,也不索取任何信息。请不要向在意“Telegram 账号与自己使用本服务相关联”的人推荐这一功能(例如账号登记了本人姓名和号码,而使用服务的地方存在风险),也不要劝说:页面只是询问,选择权在用户。 + ## DNS 所有者开启**页面上的 DNS 选择**后(见下文),用户可以在自己的页面上选择: diff --git a/internal/panel/access/sub.go b/internal/panel/access/sub.go index 8295f920d..b0038dbee 100644 --- a/internal/panel/access/sub.go +++ b/internal/panel/access/sub.go @@ -66,6 +66,9 @@ type SubView struct { // AppAmnezia is the user's AmneziaVPN toggle alone (AccessAmnezia also needs a live inbound and an active user): a person // whose subscription ended still sees the keys they hold and can remove them. AppAmnezia, AppTelegram, AppTrustTunnel bool + // NotifyBot is the username of the bot the person can link a Telegram chat to ("" = none: the page has no such block). Only the + // page's own view carries it. + NotifyBot string // AppMistgateOff is the person's Mistgate app switch, off: a client API sync of one of their devices carries no servers. AppMistgateOff bool // Nodes are the servers of the person, one per node, in subscription order: the ones a link carries and the ones a key @@ -442,6 +445,9 @@ func (s *Service) subView(ctx context.Context, u store.AccessUser, touch bool, o if hook := s.snapshotHookForTest; hook != nil { hook() } + if !opt.NoPageData { + v.NotifyBot, _ = s.st.UserTelegramBotUsername(ctx) // a bot that cannot be read is no block on the page, not a page that fails + } made := make(map[string]int, len(data.Inbounds)) // the store returns creation order: SubServer.Made for i, f := range data.Inbounds { made[f.Inbound.ID] = i diff --git a/internal/panel/access/user_telegram.go b/internal/panel/access/user_telegram.go new file mode 100644 index 000000000..679763e30 --- /dev/null +++ b/internal/panel/access/user_telegram.go @@ -0,0 +1,120 @@ +package access + +import ( + "context" + "errors" + "time" + + "github.com/mistgate/mistgate/internal/panel/store" +) + +// The notifications to the person in Telegram, as the person's own page sees them (subs/telegram.go): which bot, the chats the +// person linked, the one-time link and the switches. The page only ever gets the row id of a chat, its language, when it was linked +// and whether announcements are on: never the Telegram chat id, its ciphertext or MAC, or the token. A person acts on their own +// chats only: every row is looked up with the user id of the link. The link code, the limit and the hash are the store's (the people's +// bot itself, package telegram, is not part of the Workers that serve the page). + +// PageTelegramChat is one chat of the person, as the page shows it. +type PageTelegramChat struct { + ID string + Lang string + Muted bool // announcements are off + LinkedAt time.Time +} + +// PageTelegramState is what the block of the page draws: Bot is "" when there is no bot to link to (the block is hidden). +type PageTelegramState struct { + Bot string + Limit int + Chats []PageTelegramChat + ExpiresIn time.Duration // how long the pending link still works, rounded up to a second; 0: none waits +} + +// PageTelegramState reads the block of a person. +func (s *Service) PageTelegramState(ctx context.Context, userID string) (PageTelegramState, error) { + var out PageTelegramState + bot, err := s.st.UserTelegramBotUsername(ctx) + if err != nil { + return out, s.internal("read people's bot", err) + } + if bot == "" { + return out, nil + } + chats, err := s.st.UserTelegramChats(ctx, userID) + if err != nil { + return out, s.internal("list people's chats", err) + } + out.Bot, out.Limit, out.Chats = bot, s.st.UserTelegramChatLimit(ctx, userID), make([]PageTelegramChat, 0, len(chats)) + for _, c := range chats { + out.Chats = append(out.Chats, PageTelegramChat{ID: c.ID, Lang: c.Lang, Muted: c.Muted, LinkedAt: c.LinkedAt}) + } + now := s.now() + switch exp, err := s.st.UserTelegramCodeExpiry(ctx, userID, now); { + case err == nil: + out.ExpiresIn = exp.Sub(now).Truncate(time.Second) + time.Second + case !errors.Is(err, store.ErrNotFound): + return out, s.internal("read people's link code", err) + } + return out, nil +} + +// BeginPageTelegramLink makes a fresh one-time link for the person and returns its t.me address. A person who has as many chats as +// the limit allows gets "chat_limit" and nothing is made; no bot is "no_bot". +func (s *Service) BeginPageTelegramLink(ctx context.Context, by, userID string) (string, error) { + bot, err := s.st.UserTelegramBotUsername(ctx) + if err != nil { + return "", s.internal("read people's bot", err) + } + if bot == "" { + return "", failed("no_bot") + } + n, err := s.st.CountUserTelegramChats(ctx, userID) + if err != nil { + return "", s.internal("count people's chats", err) + } + if limit := s.st.UserTelegramChatLimit(ctx, userID); n >= limit { + return "", failed("chat_limit: %d", limit) + } + code, _, err := s.st.NewUserTelegramCode(ctx, userID, s.now()) + if err != nil { + return "", s.internal("create people's link code", err) + } + s.audit(ctx, by, "user_telegram_link_begin", map[string]any{"user_id": userID}) + return "https://t.me/" + bot + "?start=" + code, nil +} + +// CancelPageTelegramLink withdraws the pending link of the person. +func (s *Service) CancelPageTelegramLink(ctx context.Context, by, userID string) error { + had, err := s.st.DeleteUserTelegramCode(ctx, userID) + if err != nil { + return s.internal("cancel people's link code", err) + } + if had { + s.audit(ctx, by, "user_telegram_link_cancel", map[string]any{"user_id": userID}) + } + return nil +} + +// UnlinkPageTelegramChat disconnects one chat of the person; a chat that is gone (or is not theirs) is not an error, the answer is the same. +func (s *Service) UnlinkPageTelegramChat(ctx context.Context, by, userID, chat string) error { + had, err := s.st.UnlinkUserTelegramChat(ctx, userID, chat) + if err != nil { + return s.internal("unlink people's chat", err) + } + if had { + s.audit(ctx, by, "user_telegram_unlink", map[string]any{"user_id": userID, "by": "user"}) + } + return nil +} + +// MutePageTelegramChat switches the announcements of one chat of the person off (muted) or on. +func (s *Service) MutePageTelegramChat(ctx context.Context, by, userID, chat string, muted bool) error { + switch err := s.st.SetUserTelegramChatMuted(ctx, userID, chat, muted); { + case errors.Is(err, store.ErrNotFound): + return notFound("chat") + case err != nil: + return s.internal("mute people's chat", err) + } + s.audit(ctx, by, "user_telegram_mute", map[string]any{"user_id": userID, "muted": muted}) + return nil +} diff --git a/internal/panel/store/user_telegram.go b/internal/panel/store/user_telegram.go index 0e1e2c3bc..8d45233a9 100644 --- a/internal/panel/store/user_telegram.go +++ b/internal/panel/store/user_telegram.go @@ -2,8 +2,14 @@ package store import ( "context" + "crypto/rand" + "crypto/sha256" "database/sql" + "encoding/base32" + "encoding/hex" "errors" + "strconv" + "strings" "time" ) @@ -325,3 +331,79 @@ func (s *Store) UserTelegramCodeExpiry(ctx context.Context, user string, now tim func (s *Store) DeleteUserTelegramCode(ctx context.Context, user string) (bool, error) { return s.deleteUserTelegramChat(ctx, `DELETE FROM user_telegram_code WHERE user_id = ?`, user) } + +// The link code and the chat limit are the store's, not the Telegram package's: the public Worker hands out a link on the page of a +// person (package access) and must not import the bot to do it. + +const ( + // UserTelegramCodeTTL is how long a link code of a person lives. + UserTelegramCodeTTL = 15 * time.Minute + // UserTelegramChatLimitKey is the key of the chat limit in user_notify_setting (everybody) and user_notify_override (one person). + UserTelegramChatLimitKey = "telegram_chat_limit" + // MaxUserTelegramChatLimit is the largest chat limit that can be set. + MaxUserTelegramChatLimit = 10 +) + +// UserTelegramCodeHash is what is stored of a link code: the hex of its SHA-256. +func UserTelegramCodeHash(code string) string { + h := sha256.Sum256([]byte(strings.TrimSpace(code))) + return hex.EncodeToString(h[:]) +} + +// NewUserTelegramCode makes the one-time link code of a person (26 characters of base32: 130 bits, so 128 bits of entropy) that +// lives UserTelegramCodeTTL from now. A new code replaces the person's earlier one. Only its hash is stored. +func (s *Store) NewUserTelegramCode(ctx context.Context, user string, now time.Time) (code string, expires time.Time, err error) { + var raw [16]byte + if _, err := rand.Read(raw[:]); err != nil { + return "", time.Time{}, err + } + code = strings.ToLower(base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(raw[:])) + expires = now.Add(UserTelegramCodeTTL) + if err := s.SetUserTelegramCode(ctx, UserTelegramCodeHash(code), user, expires); err != nil { + return "", time.Time{}, err + } + return code, expires, nil +} + +// UserTelegramChatLimits is the limit of everybody (the setting, or the default) and the person's own (0 when there is none). +func (s *Store) UserTelegramChatLimits(ctx context.Context, user string) (global, own int) { + global = DefaultUserTelegramChatLimit + if all, err := s.UserNotifySettings(ctx); err == nil { + if n, ok := UserTelegramLimitValue(all[UserTelegramChatLimitKey]); ok { + global = n + } + } + if user != "" { + if ov, err := s.UserNotifyOverrides(ctx, user); err == nil { + own, _ = UserTelegramLimitValue(ov[UserTelegramChatLimitKey]) + } + } + return global, own +} + +// UserTelegramChatLimit is how many chats a person may link. +func (s *Store) UserTelegramChatLimit(ctx context.Context, user string) int { + global, own := s.UserTelegramChatLimits(ctx, user) + if own > 0 { + return own + } + return global +} + +// UserTelegramLimitValue reads a stored limit (a JSON number); ok is false for none or one out of range. +func UserTelegramLimitValue(v string) (int, bool) { + n, err := strconv.Atoi(strings.TrimSpace(v)) + return n, err == nil && n >= 1 && n <= MaxUserTelegramChatLimit +} + +// UserTelegramBotUsername is the username of the people's bot as the page of a person offers it: "" when no bot is set, or when it is +// the owner's own (that bot is not polled for the people, so a link to it would never be taken). +func (s *Store) UserTelegramBotUsername(ctx context.Context) (string, error) { + var name string + err := s.R.QueryRowContext(ctx, `SELECT username FROM user_telegram_bot WHERE id = 1 + AND NOT EXISTS (SELECT 1 FROM telegram_bot WHERE id = 1 AND bot_id = user_telegram_bot.bot_id)`).Scan(&name) + if errors.Is(err, sql.ErrNoRows) { + return "", nil + } + return name, err +} diff --git a/internal/panel/subs/notify_tg.go b/internal/panel/subs/notify_tg.go new file mode 100644 index 000000000..bd9864dfa --- /dev/null +++ b/internal/panel/subs/notify_tg.go @@ -0,0 +1,116 @@ +package subs + +import ( + "context" + "net/http" + "strings" + "time" + + "github.com/mistgate/mistgate/internal/panel/access" + "github.com/mistgate/mistgate/internal/panel/subsettings" +) + +// The block "Notifications in Telegram" of the page: a person links a chat of their own to the bot of the notifications and +// manages those chats. Under the subscription link, POST, JSON in and out, behind the page password, the cross-origin check and the +// owner's self-service switch, like the device calls: +// +// POST /telegram {} the block as it is now +// POST /telegram/link {} a fresh one-time link (the pending one stops working) +// POST /telegram/cancel {} withdraw the pending link +// POST /telegram//unlink {} disconnect one chat +// POST /telegram//mute {"muted": bool} announcements of one chat off (true) or on +// +// 200 {"bot": "", "limit": 3, "chats": [{"id","lang","muted","linked_unix"}], "expires_in": 897, "url": "https://t.me/..."} +// +// bot is "" when there is no bot to link to (the page then hides the block); expires_in is how many seconds the pending link +// still works (0: none waits), counted by the panel, so the page does not depend on its own clock; url comes with /link only. +// A change goes through the same hourly budget of writes as the devices; reading the block (the page asks every few seconds while +// it waits for Telegram) does not spend it. Errors: 409 no_bot, 409 chat_limit (the person has as many chats as the limit allows), +// 404 not_found (a chat that is not theirs, for /mute). A person never gets the Telegram chat id of a chat, only its row id. + +// PageTelegram is what the endpoints call; *access.Service implements it. A Source that does not leaves them off. +type PageTelegram interface { + PageTelegramState(ctx context.Context, userID string) (access.PageTelegramState, error) + BeginPageTelegramLink(ctx context.Context, by, userID string) (string, error) + CancelPageTelegramLink(ctx context.Context, by, userID string) error + UnlinkPageTelegramChat(ctx context.Context, by, userID, chat string) error + MutePageTelegramChat(ctx context.Context, by, userID, chat string, muted bool) error +} + +// pageTGNotify is the part of the page data that switches the block on: it is there only when a bot is set, the owner allows +// self-service and the page can write. +type pageTGNotify struct { + Endpoint string `json:"endpoint"` +} + +type tgChatJSON struct { + ID string `json:"id"` + Lang string `json:"lang"` + Muted bool `json:"muted"` + LinkedUnix int64 `json:"linked_unix"` +} + +type tgAnswer struct { + Bot string `json:"bot"` + Limit int `json:"limit"` + Chats []tgChatJSON `json:"chats"` + ExpiresIn int `json:"expires_in"` + URL string `json:"url,omitempty"` +} + +func (h *handler) serveTelegram(w http.ResponseWriter, r *http.Request, token, sub, client string, now time.Time) { + ctx := r.Context() + v, _, ok := h.enter(w, r, token, client, now, h.ptg != nil, subsettings.SelfService, "self_service_disabled") + if !ok { + return + } + var chat, action string + switch rest := strings.TrimPrefix(strings.TrimPrefix(sub, "telegram"), "/"); { + case sub == "telegram": + case rest == "link" || rest == "cancel": + action = rest + default: + id, act, found := strings.Cut(rest, "/") + if !found || !validDeviceID(id) || (act != "unlink" && act != "mute") { + jsonError(w, http.StatusNotFound, "not_found", "") + return + } + chat, action = id, act + } + var in struct { + Muted bool `json:"muted"` + } + if !readJSON(w, r, &in) { + return + } + // reading the block is free; a change is a write of the page + if action != "" && !h.admitWrite(ctx, w, token, client, v, false) { + return + } + by, url := "user:"+v.UserID, "" + var err error + switch action { + case "link": + url, err = h.ptg.BeginPageTelegramLink(ctx, by, v.UserID) + case "cancel": + err = h.ptg.CancelPageTelegramLink(ctx, by, v.UserID) + case "unlink": + err = h.ptg.UnlinkPageTelegramChat(ctx, by, v.UserID, chat) + case "mute": + err = h.ptg.MutePageTelegramChat(ctx, by, v.UserID, chat, in.Muted) + } + if err != nil { + writeAccessError(w, err) + return + } + s, err := h.ptg.PageTelegramState(ctx, v.UserID) + if err != nil { + writeAccessError(w, err) + return + } + out := tgAnswer{Bot: s.Bot, Limit: s.Limit, Chats: make([]tgChatJSON, 0, len(s.Chats)), ExpiresIn: int(s.ExpiresIn / time.Second), URL: url} + for _, c := range s.Chats { + out.Chats = append(out.Chats, tgChatJSON{ID: c.ID, Lang: c.Lang, Muted: c.Muted, LinkedUnix: c.LinkedAt.Unix()}) + } + writeJSON(w, http.StatusOK, out) +} diff --git a/internal/panel/subs/notify_tg_test.go b/internal/panel/subs/notify_tg_test.go new file mode 100644 index 000000000..3529fff0e --- /dev/null +++ b/internal/panel/subs/notify_tg_test.go @@ -0,0 +1,251 @@ +package subs_test + +import ( + "encoding/json" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/mistgate/mistgate/internal/panel/store" + "github.com/mistgate/mistgate/internal/panel/subs" + "github.com/mistgate/mistgate/internal/panel/subsettings" +) + +// The block "Notifications in Telegram" of the page, against the real access module and database: it exists only with a bot that is +// not the owner's, behind the page password and the self-service switch; a person reaches their own chats only and never the Telegram +// chat id; a link is one code, held as a hash; the chat limit counts. + +type tgAnswerBody struct { + Bot string `json:"bot"` + Limit int `json:"limit"` + ExpiresIn int `json:"expires_in"` + URL string `json:"url"` + Error string `json:"error"` + Chats []struct { + ID string `json:"id"` + Lang string `json:"lang"` + Muted bool `json:"muted"` + LinkedUnix int64 `json:"linked_unix"` + } `json:"chats"` +} + +func tgBody(t *testing.T, rec *httptest.ResponseRecorder) tgAnswerBody { + t.Helper() + var a tgAnswerBody + if err := json.Unmarshal(rec.Body.Bytes(), &a); err != nil { + t.Fatalf("not JSON (%d): %v %q", rec.Code, err, rec.Body.String()) + } + return a +} + +func (g *gate) setUserBot(t *testing.T, botID int64) { + t.Helper() + if _, err := g.st.SetUserTelegramBot(g.ctx, store.UserTelegramBot{Token: []byte("sealed"), BotID: botID, Username: "example_people_bot"}, time.Now()); err != nil { + t.Fatal(err) + } +} + +// chat links a chat to a person straight in the store (what the bot does when the person sends /start); enc stands for the sealed id. +func (g *gate) chat(t *testing.T, user, mac string) { + t.Helper() + if err := g.st.LinkUserTelegramChat(g.ctx, user, []byte(mac), []byte("SEALED-"+mac), "ru", 10, time.Now()); err != nil { + t.Fatal(err) + } +} + +func TestTelegramBlockOfThePage(t *testing.T) { + g := newGate(t, func(c *subs.Config) { c.MinInterval = -1 }) + uid, tok := g.newUser("alice", nil) + other, otherTok := g.newUser("bob", nil) + cookie := ck(cookieOf(t, g.unlock(t, tok, g.password(uid)))) + otherCookie := ck(cookieOf(t, g.unlock(t, otherTok, g.password(other)))) + c, oc := call{g.h, t, tok}, call{g.h, t, otherTok} + tgNotify := func() any { return dataOf(t, g.page(tok, "Cookie", cookie))["tg_notify"] } + + // no bot: no block, and the calls say so + if tgNotify() != nil { + t.Error("the page offers the block without a bot") + } + if a := tgBody(t, c.post("/telegram", "{}", "Cookie", cookie)); a.Bot != "" || len(a.Chats) != 0 { + t.Errorf("state without a bot: %+v", a) + } + if rec := c.post("/telegram/link", "{}", "Cookie", cookie); rec.Code != 409 || tgBody(t, rec).Error != "no_bot" { + t.Errorf("a link without a bot: %d %s", rec.Code, rec.Body) + } + + // the owner's own bot is not the people's bot: a link to it would never be taken + if _, err := g.st.W.Exec(`INSERT INTO telegram_bot (id, token, bot_id, username, updated_at) VALUES (1, x'00', 7, 'owner_bot', 1)`); err != nil { + t.Fatal(err) + } + g.setUserBot(t, 7) + if tgNotify() != nil { + t.Error("the page offers the owner's own bot") + } + g.setUserBot(t, 8) + n, _ := tgNotify().(map[string]any) + if n == nil || !strings.HasSuffix(n["endpoint"].(string), "/"+tok+"/telegram") { + t.Fatalf("tg_notify = %v", n) + } + + // behind the page password: no cookie, no block + if rec := c.post("/telegram", "{}"); rec.Code != 401 || tgBody(t, rec).Error != "locked" { + t.Errorf("without the cookie: %d %s", rec.Code, rec.Body) + } + if d := dataOf(t, g.page(tok)); d["tg_notify"] != nil || d["locked"] != true { + t.Errorf("a locked page carries the block: %v", d["tg_notify"]) + } + + st := tgBody(t, c.post("/telegram", "{}", "Cookie", cookie)) + if st.Bot != "example_people_bot" || st.Limit != 3 || st.ExpiresIn != 0 || len(st.Chats) != 0 { + t.Fatalf("state: %+v", st) + } + + // a link: one code, held as its hash, 15 minutes + rec := c.post("/telegram/link", "{}", "Cookie", cookie) + a := tgBody(t, rec) + code, ok := strings.CutPrefix(a.URL, "https://t.me/example_people_bot?start=") + if rec.Code != 200 || !ok || len(code) != 26 || a.ExpiresIn < 890 || a.ExpiresIn > 900 { + t.Fatalf("link: %d %s", rec.Code, rec.Body) + } + if got := tgBody(t, c.post("/telegram", "{}", "Cookie", cookie)); got.ExpiresIn < 890 || got.URL != "" { + t.Errorf("state while it waits: %+v", got) + } + var held string + if err := g.st.R.QueryRow(`SELECT hash FROM user_telegram_code WHERE user_id = ?`, uid).Scan(&held); err != nil || held == code || held != store.UserTelegramCodeHash(code) { + t.Errorf("the code is not held as its hash: %q (%v)", held, err) + } + if who, err := g.st.TakeUserTelegramCode(g.ctx, store.UserTelegramCodeHash(code), time.Now()); err != nil || who != uid { + t.Errorf("the code belongs to %q (%v), want the person", who, err) + } + if got := tgBody(t, c.post("/telegram", "{}", "Cookie", cookie)); got.ExpiresIn != 0 { + t.Errorf("a taken code still waits: %+v", got) + } + + // the bot links two chats: the page lists them without any id of Telegram + g.chat(t, uid, "aa") + g.chat(t, uid, "bb") + g.chat(t, other, "cc") + rec = c.post("/telegram", "{}", "Cookie", cookie) + if strings.Contains(rec.Body.String(), "SEALED") || strings.Contains(rec.Body.String(), "mac") { + t.Errorf("the answer carries chat material: %s", rec.Body) + } + st = tgBody(t, rec) + if len(st.Chats) != 2 || st.Chats[0].Lang != "ru" || st.Chats[0].Muted || !strings.HasPrefix(st.Chats[0].ID, "utc_") || st.Chats[0].LinkedUnix == 0 { + t.Fatalf("chats: %+v", st.Chats) + } + mine, foreign := st.Chats[0].ID, tgBody(t, oc.post("/telegram", "{}", "Cookie", otherCookie)).Chats[0].ID + + // announcements of one chat; a chat that is not theirs is not found, and stays as it was + if a := tgBody(t, c.post("/telegram/"+mine+"/mute", `{"muted":true}`, "Cookie", cookie)); !a.Chats[0].Muted || st.Chats[1].Muted { + t.Errorf("mute: %+v", a.Chats) + } + if a := tgBody(t, c.post("/telegram/"+mine+"/mute", `{"muted":false}`, "Cookie", cookie)); a.Chats[0].Muted { + t.Errorf("unmute: %+v", a.Chats) + } + if rec := c.post("/telegram/"+foreign+"/mute", `{"muted":true}`, "Cookie", cookie); rec.Code != 404 { + t.Errorf("another person's chat: %d %s", rec.Code, rec.Body) + } + if rec := c.post("/telegram/"+foreign+"/unlink", "{}", "Cookie", cookie); rec.Code != 200 || len(tgBody(t, rec).Chats) != 2 { + t.Errorf("unlinking another person's chat: %d %s", rec.Code, rec.Body) + } + if left := tgBody(t, oc.post("/telegram", "{}", "Cookie", otherCookie)).Chats; len(left) != 1 || left[0].Muted { + t.Errorf("the other person's chat was touched: %+v", left) + } + if rec := c.post("/telegram/not-a-chat!/mute", `{}`, "Cookie", cookie); rec.Code != 404 { + t.Errorf("a malformed chat id: %d", rec.Code) + } + if rec := c.post("/telegram/"+mine+"/wipe", "{}", "Cookie", cookie); rec.Code != 404 { + t.Errorf("an unknown action: %d", rec.Code) + } + + // the limit: the person's own wins, and a link is refused before a code is made + if err := g.st.SetUserNotifyOverride(g.ctx, uid, store.UserTelegramChatLimitKey, "2"); err != nil { + t.Fatal(err) + } + if rec := c.post("/telegram/link", "{}", "Cookie", cookie); rec.Code != 409 || tgBody(t, rec).Error != "chat_limit" { + t.Errorf("a link at the limit: %d %s", rec.Code, rec.Body) + } + if _, err := g.st.UserTelegramCodeExpiry(g.ctx, uid, time.Now()); err == nil { + t.Error("a refused link left a code") + } + + // unlink one, then a link, then cancel it + if a := tgBody(t, c.post("/telegram/"+mine+"/unlink", "{}", "Cookie", cookie)); len(a.Chats) != 1 || a.Limit != 2 { + t.Errorf("unlink: %+v", a) + } + if rec := c.post("/telegram/"+mine+"/unlink", "{}", "Cookie", cookie); rec.Code != 200 { + t.Errorf("unlinking a chat that is gone: %d", rec.Code) + } +} + +// A change is a write of the page and spends its hourly budget; reading the block (the page does it every few seconds while it waits +// for Telegram) does not. +func TestTelegramBlockReadsAreFree(t *testing.T) { + g := newGate(t, func(c *subs.Config) { c.MinInterval = -1; c.MaxWritesPerHour = 2 }) + uid, tok := g.newUser("alice", nil) + cookie := ck(cookieOf(t, g.unlock(t, tok, g.password(uid)))) + c := call{g.h, t, tok} + g.setUserBot(t, 8) + for i := 0; i < 10; i++ { + if rec := c.post("/telegram", "{}", "Cookie", cookie); rec.Code != 200 { + t.Fatalf("read %d: %d %s", i, rec.Code, rec.Body) + } + } + for _, p := range []string{"/telegram/link", "/telegram/cancel"} { + if rec := c.post(p, "{}", "Cookie", cookie); rec.Code != 200 { + t.Fatalf("%s: %d %s", p, rec.Code, rec.Body) + } + } + if rec := c.post("/telegram/link", "{}", "Cookie", cookie); rec.Code != 429 || rec.Header().Get("Retry-After") == "" { + t.Errorf("over the budget of writes: %d %s", rec.Code, rec.Body) + } +} + +func TestTelegramBlockCancelAndSwitches(t *testing.T) { + g := newGate(t, func(c *subs.Config) { c.MinInterval = -1 }) + uid, tok := g.newUser("alice", nil) + cookie := ck(cookieOf(t, g.unlock(t, tok, g.password(uid)))) + c := call{g.h, t, tok} + g.setUserBot(t, 8) + + if a := tgBody(t, c.post("/telegram/link", "{}", "Cookie", cookie)); a.ExpiresIn == 0 { + t.Fatalf("link: %+v", a) + } + if a := tgBody(t, c.post("/telegram/cancel", "{}", "Cookie", cookie)); a.ExpiresIn != 0 || a.URL != "" { + t.Errorf("cancel: %+v", a) + } + for _, action := range []string{"user_telegram_link_begin", "user_telegram_link_cancel"} { + var n int + if err := g.st.R.QueryRow(`SELECT count(*) FROM audit WHERE action = ? AND actor = ? AND params LIKE ?`, action, "user:"+uid, `%"user_id":"`+uid+`"%`).Scan(&n); err != nil || n != 1 { + t.Errorf("audit of %s: %d (%v)", action, n, err) + } + } + if rec := c.post("/telegram", `{"x":1}`, "Cookie", cookie); rec.Code != 400 { + t.Errorf("an unknown field: %d", rec.Code) + } + if rec := c.post("/telegram", "{}", "Cookie", cookie, "Sec-Fetch-Site", "cross-site"); rec.Code != 403 { + t.Errorf("another origin: %d", rec.Code) + } + if rec := fetch(g.h, "/"+tok+"/telegram", chrome, "Cookie", cookie); rec.Code == 200 && strings.Contains(rec.Body.String(), "example_people_bot") { + t.Error("GET answers the block") + } + + // the owner switches self-service off: the block goes, the calls refuse + set := subsettings.Defaults() + set.UserPage.AllowDeviceSelfService = new(bool) + if _, err := g.cache.Update(g.ctx, set); err != nil { + t.Fatal(err) + } + if rec := c.post("/telegram", "{}", "Cookie", cookie); rec.Code != 403 || tgBody(t, rec).Error != "self_service_disabled" { + t.Errorf("switched off: %d %s", rec.Code, rec.Body) + } + if dataOf(t, g.page(tok, "Cookie", cookie))["tg_notify"] != nil { + t.Error("the page offers the block with self-service off") + } + + // an unknown link gets the decoy, not an answer about a bot + if rec := (call{g.h, t, strings.Repeat("z", 43)}).post("/telegram", "{}"); rec.Body.String() != decoyBody { + t.Errorf("an unknown token: %d %s", rec.Code, rec.Body) + } +} diff --git a/internal/panel/subs/page.go b/internal/panel/subs/page.go index 6c2958380..c36f89f26 100644 --- a/internal/panel/subs/page.go +++ b/internal/panel/subs/page.go @@ -115,8 +115,11 @@ type pageData struct { DevicesEndpoint string `json:"devices_endpoint"` // LinkDeviceLimit is the mode of the device limit for the apps on the link: "track" (counted, nobody refused), "enforce" or // "strict" (the apps that report no device ID are refused). The page words the shared place and the full limit by it. - LinkDeviceLimit string `json:"link_device_limit"` - Amnezia *pageAmnezia `json:"amnezia"` // null unless the user has the Amnezia app and a usable AWG profile (or keys to remove) + LinkDeviceLimit string `json:"link_device_limit"` + // TGNotify switches on the block "Notifications in Telegram": null when there is no bot to link to, self-service is off or the page + // cannot write (see notify_tg.go). + TGNotify *pageTGNotify `json:"tg_notify"` + Amnezia *pageAmnezia `json:"amnezia"` // null unless the user has the Amnezia app and a usable AWG profile (or keys to remove) // Servers are the person's servers, one per node; DNS and DNSPresets are the choice of DNS for each of them. Servers []pageNode `json:"servers"` DNS pageDNS `json:"dns"` @@ -286,6 +289,9 @@ func buildPageData(v access.SubView, link, title, lang string, set *adminv1.Subs if opt.GetShowQr() { d.QR = pageQROf(link) } + if v.NotifyBot != "" && subsettings.SelfService(set) && !preview && link != "" { + d.TGNotify = &pageTGNotify{Endpoint: link + "/telegram"} + } d.Amnezia = amneziaData(v, link, subsettings.SelfService(set), subsettings.RUDirect(set), preview, now) if v.AppTelegram { d.Telegram = pageTelegramOf(v, lang) diff --git a/internal/panel/subs/subs.go b/internal/panel/subs/subs.go index 26f844122..022dc0a5a 100644 --- a/internal/panel/subs/subs.go +++ b/internal/panel/subs/subs.go @@ -288,6 +288,7 @@ type handler struct { fsrc FormatSource // src when it can render a format, else nil dev Devices // src when it manages devices, else nil pdns PageDNS // src when it takes the DNS pick of the page, else nil + ptg PageTelegram // src when it serves the Telegram notifications block of the page, else nil enrol ClientEnrol // src when it enrols client API devices, else nil client ClientAPI // src when it serves client API sync and leave, else nil cop *http.CrossOriginProtection @@ -315,6 +316,7 @@ func Handler(src Source, decoy http.Handler, cfg Config) http.Handler { h.fsrc, _ = src.(FormatSource) h.dev, _ = src.(Devices) h.pdns, _ = src.(PageDNS) + h.ptg, _ = src.(PageTelegram) h.enrol, _ = src.(ClientEnrol) h.client, _ = src.(ClientAPI) readers := cfg.ClientDebugReaders @@ -403,6 +405,9 @@ func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { case sub == "probe": h.serveProbe(w, r, token, client, now) return + case sub == "telegram" || strings.HasPrefix(sub, "telegram/"): + h.serveTelegram(w, r, token, sub, client, now) + return case sub == "client/enrol": h.serveEnrol(w, r, token, client, now) return @@ -1025,7 +1030,7 @@ func (h *handler) suspect(user string) { } // routeOf splits a request under the prefix into the token and what follows it: GET/HEAD / is the -// subscription itself (sub ""), POST //devices[//] a self-service call (sub "devices..."), POST //dns the pick of a DNS (sub "dns"), POST //unlock the page password, +// subscription itself (sub ""), POST //devices[//] a self-service call (sub "devices..."), POST //dns the pick of a DNS (sub "dns"), POST //telegram[/...] the notifications block (sub "telegram..."), POST //unlock the page password, // POST //probe a report of the kl!ck probe. // Anything else is not ours (ok false). func routeOf(r *http.Request, prefix string) (token, sub string, ok bool) { @@ -1050,7 +1055,7 @@ func routeOf(r *http.Request, prefix string) (token, sub string, ok bool) { switch { case sub == "" && (r.Method == http.MethodGet || r.Method == http.MethodHead): return token, "", true - case r.Method == http.MethodPost && (sub == "unlock" || sub == "dns" || sub == "probe" || sub == "client/enrol" || sub == "devices" || strings.HasPrefix(sub, "devices/")): + case r.Method == http.MethodPost && (sub == "unlock" || sub == "dns" || sub == "probe" || sub == "client/enrol" || sub == "devices" || sub == "telegram" || strings.HasPrefix(sub, "telegram/") || strings.HasPrefix(sub, "devices/")): return token, sub, true } return "", "", false diff --git a/internal/panel/telegram/user_bot.go b/internal/panel/telegram/user_bot.go index 9f8feb529..86188ca6e 100644 --- a/internal/panel/telegram/user_bot.go +++ b/internal/panel/telegram/user_bot.go @@ -3,9 +3,7 @@ package telegram import ( "context" "crypto/hmac" - "crypto/rand" "crypto/sha256" - "encoding/base32" "encoding/hex" "errors" "strconv" @@ -26,11 +24,9 @@ import ( const ( userTokenRecordID = "user_telegram_bot.token" - userLinkCodeTTL = 15 * time.Minute userPollLease = "user-telegram-poll" - // userChatLimitKey is the key of the chat limit in user_notify_setting (everybody) and user_notify_override (one person). - userChatLimitKey = "telegram_chat_limit" - maxChatLimit = 10 + userChatLimitKey = store.UserTelegramChatLimitKey + maxChatLimit = store.MaxUserTelegramChatLimit ) // The state of the bot of the people, what GetUserBot says (and what user_telegram_bot.last_error holds, bar "ok"). @@ -267,7 +263,7 @@ func (s *Service) linkUserChat(ctx context.Context, tok vault.Redacted, m tgMess if linked { lang = chat.Lang // an answer to a chat that is known follows its own language, not what the client says today } - user, err := s.st.TakeUserTelegramCode(ctx, codeHash(code), s.now()) + user, err := s.st.TakeUserTelegramCode(ctx, store.UserTelegramCodeHash(code), s.now()) switch { case errors.Is(err, store.ErrNotFound): s.userReply(ctx, tok, m.Chat.ID, mac, userBadCode.in(lang)) @@ -341,48 +337,20 @@ func (s *Service) userReply(ctx context.Context, tok vault.Redacted, chat int64, // ---- link codes and the chat limit -// newUserCode makes the one-time code of a person (26 characters of base32: 130 bits, so 128 bits of entropy) that lives -// userLinkCodeTTL. A new code replaces the person's earlier one. Only its hash is stored. +// newUserCode makes the one-time code of a person (the store's: the page of the person makes one too). func (s *Service) newUserCode(ctx context.Context, user string) (code string, expires time.Time, err error) { - var raw [16]byte - if _, err := rand.Read(raw[:]); err != nil { - return "", time.Time{}, err - } - code = strings.ToLower(base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(raw[:])) - expires = s.now().Add(userLinkCodeTTL) - if err := s.st.SetUserTelegramCode(ctx, codeHash(code), user, expires); err != nil { - return "", time.Time{}, err - } - return code, expires, nil + return s.st.NewUserTelegramCode(ctx, user, s.now()) } // userChatLimits is the limit of everybody (the setting, or the default) and the person's own (0 when there is none). func (s *Service) userChatLimits(ctx context.Context, user string) (global, own int) { - global = store.DefaultUserTelegramChatLimit - if all, err := s.st.UserNotifySettings(ctx); err == nil { - if n, ok := limitValue(all[userChatLimitKey]); ok { - global = n - } - } - if user != "" { - if ov, err := s.st.UserNotifyOverrides(ctx, user); err == nil { - own, _ = limitValue(ov[userChatLimitKey]) - } - } - return global, own + return s.st.UserTelegramChatLimits(ctx, user) } // userChatLimit is how many chats a person may link. func (s *Service) userChatLimit(ctx context.Context, user string) int { - global, own := s.userChatLimits(ctx, user) - if own > 0 { - return own - } - return global + return s.st.UserTelegramChatLimit(ctx, user) } // limitValue reads a stored limit (a JSON number); ok is false for none or one out of range. -func limitValue(v string) (int, bool) { - n, err := strconv.Atoi(strings.TrimSpace(v)) - return n, err == nil && n >= 1 && n <= maxChatLimit -} +func limitValue(v string) (int, bool) { return store.UserTelegramLimitValue(v) } diff --git a/web/src/sub/api.ts b/web/src/sub/api.ts index 881c16614..bcb45d786 100644 --- a/web/src/sub/api.ts +++ b/web/src/sub/api.ts @@ -1,5 +1,5 @@ -import { awgConfig, awgDevice, linkDns, serverEntry } from "./logic"; -import type { AwgConfig, AwgDevice, LinkDns, ServerEntry } from "./types"; +import { awgConfig, awgDevice, linkDns, serverEntry, tgInfo } from "./logic"; +import type { AwgConfig, AwgDevice, LinkDns, ServerEntry, TgInfo } from "./types"; // The self-service calls of the Amnezia section (subs/devices.go): POST, JSON in and out, under the subscription link. // The page only ever talks to its own origin (CSP connect-src 'self'): the address in the page data is reduced to its @@ -89,3 +89,13 @@ export const setDns = async (url: string, body: { server: string; preset: string stale_devices: Array.isArray(j.stale_devices) ? j.stale_devices.filter((x): x is string => typeof x === "string") : [], }; }; + +/** + * The notifications block (subs/notify_tg.go), under the page's ".../telegram" address. Every call answers the block as it is now; + * the link comes with `tgLink` only. + */ +export const tgState = async (url: string): Promise => tgInfo(await post(url, "", {})); +export const tgLink = async (url: string): Promise => tgInfo(await post(url, "/link", {})); +export const tgCancel = async (url: string): Promise => tgInfo(await post(url, "/cancel", {})); +export const tgUnlink = async (url: string, chat: string): Promise => tgInfo(await post(url, `/${encodeURIComponent(chat)}/unlink`, {})); +export const tgMute = async (url: string, chat: string, muted: boolean): Promise => tgInfo(await post(url, `/${encodeURIComponent(chat)}/mute`, { muted })); diff --git a/web/src/sub/dev-data.ts b/web/src/sub/dev-data.ts index dd713f63e..f26202f3b 100644 --- a/web/src/sub/dev-data.ts +++ b/web/src/sub/dev-data.ts @@ -173,6 +173,7 @@ const base: MgData = { servers: [fra, ams, hel], dns: dnsOn, dns_presets: presets, + tg_notify: null, user: { name: "Alice", status: "active", diff --git a/web/src/sub/dev-scene.test.ts b/web/src/sub/dev-scene.test.ts index 49ec6ff36..ebbdf0faf 100644 --- a/web/src/sub/dev-scene.test.ts +++ b/web/src/sub/dev-scene.test.ts @@ -8,7 +8,7 @@ import { dnsActions } from "./dns-actions"; import { dict } from "./i18n"; import { awgConfig, awgDevice, asPlatform, mainProfile, normalize, safeUrl } from "./logic"; import { lockView, type LockState } from "./lock"; -import { newAmzState, newDnsState, type Actions, type Ctx, type State, type Tab } from "./state"; +import { newAmzState, newDnsState, newTgState, type Actions, type Ctx, type State, type Tab } from "./state"; import { actions, plain, text } from "./test-kit"; import { annKey, openTab, view } from "./view"; @@ -178,6 +178,7 @@ async function open(q: string) { returning: !q.includes("case=first"), amz: newAmzState(here || "other", mainProfile(d.amnezia?.profiles ?? []), here), dns: newDnsState(), + tg: newTgState(), }; const a: Actions = { ...actions(), amz: amzActions({ data: d, st, render: () => {}, api, reveal: () => {}, focus: () => {} }), dns: dnsActions({ data: d, st, render: () => {}, api: dnsApi }) }; devScene(params, d, st, a); diff --git a/web/src/sub/devices.ts b/web/src/sub/devices.ts index 6a024f9b0..7be27269b 100644 --- a/web/src/sub/devices.ts +++ b/web/src/sub/devices.ts @@ -3,6 +3,7 @@ import { h, type Kid } from "./dom"; import { icon, type IconName } from "./icons"; import { countryName, deviceAbout, fmtAgo, isShared, keyAppName, linkFull, otherDevices, platformWord, selfServe } from "./logic"; import type { Ctx } from "./state"; +import { notifySection } from "./notify"; import { connectNeeded } from "./status"; import { copyButton, gap } from "./ui"; import type { AwgDevice, Device } from "./types"; @@ -224,7 +225,8 @@ export function devicesSection(c: Ctx): Kid[] { const list: Kid[][] = own.map((x) => (x.kind === "telegram" ? telegramRow(c, x) : x.kind === "trusttunnel" ? trustTunnelRow(c, x) : linkRow(c, x))); if (shared || (d.access.happ && (strict || own.length === 0))) list.push(sharedRow(c, shared, strict)); if (keys) list.push(...keys.devices.map((x) => keyRow(c, x, serve))); - if (inactive && list.length === 0) return []; + const notify = notifySection(c); + if (inactive && list.length === 0) return notify ? [notify] : []; // a long list folds to three rows, so the page stays short const fold = list.length > 3; const shown = fold && !s.devicesOpen ? list.slice(0, 3) : list; @@ -242,5 +244,6 @@ export function devicesSection(c: Ctx): Kid[] { h("button", { class: "u-btn quiet", type: "button", "data-k": "dev-fold", "aria-expanded": s.devicesOpen, on: { click: () => a.devicesOpen(!s.devicesOpen) } }, s.devicesOpen ? t.lessDevices : t.moreDevices(list.length - 3), icon("chev")), ), ), + notify, ]; } diff --git a/web/src/sub/i18n-notify.ts b/web/src/sub/i18n-notify.ts new file mode 100644 index 000000000..cf92e7da5 --- /dev/null +++ b/web/src/sub/i18n-notify.ts @@ -0,0 +1,226 @@ +import type { Lang } from "./types"; + +// notify: the words of the block "Notifications in Telegram" (notify.ts). Keys are added to `ru`, the board's own words; every other +// language has the same keys (the type is `ru`'s). Functions take plain values. The user is addressed formally («вы»). The example +// messages in the pane beside the block are the texts of the bot itself (internal/panel/telegram/user_texts.go for the welcome, the +// panel's notices for the rest): the bot says them in the chat's language, so the page shows them in its own. + +const minutesRu = (n: number) => { + const r = new Intl.PluralRules("ru").select(n); + return `${n} ${r === "one" ? "минуту" : r === "few" ? "минуты" : "минут"}`; +}; + +const ru = { + tgnT: "Уведомления в Telegram", + tgnP: "Бот напишет, когда подходит конец срока, заканчивается трафик или не работают серверы", + tgnWarn: "Telegram будет знать, что вы пользуетесь этим сервисом", + tgnConnect: "Подключить Telegram", + tgnWait: "Ждём Telegram", + tgnWaitP: (min: number) => `Откройте бота и нажмите «Запустить». Ссылка одноразовая и работает ${minutesRu(min)}`, + tgnLeft: "осталось", + tgnOpen: "Открыть Telegram", + tgnCancel: "Отмена", + tgnExp: "Ссылка устарела", + tgnExpP: (min: number) => `Ссылка работала ${minutesRu(min)} и больше не подойдёт. Получите новую`, + tgnNew: "Новая ссылка", + tgnOn: "Подключено", + tgnOf: (n: number, m: number) => `${n} из ${m}`, + tgnChat: (lang: string) => `Telegram · ${lang}`, + tgnSince: (d: string) => `с ${d}`, + tgnAnn: "Объявления", + tgnOff: "Отключить", + tgnOffAria: (chat: string) => `Отключить: ${chat}`, + tgnMore: "Подключить ещё один", + tgnCmd: "В чате с ботом: /stop — отключить этот чат, /mute — без объявлений", + tgnEx: "Пример", + tgnSilent: "Бот не отвечает: ссылка устарела", + tgnMsgSoon: "Доступ закончится через 3 дня, 14 декабря. Чтобы продлить, напишите тому, кто вас подключил", + tgnMsgQuota: "Потрачено 80% трафика: 80 ГБ из 100 ГБ. Новый период начнётся 1 января", + tgnMsgDown: "Есть проблемы с доступом. Уже чиним, напишем, когда заработает", + tgnMsgWelcome: "Готово, уведомления подключены. Этот бот никогда не присылает ссылок и ничего не спрашивает. /stop — отключить этот чат, /mute — без объявлений", + tgnErr: (c: string, m: number, limit: number) => + ( + { + chat_limit: `Подключено максимум чатов: ${limit}. Отключите один из них и попробуйте снова.`, + no_bot: "Уведомления сейчас недоступны. Напишите тому, кто вас подключил.", + self_service_disabled: "Здесь это выключено владельцем сервиса. Напишите ему.", + too_many_requests: m > 0 ? `Слишком много действий подряд. Попробуйте через ${m} мин.` : "Слишком много действий подряд. Попробуйте позже.", + not_found: "Такого чата уже нет. Обновите страницу.", + network: "Нет связи. Проверьте интернет и повторите.", + locked: "Нужен пароль. Обновите страницу.", + } as Record + )[c] ?? "Не получилось. Попробуйте ещё раз.", +}; + +export type NotifyDict = typeof ru; + +const en: NotifyDict = { + tgnT: "Notifications in Telegram", + tgnP: "The bot will message you when your term is about to end, your traffic runs out, or the servers stop working", + tgnWarn: "Telegram will know you use this service", + tgnConnect: "Connect Telegram", + tgnWait: "Waiting for Telegram", + tgnWaitP: (min) => `Open the bot and press “Start”. The link works once and for ${min} ${min === 1 ? "minute" : "minutes"}`, + tgnLeft: "left", + tgnOpen: "Open Telegram", + tgnCancel: "Cancel", + tgnExp: "Link expired", + tgnExpP: (min) => `The link worked for ${min} ${min === 1 ? "minute" : "minutes"} and will not work any more. Get a new one`, + tgnNew: "New link", + tgnOn: "Connected", + tgnOf: (n, m) => `${n} of ${m}`, + tgnChat: (lang) => `Telegram · ${lang}`, + tgnSince: (d) => `since ${d}`, + tgnAnn: "Announcements", + tgnOff: "Disconnect", + tgnOffAria: (chat) => `Disconnect: ${chat}`, + tgnMore: "Connect another one", + tgnCmd: "In the chat with the bot: /stop disconnects this chat, /mute turns announcements off", + tgnEx: "Example", + tgnSilent: "The bot does not reply: the link has expired", + tgnMsgSoon: "Your access ends in 3 days, on December 14. To extend it, contact the person who set it up for you", + tgnMsgQuota: "You’ve used 80% of your data: 80 GB of 100 GB. A new period starts on January 1", + tgnMsgDown: "There are problems with access. We’re fixing it and will let you know when it works", + tgnMsgWelcome: "Done, notifications are on. This bot never sends links and never asks you for anything. /stop turns off this chat, /mute turns off announcements", + tgnErr: (c, m, limit) => + ( + { + chat_limit: `The most chats are connected already: ${limit}. Disconnect one of them and try again.`, + no_bot: "Notifications are not available right now. Message the person who set you up.", + self_service_disabled: "The owner of the service has turned this off here. Message them.", + too_many_requests: m > 0 ? `Too many actions in a row. Try again in ${m} min.` : "Too many actions in a row. Try again later.", + not_found: "That chat is gone. Refresh the page.", + network: "No connection. Check your internet and try again.", + locked: "A password is needed. Refresh the page.", + } as Record + )[c] ?? "That did not work. Try again.", +}; + +const zh: NotifyDict = { + tgnT: "Telegram 通知", + tgnP: "有效期临近、流量用完或服务器无法使用时,机器人会通知您", + tgnWarn: "Telegram 会知道您在使用此服务", + tgnConnect: "连接 Telegram", + tgnWait: "等待 Telegram", + tgnWaitP: (min) => `打开机器人并点击“开始”。链接仅可使用一次,有效期 ${min} 分钟`, + tgnLeft: "剩余", + tgnOpen: "打开 Telegram", + tgnCancel: "取消", + tgnExp: "链接已过期", + tgnExpP: (min) => `该链接 ${min} 分钟内有效,现已失效。请获取新链接`, + tgnNew: "新链接", + tgnOn: "已连接", + tgnOf: (n, m) => `${n} / ${m}`, + tgnChat: (lang) => `Telegram · ${lang}`, + tgnSince: (d) => `自 ${d} 起`, + tgnAnn: "公告", + tgnOff: "断开", + tgnOffAria: (chat) => `断开:${chat}`, + tgnMore: "再连接一个", + tgnCmd: "在与机器人的聊天中:/stop 断开此聊天,/mute 关闭公告", + tgnEx: "示例", + tgnSilent: "机器人不会回复:链接已过期", + tgnMsgSoon: "您的访问将在 3 天后(12 月 14 日)到期。如需续期,请联系为您开通的人", + tgnMsgQuota: "流量已使用 80%:100 GB 中的 80 GB。新周期将于 1 月 1 日开始", + tgnMsgDown: "访问出现问题,正在修复,恢复后会通知您", + tgnMsgWelcome: "已完成,通知已开启。本机器人从不发送链接,也不会向您索取任何信息。/stop 关闭此聊天,/mute 关闭公告", + tgnErr: (c, m, limit) => + ( + { + chat_limit: `已连接的聊天数已达上限:${limit}。请先断开其中一个,然后重试。`, + no_bot: "通知目前不可用。请联系为您开通的人。", + self_service_disabled: "服务的所有者已在此关闭该功能。请联系对方。", + too_many_requests: m > 0 ? `操作过于频繁,请 ${m} 分钟后再试。` : "操作过于频繁,请稍后再试。", + not_found: "该聊天已不存在。请刷新页面。", + network: "无法连接。请检查网络后重试。", + locked: "需要密码。请刷新页面。", + } as Record + )[c] ?? "未成功。请重试。", +}; + +// Turkish and Persian: for the owner's proofreading. +const tr: NotifyDict = { + tgnT: "Telegram bildirimleri", + tgnP: "Süreniz bitmek üzereyken, trafiğiniz tükenirken veya sunucular çalışmadığında bot size yazar", + tgnWarn: "Telegram, bu hizmeti kullandığınızı bilecek", + tgnConnect: "Telegram’ı bağla", + tgnWait: "Telegram bekleniyor", + tgnWaitP: (min) => `Botu açın ve “Başlat”a basın. Bağlantı tek kullanımlıktır ve ${min} dakika geçerlidir`, + tgnLeft: "kaldı", + tgnOpen: "Telegram’ı aç", + tgnCancel: "İptal", + tgnExp: "Bağlantının süresi doldu", + tgnExpP: (min) => `Bağlantı ${min} dakika geçerliydi, artık çalışmaz. Yeni bir bağlantı alın`, + tgnNew: "Yeni bağlantı", + tgnOn: "Bağlandı", + tgnOf: (n, m) => `${n} / ${m}`, + tgnChat: (lang) => `Telegram · ${lang}`, + tgnSince: (d) => `${d} tarihinden beri`, + tgnAnn: "Duyurular", + tgnOff: "Bağlantıyı kes", + tgnOffAria: (chat) => `Bağlantıyı kes: ${chat}`, + tgnMore: "Bir tane daha bağla", + tgnCmd: "Botla sohbette: /stop bu sohbetin bağlantısını keser, /mute duyuruları kapatır", + tgnEx: "Örnek", + tgnSilent: "Bot yanıt vermiyor: bağlantının süresi doldu", + tgnMsgSoon: "Erişiminiz 3 gün sonra, 14 Aralık’ta sona erecek. Uzatmak için sizi bağlayan kişiye yazın", + tgnMsgQuota: "Trafiğinizin %80’ini kullandınız: 100 GB’ın 80 GB’ı. Yeni dönem 1 Ocak’ta başlıyor", + tgnMsgDown: "Erişimde sorunlar var. Üzerinde çalışıyoruz, düzelince yazacağız", + tgnMsgWelcome: "Tamam, bildirimler açıldı. Bu bot hiçbir zaman bağlantı göndermez ve sizden hiçbir şey istemez. /stop bu sohbeti kapatır, /mute duyuruları kapatır", + tgnErr: (c, m, limit) => + ( + { + chat_limit: `Bağlanabilecek en fazla sohbet sayısına ulaşıldı: ${limit}. Birinin bağlantısını kesip tekrar deneyin.`, + no_bot: "Bildirimler şu an kullanılamıyor. Sizi bağlayan kişiye yazın.", + self_service_disabled: "Hizmetin sahibi bunu burada kapatmış. Ona yazın.", + too_many_requests: m > 0 ? `Arka arkaya çok fazla işlem. ${m} dk sonra tekrar deneyin.` : "Arka arkaya çok fazla işlem. Daha sonra tekrar deneyin.", + not_found: "Bu sohbet artık yok. Sayfayı yenileyin.", + network: "Bağlantı yok. İnternetinizi kontrol edip tekrar deneyin.", + locked: "Şifre gerekiyor. Sayfayı yenileyin.", + } as Record + )[c] ?? "Olmadı. Tekrar deneyin.", +}; + +const fa: NotifyDict = { + tgnT: "اعلان‌ها در تلگرام", + tgnP: "وقتی مهلت شما رو به پایان باشد، ترافیک تمام شود یا سرورها کار نکنند، ربات به شما پیام می‌دهد", + tgnWarn: "تلگرام خواهد دانست که شما از این سرویس استفاده می‌کنید", + tgnConnect: "اتصال تلگرام", + tgnWait: "در انتظار تلگرام", + tgnWaitP: (min) => `ربات را باز کنید و «شروع» را بزنید. این پیوند یک‌بار مصرف است و ${min} دقیقه اعتبار دارد`, + tgnLeft: "باقی‌مانده", + tgnOpen: "باز کردن تلگرام", + tgnCancel: "انصراف", + tgnExp: "پیوند منقضی شد", + tgnExpP: (min) => `این پیوند ${min} دقیقه معتبر بود و دیگر کار نمی‌کند. پیوند تازه‌ای بگیرید`, + tgnNew: "پیوند تازه", + tgnOn: "متصل", + tgnOf: (n, m) => `${n} از ${m}`, + tgnChat: (lang) => `تلگرام · ${lang}`, + tgnSince: (d) => `از ${d}`, + tgnAnn: "اطلاعیه‌ها", + tgnOff: "قطع اتصال", + tgnOffAria: (chat) => `قطع اتصال: ${chat}`, + tgnMore: "اتصال یک مورد دیگر", + tgnCmd: "در گفتگو با ربات: /stop این گفتگو را قطع می‌کند، /mute اطلاعیه‌ها را خاموش می‌کند", + tgnEx: "نمونه", + tgnSilent: "ربات پاسخ نمی‌دهد: پیوند منقضی شده است", + tgnMsgSoon: "دسترسی شما 3 روز دیگر، یعنی 14 دسامبر، به پایان می‌رسد. برای تمدید، به کسی که شما را متصل کرده پیام بدهید", + tgnMsgQuota: "80% ترافیک مصرف شد: 80 گیگابایت از 100 گیگابایت. دورهٔ تازه از 1 ژانویه شروع می‌شود", + tgnMsgDown: "در دسترسی مشکلاتی وجود دارد. در حال رفع آن هستیم و وقتی درست شد خبر می‌دهیم", + tgnMsgWelcome: "انجام شد، اعلان‌ها روشن شد. این ربات هرگز پیوند نمی‌فرستد و هیچ چیزی از شما نمی‌خواهد. /stop این گفتگو را قطع می‌کند، /mute اطلاعیه‌ها را خاموش می‌کند", + tgnErr: (c, m, limit) => + ( + { + chat_limit: `حداکثر تعداد گفتگوها متصل است: ${limit}. یکی را قطع کنید و دوباره تلاش کنید.`, + no_bot: "اعلان‌ها اکنون در دسترس نیستند. به کسی که شما را متصل کرده پیام بدهید.", + self_service_disabled: "مالک سرویس این را در اینجا خاموش کرده است. به او پیام بدهید.", + too_many_requests: m > 0 ? `تعداد کارهای پشت‌سرهم زیاد است. ${m} دقیقه دیگر دوباره تلاش کنید.` : "تعداد کارهای پشت‌سرهم زیاد است. بعداً دوباره تلاش کنید.", + not_found: "این گفتگو دیگر وجود ندارد. صفحه را تازه کنید.", + network: "ارتباطی برقرار نیست. اینترنت خود را بررسی کنید و دوباره تلاش کنید.", + locked: "رمز عبور لازم است. صفحه را تازه کنید.", + } as Record + )[c] ?? "انجام نشد. دوباره تلاش کنید.", +}; + +export const notify: Record = { ru, en, zh, fa, tr }; diff --git a/web/src/sub/i18n.ts b/web/src/sub/i18n.ts index 1b44e23d8..1ba127e6d 100644 --- a/web/src/sub/i18n.ts +++ b/web/src/sub/i18n.ts @@ -1,6 +1,7 @@ import { add, type AddDict } from "./i18n-add"; import { core, type CoreDict } from "./i18n-core"; import { dlg, type DlgDict } from "./i18n-dlg"; +import { notify, type NotifyDict } from "./i18n-notify"; import { tabs, type TabsDict } from "./i18n-tabs"; import type { Lang } from "./types"; @@ -206,8 +207,8 @@ const ru = { }; type Base = typeof ru; -/** The words of the page: the base above, then the redesign's own (i18n-core: the page and its status, i18n-add: the new-device window, i18n-dlg: the small windows, i18n-tabs: the servers, the proxies and the devices). */ -export type Dict = Base & CoreDict & AddDict & DlgDict & TabsDict; +/** The words of the page: the base above, then the redesign's own (i18n-core: the page and its status, i18n-add: the new-device window, i18n-dlg: the small windows, i18n-tabs: the servers, the proxies and the devices, i18n-notify: the block "Notifications in Telegram"). */ +export type Dict = Base & CoreDict & AddDict & DlgDict & TabsDict & NotifyDict; const en: Base = { dayWord: (n) => (n === 1 ? "day" : "days"), @@ -961,7 +962,7 @@ const tr: Base = { platforms: { ios: "iPhone", android: "Android", windows: "Windows", macos: "Mac", linux: "Linux", other: "Diğer" }, }; -const merge = (base: Base, l: Lang): Dict => ({ ...base, ...core[l], ...add[l], ...dlg[l], ...tabs[l] }); +const merge = (base: Base, l: Lang): Dict => ({ ...base, ...core[l], ...add[l], ...dlg[l], ...tabs[l], ...notify[l] }); export const dict: Record = { ru: typeset(merge(ru, "ru")), en: typeset(merge(en, "en")), zh: typeset(merge(zh, "zh")), fa: typeset(merge(fa, "fa")), tr: typeset(merge(tr, "tr")) }; /** The languages of the menu in the top bar, in order. */ diff --git a/web/src/sub/icons.ts b/web/src/sub/icons.ts index 221c17764..46e8283af 100644 --- a/web/src/sub/icons.ts +++ b/web/src/sub/icons.ts @@ -28,6 +28,10 @@ const paths = { file: ["M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z", "M14 3v5h5", "M12 11.5v5.5M9.5 14.5 12 17l2.5-2.5"], eye: ["M2.5 12S6 5.5 12 5.5 21.5 12 21.5 12 18 18.5 12 18.5 2.5 12 2.5 12z", circle(12, 12, 3)], send: ["M20.5 4 3.5 10.6l5.6 2 2 5.9 3-3.6 4.3 3.1z", "m9.1 12.6 6.4-4.4"], + /** the block "Notifications in Telegram": the plane of its board, a clock, the arrow out of a box */ + tg: ["M20.5 4 3.5 10.5l6 2.5M20.5 4 17 19.5 9.5 13M20.5 4 9.5 13v5.5l3.2-2.7"], + clock: [circle(12, 12, 8.5), "M12 7.5V12l3 2"], + openx: ["M14 5h5v5M19 5l-8 8M17 14v4a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V8a1 1 0 0 1 1-1h4"], shield: ["M12 3 5 6v5.5c0 4.4 3 8.2 7 9.5 4-1.3 7-5.1 7-9.5V6z"], info: [circle(12, 12, 9), "M12 11v5.5M12 7.6v.01"], warn: ["M10.3 4.2 2.8 17.5A2 2 0 0 0 4.5 20.5h15a2 2 0 0 0 1.7-3L13.7 4.2a2 2 0 0 0-3.4 0z", "M12 9.5v4M12 17v.01"], @@ -53,7 +57,7 @@ const paths = { export type IconName = keyof typeof paths; /** The icons that point along the line: mirrored on a right-to-left page (sub.css .flip). */ -const flips: ReadonlySet = new Set(["next", "back", "external", "send", "exit", "chat"]); +const flips: ReadonlySet = new Set(["next", "back", "external", "send", "exit", "chat", "tg", "openx"]); /** The icon at `size` px (the grid is 24; the board draws it at 16 with a 1.5 stroke, sub.css .i). */ export function icon(name: IconName, size = 16): SVGSVGElement { diff --git a/web/src/sub/logic.ts b/web/src/sub/logic.ts index c432254cd..60dc02d7d 100644 --- a/web/src/sub/logic.ts +++ b/web/src/sub/logic.ts @@ -24,6 +24,7 @@ import type { Status, Theme, Qr, + TgInfo, TrustTunnelLink, } from "./types"; @@ -181,6 +182,19 @@ function dnsInfo(raw: unknown): DnsInfo | null { return { enabled: x.enabled === true, endpoint: str(x.endpoint), refresh_hours: num(x.refresh_hours) || 12, link: linkDns(x.link) }; } +/** What the notifications endpoint answers (subs/notify_tg.go); a link is kept only when it is a t.me one. */ +export function tgInfo(raw: unknown): TgInfo { + const x = rec(raw); + const url = str(x.url); + return { + bot: str(x.bot), + limit: num(x.limit), + chats: list(x.chats).flatMap((c) => (str(c.id) ? [{ id: str(c.id), lang: str(c.lang), muted: c.muted === true, linked_unix: num(c.linked_unix) }] : [])), + expires_in: Math.floor(num(x.expires_in)), + url: /^https:\/\/t\.me\//.test(url) ? url : "", + }; +} + /** Turns whatever the server embedded into a complete MgData: a missing or malformed field gets a safe default. */ export function normalize(raw: unknown): MgData { const r = rec(raw); @@ -243,6 +257,7 @@ export function normalize(raw: unknown): MgData { ), servers: list(r.servers).map(serverEntry).filter((s) => s.country_code !== "" || s.label !== ""), dns: dnsInfo(r.dns), + tg_notify: r.tg_notify && typeof r.tg_notify === "object" && str(rec(r.tg_notify).endpoint) ? { endpoint: str(rec(r.tg_notify).endpoint) } : null, dns_presets: list(r.dns_presets).map(dnsPreset).filter((p) => p.id !== "" && p.name !== ""), user: { name: str(u.name), diff --git a/web/src/sub/main.ts b/web/src/sub/main.ts index 967a281a5..fe8a83fbb 100644 --- a/web/src/sub/main.ts +++ b/web/src/sub/main.ts @@ -10,7 +10,8 @@ import { icon } from "./icons"; import { lockActions, lockView, type LockState } from "./lock"; import { addPlatforms, asPlatform, asTheme, detectPlatform, isHex, isReturning, mainProfile, normalize, pickPlatform, safeUrl } from "./logic"; import { createModal } from "./modal"; -import { newAmzState, newDnsState, type Actions, type Ctx, type State } from "./state"; +import { tgActions } from "./notify-actions"; +import { newAmzState, newDnsState, newTgState, type Actions, type Ctx, type State } from "./state"; import { placeToast } from "./ui"; import type { Lang, Theme } from "./types"; import { annKey, brandName, logoSrc, view } from "./view"; @@ -163,6 +164,7 @@ if (data.locked) { returning: isReturning(data, stored("setup") === "1"), amz: newAmzState(here || "other", mainProfile(data.amnezia?.profiles ?? []), here), dns: newDnsState(), + tg: newTgState(), }; // the first of the controls (a|b) that is on screen: a row has one for a phone and one for a computer const focusKey = (keys: string) => @@ -231,6 +233,7 @@ if (data.locked) { marked: () => actions.mark(), }), dns: dnsActions({ data, st, render: () => render(), api: import.meta.env.DEV && data.dns?.endpoint === "dev:" ? devApi : api, focus: focusKey, locked: lockedPage }), + tg: tgActions({ data, st, render: () => render(), api, locked: lockedPage }), }; // the control used last (a tap does not focus a button in Safari): where the dialog gives the focus back @@ -277,6 +280,7 @@ if (data.locked) { // `vite -c vite.sub.config.ts` only: the scenes (every state of the page and every window opens on a page of its own; dev-scene.ts) if (import.meta.env.DEV) (await import("./dev-scene")).devScene(devQuery, data, st, actions); render("all"); + actions.tg.read(); } // the static favicon in sub.html is a placeholder (so the browser never asks for /favicon.ico); show the brand document.querySelector('link[rel="icon"]')?.setAttribute("href", logoSrc(data)); diff --git a/web/src/sub/notify-actions.ts b/web/src/sub/notify-actions.ts new file mode 100644 index 000000000..51962f94c --- /dev/null +++ b/web/src/sub/notify-actions.ts @@ -0,0 +1,163 @@ +import { ApiError } from "./api"; +import type { TgActions, TgState } from "./state"; +import type { MgData, TgInfo } from "./types"; + +// What the block "Notifications in Telegram" does: read the block, make a link and wait for Telegram, cancel, disconnect a chat, +// switch the announcements of one. Every call answers the block as it is now, and that is what the page keeps. While a link waits, +// one timer asks the panel every few seconds (the person links the chat in Telegram, not here) and one counts the seconds down; +// both stop with the wait. The calls are injected so a test can use a fake. + +export type TgApi = { + tgState(url: string): Promise; + tgLink(url: string): Promise; + tgCancel(url: string): Promise; + tgUnlink(url: string, chat: string): Promise; + tgMute(url: string, chat: string, muted: boolean): Promise; +}; + +type Deps = { + data: MgData; + st: { tg: TgState }; + render: () => void; + api: TgApi; + locked?: () => void; + /** The clock (ms) and the pause between two looks at the panel; a test sets its own. */ + now?: () => number; + pollMs?: number; +}; + +/** "14:32": what is left of the wait. */ +export const countdown = (ms: number): string => { + const s = Math.max(0, Math.ceil(ms / 1000)); + return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`; +}; + +export function tgActions({ data, st, render, api, locked, now = Date.now, pollMs = 4000 }: Deps): TgActions { + const tg = () => st.tg; + const endpoint = () => data.tg_notify?.endpoint ?? ""; + let pollTimer = 0; + let tickTimer = 0; + + const stop = () => { + clearTimeout(pollTimer); + clearInterval(tickTimer); + pollTimer = tickTimer = 0; + }; + + /** What the panel said becomes the page's copy; the wait's clock follows it. */ + function take(info: TgInfo) { + tg().info = info; + tg().until = info.expires_in > 0 ? now() + info.expires_in * 1000 : 0; + } + + function fail(e: unknown) { + if (e instanceof ApiError && e.code === "locked") return locked?.(); + tg().error = { code: e instanceof ApiError ? e.code : "failed", retryMin: e instanceof ApiError ? Math.ceil(e.retryAfter / 60) : 0 }; + } + + /** Ends the wait, with a new chat (`expired` false) or without one. */ + function done(expired: boolean) { + stop(); + tg().url = ""; + tg().until = 0; + tg().expired = expired; + } + + function watch() { + stop(); + const look = () => { + pollTimer = window.setTimeout(async () => { + if (!document.hidden) await actions.poll(); // a tab nobody looks at does not ask + if (tg().url) look(); + }, pollMs); + }; + look(); + tickTimer = window.setInterval(actions.tick, 1000); + } + + /** A call that changes the block: the answer replaces the copy, a failure is said under the block. */ + async function call(busy: string, run: (url: string) => Promise, then?: (info: TgInfo) => void) { + if (!endpoint() || tg().busy) return; + tg().busy = busy; + tg().error = null; + render(); + try { + const info = await run(endpoint()); + take(info); + then?.(info); + } catch (e) { + fail(e); + } + tg().busy = ""; + render(); + } + + const actions: TgActions = { + read() { + const url = endpoint(); + if (!url) return; + api.tgState(url).then( + (info) => { + take(info); + render(); + }, + (e) => { + // a block that could not be read is not drawn; only a lost password matters + if (e instanceof ApiError && e.code === "locked") locked?.(); + }, + ); + }, + link() { + return void call( + "link", + api.tgLink.bind(api), + (info) => { + tg().url = info.url; + tg().expired = false; + tg().ttl = Math.max(1, Math.round(info.expires_in / 60)); + // the chats the person has now do not count as the one that is linked next + tg().before = info.chats.map((c) => c.id); + if (info.url) watch(); + }, + ); + }, + cancel() { + stop(); + return void call("cancel", api.tgCancel.bind(api), () => done(false)); + }, + unlink(id) { + return void call(`unlink:${id}`, (u) => api.tgUnlink(u, id)); + }, + mute(id, muted) { + return void call(`mute:${id}`, (u) => api.tgMute(u, id, muted)); + }, + async poll() { + if (!tg().url || !endpoint()) return; + try { + const info = await api.tgState(endpoint()); + if (!tg().url) return; // cancelled or ended while the answer was on its way + take(info); + if (info.chats.some((c) => !tg().before.includes(c.id))) done(false); + else if (info.expires_in === 0) done(true); // the link is gone and no chat came of it + render(); + } catch (e) { + // a lost network is tried again at the next look; a lost password ends the wait + if (e instanceof ApiError && e.code === "locked") { + stop(); + locked?.(); + } + } + }, + tick() { + if (!tg().url) return stop(); + const left = tg().until - now(); + if (left <= 0) { + done(true); + render(); + return actions.read(); // a chat linked in the last second + } + for (const el of document.querySelectorAll("[data-tg-left]")) el.textContent = countdown(left); + }, + }; + return actions; +} diff --git a/web/src/sub/notify.test.ts b/web/src/sub/notify.test.ts new file mode 100644 index 000000000..ff7a3b87b --- /dev/null +++ b/web/src/sub/notify.test.ts @@ -0,0 +1,415 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { ApiError } from "./api"; +import { dict, langs } from "./i18n"; +import { fmtDate, normalize, tgInfo } from "./logic"; +import { chatLanguage, notifySection, tgView } from "./notify"; +import { countdown, tgActions, type TgApi } from "./notify-actions"; +import { newTgState, type Ctx, type State } from "./state"; +import { actions, data, state, text } from "./test-kit"; +import type { Lang, MgData, TgChat, TgInfo } from "./types"; +import { view } from "./view"; + +// The block "Notifications in Telegram": which state it is in and what each state says (the words of the board, in every language of +// the page), and what its calls do (the link, the wait for Telegram, the chats), against a fake of the page's endpoints. + +const endpoint = "https://sub.example.com/k3xq8/tok/telegram"; +const chat = (id: string, lang = "ru", muted = false): TgChat => ({ id, lang, muted, linked_unix: 1_796_000_000 }); +const info = (over: Partial = {}): TgInfo => ({ bot: "example_people_bot", limit: 3, chats: [], expires_in: 0, url: "", ...over }); + +const on = (d: MgData) => { + d.tg_notify = { endpoint }; +}; +const ctx = (i: TgInfo | null, over: Partial = {}, lang: Lang = "ru", f: (d: MgData) => void = on): Ctx => { + const d = data("first", f); + const s = state("windows", { tab: "devices" }, lang); + s.tg = { ...newTgState(), info: i, ...over }; + return { d, s, a: actions(), t: dict[lang], support: "" }; +}; +const block = (c: Ctx, now = Date.now()) => notifySection(c, now); +const kind = (el: HTMLElement | null) => el?.getAttribute("data-tg"); + +describe("which state the block is in", () => { + it("not drawn without a bot, without the endpoint, before the panel has answered, or when the panel says there is no bot", () => { + expect(block(ctx(info()))).not.toBeNull(); + expect(block(ctx(info(), {}, "ru", () => {}))).toBeNull(); // tg_notify null: self-service is off or the page cannot write + expect(block(ctx(null))).toBeNull(); + expect(block(ctx(info({ bot: "" })))).toBeNull(); + }); + + it("not connected, waiting (the link is in memory and has not run out), connected, and the link ran out", () => { + const now = 1_000_000; + const at = (i: TgInfo, over: Partial = {}) => tgView(ctx(i, over), now); + expect(at(info())).toBe("off"); + expect(at(info(), { url: "https://t.me/b?start=x", until: now + 5000 })).toBe("wait"); + expect(at(info(), { url: "https://t.me/b?start=x", until: now - 1 })).toBe("off"); // the clock ran out before the timer noticed + expect(at(info({ chats: [chat("utc_a")] }))).toBe("on"); + expect(at(info({ chats: [chat("utc_a")] }), { url: "https://t.me/b?start=x", until: now + 5000 })).toBe("wait"); // "connect another one" + expect(at(info(), { expired: true })).toBe("exp"); + expect(at(info({ chats: [chat("utc_a")] }), { expired: true })).toBe("on"); // the chats stay in reach + }); + + it("a pending link whose address the page does not have (after a reload) is not a wait: the person asks for a new one", () => { + expect(tgView(ctx(info({ expires_in: 600 })))).toBe("off"); + }); +}); + +describe("what each state says (Russian, the words of the board)", () => { + it("not connected: the privacy warning, the button, the example of the chat", () => { + const el = block(ctx(info()))!; + expect(el.getAttribute("aria-label")).toBe("Уведомления в Telegram"); + expect(text(el.querySelector(".u-tgn-hd b"))).toBe("Уведомления в Telegram"); + expect(text(el.querySelector(".u-tgn-p"))).toBe("Бот напишет, когда подходит конец срока, заканчивается трафик или не работают серверы"); + expect(text(el.querySelector(".u-tgn-w"))).toBe("Telegram будет знать, что вы пользуетесь этим сервисом"); + expect(text(el.querySelector(".u-tgn-a .u-btn"))).toBe("Подключить Telegram"); + expect(text(el.querySelector(".u-tgn-chat .who"))).toBe("@example_people_botПример"); + expect(el.querySelector(".u-tgn-chat")?.getAttribute("aria-hidden")).toBe("true"); + expect([...el.querySelectorAll(".u-tgn-chat .bb")].map(text)).toEqual([ + "Доступ закончится через 3 дня, 14 декабря. Чтобы продлить, напишите тому, кто вас подключил", + "Потрачено 80% трафика: 80 ГБ из 100 ГБ. Новый период начнётся 1 января", + "Есть проблемы с доступом. Уже чиним, напишем, когда заработает", + ]); + }); + + it("the button asks for a link", () => { + const c = ctx(info()); + block(c)!.querySelector("[data-k=tg-link]")!.click(); + expect((c.a as ReturnType).log).toEqual(["tg-link"]); + }); + + it("waiting: the one-time link opens Telegram in a new tab, the time left, cancel", () => { + const now = 5_000_000; + const c = ctx(info(), { url: "https://t.me/example_people_bot?start=abc", until: now + 872_000, ttl: 15 }); + const el = block(c, now)!; + expect(text(el.querySelector(".u-tgn-st"))).toBe("Ждём Telegram"); + expect(text(el.querySelector(".u-tgn-p"))).toBe("Откройте бота и нажмите «Запустить». Ссылка одноразовая и работает 15 минут"); + expect(text(el.querySelector(".u-tgn-t"))).toBe("осталось14:32"); + expect(el.querySelector("[data-tg-left]")?.getAttribute("dir")).toBe("ltr"); + const open = el.querySelector("a[data-k=tg-open]")!; + expect([open.getAttribute("href"), open.target, open.rel, text(open)]).toEqual(["https://t.me/example_people_bot?start=abc", "_blank", "noopener noreferrer", "Открыть Telegram"]); + expect(text(el.querySelector("[data-k=tg-cancel]"))).toBe("Отмена"); + expect([...el.querySelectorAll(".u-tgn-chat .bb")].map(text)).toEqual(["/start", ""]); // the person's /start and the typing dots + el.querySelector("[data-k=tg-cancel]")!.click(); + expect((c.a as ReturnType).log).toEqual(["tg-cancel"]); + }); + + it("the link ran out: it says so and offers a new one", () => { + const el = block(ctx(info(), { expired: true }))!; + expect(text(el.querySelector(".u-tgn-st"))).toBe("Ссылка устарела"); + expect(text(el.querySelector(".u-tgn-p"))).toBe("Ссылка работала 15 минут и больше не подойдёт. Получите новую"); + expect(text(el.querySelector("[data-k=tg-link]"))).toBe("Новая ссылка"); + expect(text(el.querySelector(".u-tgn-sil"))).toBe("Бот не отвечает: ссылка устарела"); + }); + + it("connected: how many of how many, a row for each chat, the commands, no way to add one over the limit", () => { + const rows = [chat("utc_a", "ru"), chat("utc_b", "en", true)]; + const el = block(ctx(info({ chats: rows })))!; + expect(text(el.querySelector(".u-tgn-st"))).toBe("Подключено 2 из 3"); + const r = [...el.querySelectorAll(".u-tgn-r")]; + expect(r.map((x) => [text(x.querySelector(".u-tgn-lc")), text(x.querySelector(".u-tgn-rn b")), text(x.querySelector(".u-tgn-rn em"))])).toEqual([ + ["RU", "Telegram · русский", `с ${fmtDate(1_796_000_000, "ru")}`], + ["EN", "Telegram · английский", `с ${fmtDate(1_796_000_000, "ru")}`], + ]); + expect(r.map((x) => x.querySelector("[role=switch]")?.getAttribute("aria-checked"))).toEqual(["true", "false"]); // announcements are on unless muted + expect(r.map((x) => text(x.querySelector(".u-tgn-sw span")))).toEqual(["Объявления", "Объявления"]); + expect(r.map((x) => text(x.querySelector(".u-btn")))).toEqual(["Отключить", "Отключить"]); + expect(text(el.querySelector("[data-k=tg-link]"))).toBe("Подключить ещё один"); + expect(text(el.querySelector(".u-tgn-cmd"))).toBe("В чате с ботом: /stop — отключить этот чат, /mute — без объявлений"); + expect(text(el.querySelector(".u-tgn-chat .bb"))).toBe("Готово, уведомления подключены. Этот бот никогда не присылает ссылок и ничего не спрашивает. /stop — отключить этот чат, /mute — без объявлений"); + + const full = block(ctx(info({ limit: 2, chats: rows })))!; + expect(text(full.querySelector(".u-tgn-st"))).toBe("Подключено 2 из 2"); + expect(full.querySelector("[data-k=tg-link]")).toBeNull(); + }); + + it("the switch turns announcements off (when they are on) or on, and Disconnect names the chat", () => { + const c = ctx(info({ chats: [chat("utc_a", "ru"), chat("utc_b", "en", true)] })); + const el = block(c)!; + el.querySelector("[data-k=tg-mute-utc_a]")!.click(); + el.querySelector("[data-k=tg-mute-utc_b]")!.click(); + el.querySelector("[data-k=tg-off-utc_b]")!.click(); + expect((c.a as ReturnType).log).toEqual(["tg-mute utc_a true", "tg-mute utc_b false", "tg-unlink utc_b"]); + expect(el.querySelector("[data-k=tg-off-utc_b]")?.getAttribute("aria-label")).toBe("Отключить: Telegram · английский"); + }); + + it("a call in flight turns the controls off; a failure is said under the block", () => { + const busy = block(ctx(info({ chats: [chat("utc_a")] }), { busy: "mute:utc_a" }))!; + expect([...busy.querySelectorAll("button")].every((b) => b.disabled)).toBe(true); + const el = block(ctx(info({ chats: [chat("utc_a")] }), { error: { code: "chat_limit", retryMin: 0 } }))!; + expect(text(el.querySelector(".note.bad"))).toBe("Подключено максимум чатов: 3. Отключите один из них и попробуйте снова."); + expect(el.querySelector(".note.bad")?.getAttribute("role")).toBe("alert"); + }); +}); + +describe("every language of the page", () => { + it.each(langs)("%s: every state has all its words, the page's direction and no leftover placeholder", (lang) => { + const now = 9_000_000; + const states: [string, TgInfo, Partial][] = [ + ["off", info(), {}], + ["wait", info(), { url: "https://t.me/b?start=x", until: now + 60_000 }], + ["exp", info(), { expired: true }], + ["on", info({ chats: [chat("utc_a", "ru"), chat("utc_b", "zh")] }), {}], + ]; + for (const [want, i, over] of states) { + const el = block(ctx(i, { ...over, error: { code: "chat_limit", retryMin: 0 } }, lang), now)!; + expect(kind(el)).toBe(want); + const all = text(el); + expect(all).not.toMatch(/undefined|NaN|\{|\}/); + expect(el.querySelector(".u-tgn-hd b")!.textContent!.length).toBeGreaterThan(3); + expect(text(el.querySelector(".note.bad")).length).toBeGreaterThan(10); + } + // the example of the chat is in the page's language + const off = block(ctx(info(), {}, lang))!; + expect([...off.querySelectorAll(".u-tgn-chat .bb")].map((b) => b.getAttribute("lang"))).toEqual([lang === "zh" ? "zh-CN" : lang, lang === "zh" ? "zh-CN" : lang, lang === "zh" ? "zh-CN" : lang]); + expect(dict[lang].tgnMsgWelcome).toContain("/stop"); + expect(dict[lang].tgnCmd).toContain("/mute"); + }); + + it("the other languages say the same things as Russian (the privacy warning, the commands)", () => { + for (const lang of langs) { + const t = dict[lang]; + expect(t.tgnWarn.length).toBeGreaterThan(10); + expect(t.tgnCmd).toMatch(/\/stop[\s\S]*\/mute/); + expect(t.tgnMsgDown).not.toBe(""); + } + expect(text(block(ctx(info(), {}, "en"))!.querySelector(".u-tgn-w"))).toBe("Telegram will know you use this service"); + expect(text(block(ctx(info({ chats: [chat("utc_a", "ru")] }), {}, "zh"))!.querySelector(".u-tgn-rn b"))).toBe("Telegram · 俄语"); + expect(chatLanguage("pt", "en")).toBe("Portuguese"); + expect(chatLanguage("", "en")).toBe(""); + }); +}); + +describe("on the page", () => { + it("the devices tab carries it under the list; the other tabs and a page without the block do not", () => { + const d = data("first", on); + const st = state("windows", { tab: "devices" }); + st.tg = { ...newTgState(), info: info() }; + const el = view(d, st, actions()); + const tg = el.querySelector(".u-tgn"); + expect(tg).not.toBeNull(); + expect(el.querySelector(".u-dvl")!.nextElementSibling).toBe(tg); + const servers = state("windows", { tab: "servers" }); + servers.tg = st.tg; + expect(view(d, servers, actions()).querySelector(".u-tgn")).toBeNull(); + expect(view(data("first"), st, actions()).querySelector(".u-tgn")).toBeNull(); + }); + + it("the page data switches the block on only with a real endpoint", () => { + expect(normalize({ tg_notify: { endpoint } }).tg_notify).toEqual({ endpoint }); + for (const raw of [{}, { tg_notify: null }, { tg_notify: { endpoint: "" } }, { tg_notify: "x" }]) expect(normalize(raw).tg_notify).toBeNull(); + }); +}); + +describe("the answer of the panel", () => { + it("is read defensively, and keeps only a t.me link", () => { + expect(tgInfo(null)).toEqual({ bot: "", limit: 0, chats: [], expires_in: 0, url: "" }); + expect(tgInfo({ bot: "b", limit: 3, expires_in: 12.9, url: "https://t.me/b?start=x", chats: [{ id: "utc_a", lang: "ru", muted: true, linked_unix: 5 }, { lang: "en" }] })).toEqual({ + bot: "b", + limit: 3, + expires_in: 12, + url: "https://t.me/b?start=x", + chats: [{ id: "utc_a", lang: "ru", muted: true, linked_unix: 5 }], + }); + expect(tgInfo({ url: "javascript:alert(1)" }).url).toBe(""); + expect(tgInfo({ url: "https://t.me.evil.example/x" }).url).toBe(""); + }); + + it("the countdown is minutes and seconds", () => { + expect([0, -5, 1, 999, 1000, 59_000, 872_000, 900_000].map(countdown)).toEqual(["0:00", "0:00", "0:01", "0:01", "0:01", "0:59", "14:32", "15:00"]); + }); +}); + +// ---- the calls ---- + +type Fake = TgApi & { calls: string[]; info: TgInfo; fail?: ApiError; next: (i: TgInfo) => void }; +function fakeApi(start: TgInfo = info()): Fake { + const f: Fake = { + calls: [], + info: start, + next: (i) => (f.info = i), + tgState: async () => (f.fail ? Promise.reject(f.fail) : (f.calls.push("state"), { ...f.info, url: "" })), + tgLink: async () => { + if (f.fail) throw f.fail; + f.calls.push("link"); + f.info = { ...f.info, expires_in: 900 }; + return { ...f.info, url: "https://t.me/example_people_bot?start=code123" }; + }, + tgCancel: async () => { + f.calls.push("cancel"); + f.info = { ...f.info, expires_in: 0 }; + return { ...f.info }; + }, + tgUnlink: async (_u, id) => { + f.calls.push(`unlink ${id}`); + f.info = { ...f.info, chats: f.info.chats.filter((c) => c.id !== id) }; + return { ...f.info }; + }, + tgMute: async (_u, id, muted) => { + f.calls.push(`mute ${id} ${muted}`); + f.info = { ...f.info, chats: f.info.chats.map((c) => (c.id === id ? { ...c, muted } : c)) }; + return { ...f.info }; + }, + }; + return f; +} + +const settle = async () => { + for (let i = 0; i < 5; i++) await Promise.resolve(); +}; + +function rig(api: TgApi, f: (d: MgData) => void = on) { + const d = data("first", f); + const st = { tg: newTgState() }; + const clock = { t: 1_000_000 }; + const renders = { n: 0 }; + const lockedCalls = { n: 0 }; + const a = tgActions({ data: d, st, render: () => renders.n++, api, locked: () => lockedCalls.n++, now: () => clock.t, pollMs: 4000 }); + return { a, st, clock, renders, lockedCalls }; +} + +describe("what the block does", () => { + beforeEach(() => vi.useFakeTimers()); + afterEach(() => vi.useRealTimers()); + + it("reads the block once; a block that cannot be read is not drawn", async () => { + const api = fakeApi(info({ chats: [chat("utc_a")] })); + const { a, st, renders } = rig(api); + a.read(); + await settle(); + expect(st.tg.info?.chats.map((c) => c.id)).toEqual(["utc_a"]); + expect(renders.n).toBe(1); + + const bad = rig(Object.assign(fakeApi(), { tgState: () => Promise.reject(new ApiError(0, "network")) })); + bad.a.read(); + await settle(); + expect(bad.st.tg.info).toBeNull(); + expect(bad.lockedCalls.n).toBe(0); + + const lock = rig(Object.assign(fakeApi(), { tgState: () => Promise.reject(new ApiError(401, "locked")) })); + lock.a.read(); + await settle(); + expect(lock.lockedCalls.n).toBe(1); + + const none = rig(fakeApi(), () => {}); + none.a.read(); + expect(none.st.tg.info).toBeNull(); // no endpoint, no call + }); + + it("a link starts the wait: the address is kept in memory, the clock follows the panel, the page looks every few seconds", async () => { + const api = fakeApi(info({ chats: [chat("utc_a")] })); + const { a, st, clock, renders } = rig(api); + a.link(); + await settle(); + expect(st.tg).toMatchObject({ url: "https://t.me/example_people_bot?start=code123", until: clock.t + 900_000, before: ["utc_a"], ttl: 15, expired: false, busy: "" }); + expect(renders.n).toBe(2); // busy, then the answer + + await vi.advanceTimersByTimeAsync(4000); + expect(api.calls).toEqual(["link", "state"]); + await vi.advanceTimersByTimeAsync(8000); + expect(api.calls).toEqual(["link", "state", "state", "state"]); + }); + + it("the person links the chat in Telegram: the next look sees it and the wait ends in the connected state", async () => { + const api = fakeApi(); + const { a, st } = rig(api); + a.link(); + await settle(); + api.next(info({ chats: [chat("utc_new", "en")], expires_in: 0 })); + await vi.advanceTimersByTimeAsync(4000); + expect(st.tg).toMatchObject({ url: "", until: 0, expired: false }); + expect(st.tg.info?.chats.map((c) => c.id)).toEqual(["utc_new"]); + const before = api.calls.length; + await vi.advanceTimersByTimeAsync(20_000); + expect(api.calls.length).toBe(before); // the timers stopped with the wait + }); + + it("a link that is gone and made no chat is an expired one", async () => { + const api = fakeApi(); + const { a, st } = rig(api); + a.link(); + await settle(); + api.next(info({ expires_in: 0 })); + await vi.advanceTimersByTimeAsync(4000); + expect(st.tg).toMatchObject({ url: "", expired: true }); + }); + + it("the countdown runs on the page's clock and the wait ends when it reaches zero, with a last look at the chats", async () => { + const api = fakeApi(); + const { a, st, clock } = rig(api); + document.body.innerHTML = '15:00'; + a.link(); + await settle(); + clock.t += 872_000; + a.tick(); + expect(document.querySelector("[data-tg-left]")!.textContent).toBe("0:28"); + clock.t += 28_000; + api.calls.length = 0; + a.tick(); + await settle(); + expect(st.tg).toMatchObject({ url: "", expired: true }); + expect(api.calls).toEqual(["state"]); // a chat linked in the last second still shows + }); + + it("a tab nobody looks at does not ask", async () => { + const api = fakeApi(); + const { a } = rig(api); + a.link(); + await settle(); + Object.defineProperty(document, "hidden", { value: true, configurable: true }); + await vi.advanceTimersByTimeAsync(12_000); + expect(api.calls).toEqual(["link"]); + Object.defineProperty(document, "hidden", { value: false, configurable: true }); + await vi.advanceTimersByTimeAsync(4000); + expect(api.calls).toContain("state"); + }); + + it("cancel withdraws the link and ends the wait", async () => { + const api = fakeApi(); + const { a, st } = rig(api); + a.link(); + await settle(); + a.cancel(); + await settle(); + expect(api.calls).toEqual(["link", "cancel"]); + expect(st.tg).toMatchObject({ url: "", until: 0, expired: false }); + await vi.advanceTimersByTimeAsync(20_000); + expect(api.calls).toEqual(["link", "cancel"]); + }); + + it("disconnects a chat and switches its announcements; the answer replaces the page's copy; one call at a time", async () => { + const api = fakeApi(info({ chats: [chat("utc_a"), chat("utc_b")] })); + const { a, st } = rig(api); + a.read(); + await settle(); + a.mute("utc_a", true); + a.mute("utc_b", true); // dropped: the first is still in flight + await settle(); + expect(api.calls).toEqual(["state", "mute utc_a true"]); + expect(st.tg.info?.chats.map((c) => c.muted)).toEqual([true, false]); + a.unlink("utc_a"); + await settle(); + expect(st.tg.info?.chats.map((c) => c.id)).toEqual(["utc_b"]); + expect(st.tg.busy).toBe(""); + }); + + it("a refusal is kept as its code and the minutes to wait; a lost password goes to the password form", async () => { + const api = fakeApi(); + const { a, st, lockedCalls } = rig(api); + api.fail = new ApiError(409, "chat_limit"); + a.link(); + await settle(); + expect(st.tg.error).toEqual({ code: "chat_limit", retryMin: 0 }); + expect(st.tg.url).toBe(""); + api.fail = new ApiError(429, "too_many_requests", 125); + a.link(); + await settle(); + expect(st.tg.error).toEqual({ code: "too_many_requests", retryMin: 3 }); + api.fail = new ApiError(0, "network"); + a.link(); + await settle(); + expect(st.tg.error?.code).toBe("network"); + api.fail = new ApiError(401, "locked"); + a.link(); + await settle(); + expect(lockedCalls.n).toBe(1); + }); +}); diff --git a/web/src/sub/notify.ts b/web/src/sub/notify.ts new file mode 100644 index 000000000..95efa4c1f --- /dev/null +++ b/web/src/sub/notify.ts @@ -0,0 +1,131 @@ +import "./sub-tg.css"; +import { h, type Kid } from "./dom"; +import { htmlLang, localeOf } from "./i18n"; +import { icon } from "./icons"; +import { fmtDate } from "./logic"; +import { countdown } from "./notify-actions"; +import type { Ctx } from "./state"; +import type { Lang, TgChat } from "./types"; +import { note } from "./ui"; + +// The block "Notifications in Telegram", as the board draws it (the devices tab, under the list): a card with the person's side on +// the left and, on the right, an example of the chat that the state leads to. Four states: not connected (the privacy warning and the +// button), waiting for Telegram (the one-time link, the countdown, "Open Telegram"), the link ran out, and connected (a row for each +// chat with its language, since when, the switch of announcements and "Disconnect"). It is not drawn when the owner has no bot for +// the people, when self-service is off or the page cannot write, nor before the panel has answered. The link lives in memory only. + +export type TgView = "off" | "wait" | "exp" | "on"; + +/** Which of the four states the block is in; null when it is not drawn. */ +export function tgView({ d, s }: Pick, now = Date.now()): TgView | null { + const tg = s.tg; + if (!d.tg_notify || !tg.info || tg.info.bot === "") return null; + if (tg.url !== "" && tg.until > now) return "wait"; + if (tg.info.chats.length > 0) return "on"; + return tg.expired ? "exp" : "off"; +} + +/** A chat's language in the words of the page ("русский"); the code itself when the browser does not know it. */ +export function chatLanguage(code: string, page: Lang): string { + try { + const name = code ? new Intl.DisplayNames(localeOf(page), { type: "language" }).of(code) : ""; + if (name && name !== code) return name; + } catch { + // a code the browser cannot name + } + return code.toUpperCase(); +} + +const bubble = (lang: string, text: string) => h("div", { class: "bb", dir: "auto", lang }, h("span", null, text)); + +function pane(c: Ctx, body: Kid[]): HTMLElement { + const { s, t } = c; + return h( + "div", + { class: "u-tgn-chat", "aria-hidden": "true" }, + h("span", { class: "who" }, h("i", null, icon("tg", 12)), h("span", { dir: "ltr" }, `@${s.tg.info?.bot ?? ""}`), h("em", null, t.tgnEx)), + ...body, + ); +} + +const typing = () => h("div", { class: "bb ty" }, h("i", null), h("i", null), h("i", null)); + +function head(c: Ctx, status?: HTMLElement): HTMLElement { + return h("div", { class: "u-tgn-hd" }, h("span", { class: "tl" }, icon("tg", 18)), h("b", null, c.t.tgnT), status); +} + +function chatRow(c: Ctx, x: TgChat): HTMLElement { + const { s, t, a } = c; + const busy = s.tg.busy !== ""; + const name = t.tgnChat(chatLanguage(x.lang, s.lang)); + const on = !x.muted; + return h( + "div", + { class: "u-tgn-r" }, + h("span", { class: "u-tgn-lc mono", "aria-hidden": "true" }, x.lang.toUpperCase().slice(0, 2)), + h("span", { class: "u-tgn-rn" }, h("b", null, name), x.linked_unix > 0 && h("em", null, t.tgnSince(fmtDate(x.linked_unix, s.lang)))), + h( + "label", + { class: "u-tgn-sw" }, + h("span", null, t.tgnAnn), + h("button", { type: "button", role: "switch", "aria-checked": on, "aria-label": t.tgnAnn, "data-k": `tg-mute-${x.id}`, disabled: busy, on: { click: () => a.tg.mute(x.id, on) } }, h("i", null)), + ), + h("button", { class: "u-btn quiet sm", type: "button", "aria-label": t.tgnOffAria(name), "data-k": `tg-off-${x.id}`, disabled: busy, on: { click: () => a.tg.unlink(x.id) } }, t.tgnOff), + ); +} + +/** The block, or null when it is not drawn (see the top of the file). */ +export function notifySection(c: Ctx, now = Date.now()): HTMLElement | null { + const { s, t, a } = c; + const view = tgView(c, now); + const info = s.tg.info; + if (!view || !info) return null; + const tg = s.tg; + const lang = htmlLang(s.lang); + const busy = tg.busy !== ""; + const spin = (key: string) => (tg.busy === key ? h("span", { class: "spin" }) : null); + const link = (label: string) => + h("button", { class: "u-btn", type: "button", "data-k": "tg-link", disabled: busy, "aria-busy": tg.busy === "link" ? "true" : false, on: { click: a.tg.link } }, spin("link") ?? icon("tg"), label); + const error = tg.error ? note("bad", "warn", t.tgnErr(tg.error.code, tg.error.retryMin, info.limit), { cls: "u-tgn-err" }) : null; + const open = tg.url + ? h("a", { class: "u-btn pri", href: tg.url, target: "_blank", rel: "noopener noreferrer", "data-k": "tg-open" }, t.tgnOpen, icon("openx")) + : null; + + let main: Kid[]; + let side: Kid[]; + switch (view) { + case "wait": + main = [ + head(c, h("span", { class: "u-tgn-st w" }, h("i", null), t.tgnWait)), + h("p", { class: "u-tgn-p" }, t.tgnWaitP(tg.ttl)), + h("p", { class: "u-tgn-t" }, icon("clock"), h("span", null, t.tgnLeft), h("b", { class: "mono", dir: "ltr", "data-tg-left": "" }, countdown(tg.until - now))), + h("div", { class: "u-tgn-a" }, open, h("button", { class: "u-btn quiet", type: "button", "data-k": "tg-cancel", disabled: busy, on: { click: a.tg.cancel } }, t.tgnCancel)), + ]; + side = [h("div", { class: "bb me mono", dir: "ltr" }, "/start"), typing()]; + break; + case "exp": + main = [head(c, h("span", { class: "u-tgn-st x" }, h("i", null), t.tgnExp)), h("p", { class: "u-tgn-p" }, t.tgnExpP(tg.ttl)), h("div", { class: "u-tgn-a" }, link(t.tgnNew))]; + side = [h("div", { class: "bb me mono", dir: "ltr" }, "/start"), h("p", { class: "u-tgn-sil" }, t.tgnSilent)]; + break; + case "on": { + const full = info.limit > 0 && info.chats.length >= info.limit; + main = [ + head(c, h("span", { class: "u-tgn-st" }, h("i", null), t.tgnOn, " ", h("span", { class: "u-tgn-n" }, t.tgnOf(info.chats.length, info.limit)))), + h("div", { class: "u-tgn-ls" }, ...info.chats.map((x) => chatRow(c, x))), + !full && h("div", { class: "u-tgn-a" }, link(t.tgnMore)), + h("p", { class: "u-tgn-cmd" }, t.tgnCmd), + ]; + side = [bubble(lang, t.tgnMsgWelcome), bubble(lang, t.tgnMsgSoon)]; + break; + } + default: + main = [ + head(c), + h("p", { class: "u-tgn-p" }, t.tgnP), + h("p", { class: "u-tgn-w" }, icon("eye"), h("span", null, t.tgnWarn)), + h("div", { class: "u-tgn-a" }, link(t.tgnConnect)), + ]; + side = [bubble(lang, t.tgnMsgSoon), bubble(lang, t.tgnMsgQuota), bubble(lang, t.tgnMsgDown)]; + } + return h("section", { class: "u-card u-tgn", "aria-label": t.tgnT, "data-tg": view }, h("div", { class: "u-tgn-m" }, ...main, error), pane(c, side)); +} diff --git a/web/src/sub/state.ts b/web/src/sub/state.ts index 47d688723..0571d5337 100644 --- a/web/src/sub/state.ts +++ b/web/src/sub/state.ts @@ -1,5 +1,5 @@ import type { Dict } from "./i18n"; -import type { AwgConfig, Lang, MgData, Platform, Theme } from "./types"; +import type { AwgConfig, Lang, MgData, Platform, TgInfo, Theme } from "./types"; // What the page remembers while it is open, and what its parts may do. The data (MgData) is the server's; this is the person's. @@ -83,6 +83,42 @@ export type DnsState = { export const newDnsState = (): DnsState => ({ open: null, pick: "", all: false, busy: "", error: null, skipped: [], done: {} }); +/** What the block "Notifications in Telegram" holds while the page is open (notify.ts, notify-actions.ts). */ +export type TgState = { + /** What the panel last said; null until it was read (the block is not drawn then, nor when the read failed). */ + info: TgInfo | null; + /** The link of the wait: kept in memory only, the panel never says it twice. "" = no wait. */ + url: string; + /** When the link ends, on this clock (ms); 0 = none. */ + until: number; + /** The chats the person had when the link was made: a chat that is not among them is the one that was linked. */ + before: string[]; + /** How many minutes a link works, as the panel said it. */ + ttl: number; + /** The wait ran out without a new chat: "Link expired". */ + expired: boolean; + /** "link", "cancel", "unlink:" or "mute:" while a call is in flight; "" otherwise. */ + busy: string; + /** The last failure, as the panel's code. */ + error: { code: string; retryMin: number } | null; +}; + +export const newTgState = (): TgState => ({ info: null, url: "", until: 0, before: [], ttl: 15, expired: false, busy: "", error: null }); + +export type TgActions = { + /** Reads the block (the page does it once when it opens). */ + read(): void; + /** A new link (the pending one stops working) and the wait for Telegram. */ + link(): void; + cancel(): void; + unlink(id: string): void; + /** The announcements of a chat: `muted` true = off. */ + mute(id: string, muted: boolean): void; + /** What the timers of the wait call: one look at the panel, one second of the countdown. */ + poll(): Promise; + tick(): void; +}; + export type AmzActions = { /** Opens (true) the "add a device" dialog, at `pane` or where the person's ways say (the choice, or the only way), or closes (false) whichever dialog is open. */ add(open: boolean, pane?: AddPane): void; @@ -146,6 +182,7 @@ export type State = { returning: boolean; amz: AmzState; dns: DnsState; + tg: TgState; }; /** What every section of the page draws from: the data, the person's state, what it may do, the words, and the support link ("" = none). */ @@ -163,4 +200,5 @@ export type Actions = { mark(): void; amz: AmzActions; dns: DnsActions; + tg: TgActions; } & Tools; diff --git a/web/src/sub/sub-tg.css b/web/src/sub/sub-tg.css new file mode 100644 index 000000000..222ddd2ff --- /dev/null +++ b/web/src/sub/sub-tg.css @@ -0,0 +1,74 @@ +/* The block "Notifications in Telegram" (notify.ts): the board's mg-tg.css, read after sub.css. A card in two columns, the person's side + and an example of the chat; one column on a phone. */ +.u-tgn { display: grid; grid-template-columns: minmax(0, 1fr) 400px; overflow: hidden; } +.u-tgn-m { display: flex; flex-direction: column; align-items: flex-start; gap: 12px; min-width: 0; padding: 24px; } +.u-tgn-hd { display: flex; align-items: center; gap: 12px; align-self: stretch; } +.u-tgn-hd .tl { display: grid; place-items: center; flex: none; width: 36px; height: 36px; border-radius: 10px; background: var(--step); color: var(--sec); } +.u-tgn-hd b { font-size: 16px; line-height: 24px; font-weight: 500; } +.u-tgn-st { display: inline-flex; align-items: center; gap: 8px; margin-inline-start: auto; font-size: 13px; line-height: 20px; color: var(--sec); white-space: nowrap; } +.u-tgn-st i { width: 8px; height: 8px; border-radius: 50%; background: var(--mint); } +.u-tgn-st.w i { background: var(--warning); } +.u-tgn-st.x i { background: var(--muted); } +.u-tgn-st .u-tgn-n { color: var(--muted); } +.u-tgn-p { max-width: 52ch; font-size: 14px; line-height: 22px; color: var(--sec); } +.u-tgn-w { display: flex; align-items: flex-start; gap: 8px; max-width: 52ch; font-size: 13px; line-height: 20px; color: var(--sec); } +.u-tgn-w .i { flex: none; width: 16px; height: 16px; margin-top: 2px; color: var(--muted); } +.u-tgn-t { display: flex; align-items: center; gap: 8px; font-size: 13px; line-height: 20px; color: var(--muted); } +.u-tgn-t .i { width: 16px; height: 16px; } +.u-tgn-t b { font-weight: 500; color: var(--text); } +.u-tgn-a { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; align-self: stretch; margin-top: auto; padding-top: 8px; } +.u-tgn-a .u-btn { flex: 0 0 auto; } +.u-tgn-a .u-btn.pri .i { order: 2; width: 14px; height: 14px; } +.u-tgn .u-btn .spin { width: 14px; height: 14px; } +.u-tgn-err { align-self: stretch; } +.u-tgn-cmd { font-size: 12px; line-height: 16px; color: var(--muted); } +.u-btn.sm { height: 32px; padding: 0 12px; font-size: 13px; border-radius: 8px; } +/* the chats */ +.u-tgn-ls { display: flex; flex-direction: column; align-self: stretch; border-top: 1px solid var(--hair); } +.u-tgn-r { display: flex; align-items: center; gap: 12px; min-height: 64px; padding: 12px 0; border-bottom: 1px solid var(--hair); } +.u-tgn-lc { display: grid; place-items: center; flex: none; width: 32px; height: 32px; border-radius: 50%; background: var(--step); font-size: 11px; color: var(--sec); } +.u-tgn-rn { display: flex; flex-direction: column; flex: 1; min-width: 0; } +.u-tgn-rn b { font-size: 14px; line-height: 20px; font-weight: 500; } +.u-tgn-rn em { font-style: normal; font-size: 13px; line-height: 20px; color: var(--muted); } +.u-tgn-sw { display: inline-flex; align-items: center; gap: 8px; font-size: 13px; line-height: 20px; color: var(--sec); cursor: pointer; } +.u-tgn-sw button { position: relative; flex: none; width: 36px; height: 20px; padding: 0; border: 0; border-radius: 10px; background: var(--hair); cursor: pointer; transition: background 0.2s; } +.u-tgn-sw button:disabled { opacity: 0.45; cursor: default; } +.u-tgn-sw button i { position: absolute; top: 2px; inset-inline-start: 2px; width: 16px; height: 16px; border-radius: 50%; background: var(--text); transition: transform 0.2s cubic-bezier(0.2, 0.7, 0.2, 1); } +.u-tgn-sw button[aria-checked="true"] { background: var(--accent); } +.u-tgn-sw button[aria-checked="true"] i { transform: translateX(16px); background: var(--ink); } +:root[dir="rtl"] .u-tgn-sw button[aria-checked="true"] i { transform: translateX(-16px); } +/* the example of the chat */ +.u-tgn-chat { display: flex; flex-direction: column; justify-content: flex-end; gap: 8px; min-height: 232px; padding: 20px 24px; border-inline-start: 1px solid var(--hair); background: var(--bg); } +.u-tgn-chat .who { display: flex; align-items: center; gap: 8px; margin-bottom: auto; padding-bottom: 8px; font: 400 12px/16px var(--mono); color: var(--sec); } +.u-tgn-chat .who i { display: grid; place-items: center; width: 24px; height: 24px; border-radius: 8px; border: 1px solid var(--hair); color: var(--sec); } +.u-tgn-chat .who i .i { width: 12px; height: 12px; } +.u-tgn-chat .who em { margin-inline-start: auto; font: 400 12px/16px var(--sans); font-style: normal; color: var(--muted); } +.u-tgn-chat .bb { align-self: flex-start; max-width: 88%; padding: 8px 12px; border-radius: 14px; border-end-start-radius: 4px; background: var(--step); font-size: 13px; line-height: 20px; animation: tgn-in 0.4s cubic-bezier(0.2, 0.7, 0.2, 1) both; } +.u-tgn-chat .bb:nth-of-type(2) { animation-delay: 0.12s; } +.u-tgn-chat .bb:nth-of-type(3) { animation-delay: 0.24s; } +.u-tgn-chat .bb span { color: var(--sec); } +.u-tgn-chat .bb.me { align-self: flex-end; border-radius: 14px; border-end-end-radius: 4px; background: color-mix(in srgb, var(--accent) 18%, transparent); } +.u-tgn-chat .bb.mono { font: 500 14px/20px var(--mono); letter-spacing: 0; } +.u-tgn-chat .bb.ty { display: inline-flex; gap: 4px; padding: 14px 12px; } +.u-tgn-chat .bb.ty i { width: 4px; height: 4px; border-radius: 50%; background: var(--muted); animation: tgn-ty 1.2s ease-in-out infinite; } +.u-tgn-chat .bb.ty i:nth-child(2) { animation-delay: 0.15s; } +.u-tgn-chat .bb.ty i:nth-child(3) { animation-delay: 0.3s; } +.u-tgn-sil { align-self: center; padding: 4px 12px; border-radius: 999px; background: var(--step); font-size: 12px; line-height: 16px; color: var(--muted); } +@keyframes tgn-in { from { opacity: 0; transform: translateY(8px); } } +@keyframes tgn-ty { 0%, 60%, 100% { opacity: 0.35; transform: none; } 30% { opacity: 1; transform: translateY(-2px); } } +@media (prefers-reduced-motion: reduce) { .u-tgn-chat .bb, .u-tgn-chat .bb.ty i, .u-tgn-sw button, .u-tgn-sw button i { animation: none; transition: none; } } +/* a phone: one column, the example under the block, each chat's switch on a line of its own */ +@media (max-width: 719.98px) { + .u-tgn { grid-template-columns: minmax(0, 1fr); } + .u-tgn-m { padding: 20px; } + .u-tgn-chat { min-height: 0; padding: 16px 20px; border-inline-start: 0; border-top: 1px solid var(--hair); } + .u-tgn-chat .who { margin-bottom: 0; } + .u-tgn-chat .bb { max-width: 100%; } + .u-tgn-hd { flex-wrap: wrap; row-gap: 0; } + .u-tgn-hd b { flex: 1; min-width: 0; } + .u-tgn-st { flex-basis: 100%; margin-inline-start: 48px; margin-top: -4px; } + .u-tgn-r { flex-wrap: wrap; row-gap: 8px; } + .u-tgn-sw { order: 3; flex-basis: calc(100% - 44px); margin-inline-start: 44px; justify-content: space-between; } + .u-tgn-r .u-btn { order: 2; } + .u-tgn-a .u-btn { height: 44px; } +} diff --git a/web/src/sub/test-kit.ts b/web/src/sub/test-kit.ts index 78d6bd86d..019fef440 100644 --- a/web/src/sub/test-kit.ts +++ b/web/src/sub/test-kit.ts @@ -2,7 +2,7 @@ import { deviceModal, deviceModalLabel, deviceModalStage } from "./add"; import { cases } from "./dev-data"; import { dict } from "./i18n"; import { normalize } from "./logic"; -import { newAmzState, newDnsState, type Actions, type State } from "./state"; +import { newAmzState, newDnsState, newTgState, type Actions, type State } from "./state"; import type { Lang, MgData } from "./types"; // Shared by the tests of the page: sample data, a state, and actions that only note what was asked. @@ -48,6 +48,7 @@ export function actions(over: Partial = {}): Actions & { log: string[] download: (f) => log.push(`download ${f}`), amz: { ...amzNoop, add: (o, pane) => log.push(pane ? `add ${o} ${pane}` : `add ${o}`), pane: (p) => log.push(`pane ${p}`) }, dns: { open: (s) => log.push(`dns-open ${s}`), pick: (p) => log.push(`dns-pick ${p}`), apply: () => log.push("dns-apply"), retry: () => log.push("dns-retry"), scope: (all) => log.push(`dns-scope ${all}`) }, + tg: { read: noop, link: () => log.push("tg-link"), cancel: () => log.push("tg-cancel"), unlink: (id) => log.push(`tg-unlink ${id}`), mute: (id, m) => log.push(`tg-mute ${id} ${m}`), poll: async () => {}, tick: noop }, ...over, }; } @@ -66,6 +67,7 @@ export function state(platform: State["platform"] = "ios", over: Partial returning: false, amz: newAmzState(platform, "p31", platform), dns: newDnsState(), + tg: newTgState(), ...over, }; } diff --git a/web/src/sub/types.ts b/web/src/sub/types.ts index be89fc31f..fd780d6fc 100644 --- a/web/src/sub/types.ts +++ b/web/src/sub/types.ts @@ -117,6 +117,16 @@ export type AwgDevice = { route: "" | "ru-direct"; min_clients: MinClient[]; }; +/** The notifications block (subs/notify_tg.go): where it talks to. null when there is no bot to link to, self-service is off or the page cannot write. */ +export type TgNotifyData = { endpoint: string }; +/** One chat of the person, by its row id (never the Telegram chat id). */ +export type TgChat = { id: string; lang: string; muted: boolean; linked_unix: number }; +/** + * What the endpoint answers: the bot ("" = none, the block goes away), the chat limit, the person's chats, the seconds the pending link + * still works (counted by the panel; 0 = none) and, for a new link only, the t.me address. + */ +export type TgInfo = { bot: string; limit: number; chats: TgChat[]; expires_in: number; url: string }; + /** An AmneziaWG profile a device can be added on; the page names it by its countries and exit, never by `name`. */ export type AwgProfile = { id: string; name: string; version: string; egress: "direct" | "warp"; countries: string[] }; export type AmneziaData = { @@ -172,6 +182,7 @@ export type MgData = { servers: ServerEntry[]; /** The DNS choice; null on an older panel (no DNS part on the page at all). */ dns: DnsInfo | null; + tg_notify: TgNotifyData | null; dns_presets: DnsPreset[]; user: { name: string;