FastAPI/Pydantic на 422 кладёт в detail массив объектов {type,loc,msg,...};
компоненты рендерили его в JSX как есть → React падал в ErrorBoundary
(Objects are not valid as a React child), пользователь не видел причину.
Все такие обработчики (Login, Profile, ConnectedAccounts, admin AnalyticsTab
и MenuEditorTab) переведены на существующий getApiErrorMessage — строковый
detail возвращается как есть (ветки .includes работают), Pydantic-массив
разворачивается в строку field: msg; ..., любой формат безопасен для рендера.
Валидация на смердженном дереве: tsc, biome lint/format, build — чисто.
Что: все обработчики ошибок, которые клали сырой response.data.detail в
состояние и затем в JSX, переведены на существующий хелпер
getApiErrorMessage (src/utils/api-error.ts):
- Login.tsx — Telegram-auth, вход/регистрация по email, восстановление пароля
- Profile.tsx — смена email (запрос и подтверждение кода), повторная
отправка письма верификации
- ConnectedAccounts.tsx — привязка email к аккаунту
- admin/AnalyticsTab.tsx, admin/MenuEditorTab.tsx — сохранение настроек
Почему: на невалидный по схеме запрос FastAPI/Pydantic отвечает 422, где
detail — не строка, а массив объектов {type, loc, msg, input, ctx}.
Компоненты рендерили его как есть, React падал с «Objects are not valid
as a React child», и вся страница (включая логин) уходила в ErrorBoundary
«Something went wrong» — пользователь не видел причину отказа вообще.
Зачем: getApiErrorMessage сводит Pydantic-массив к строке
«field: message; ...», поэтому вместо краша форма показывает настоящий
текст ошибки валидации. Ветвления по detail.includes(...) сохранены и
работают по нормализованной строке — поведение прежнее для строковых
detail, но безопасное для любой формы ответа.
- telegram-webview-guards.grit: исключение сузил с подстроки "platform"
до якорного "src/platform/" — прежний eslint-override действовал ровно на
src/platform/**, а bare-substring щадил бы любой файл с "platform" в имени
(проверено: src/platform всё ещё exempt, гвард срабатывает в обычных файлах)
- biome.json: вернул исключения *.min.js/*.min.css из .prettierignore
- lint-staged: вернул форматирование *.css в pre-commit (biome format --write) —
иначе CI-формат-чек ловил бы css, который хук не трогал
- lint.yml: метка шага "Run ESLint" → "Run linter" (выполняет biome)
По итогам разбора Biome 2.5 x Tailwind v3: noUnknownAtRules и
noUnknownFunction не выключаем, а используем их опцию ignore
(tailwind; theme/screen) - детект опечаток в at-rules и функциях
сохраняется. noDuplicateProperties off: наши дубли - прогрессивные
фолбэки (100dvh -> var(--tg-viewport-stable-height)), опции
"разрешить фолбэки" нет (biomejs/biome#6051). noImportantStyles off:
все 31 !important осознанные. @tailwind в ignore из-за
biomejs/biome#7899 (tailwindDirectives их пока не покрывает).
UI для фичи «Купоны» (backend — remnawave-bot #3044):
- админ-раздел /admin/coupons: список партий со статистикой, форма создания
с готовыми ссылками (копировать/скачать .txt), карточка партии с экспортом
и отзывом непогашенных за PermissionGate coupons:edit
- публичная /coupon/:token: партнёр видит тариф/срок, кнопки активации в боте
и (для залогиненных) в кабинете с маппингом машинных кодов ошибок
- локали ru/en; zh/fa через ru-фолбэк
Ревью-фиксы поверх PR:
- единый formatShortDate вместо 3 копий formatDate + инлайн localeMap
- статистика списка показывается только для одной страницы (суммы по
странице иначе противоречат глобальному total)
- retry:false на публичном статусе (404 — штатный ответ)
- formatShortDate вынесен в utils/format вместо трёх копий formatDate +
инлайн localeMap (AdminCoupons/AdminCouponDetail/CouponStatus)
- список партий: агрегатные карточки Активны/Погашено/Отозвано считались
только по текущей странице и противоречили глобальному total «Партий» —
показываем их лишь когда весь набор влезает на одну страницу
- CouponStatus: retry:false на публичном статусе (404 — ожидаемый ответ на
невалидный/погашенный токен, ретрай зря бьёт rate-limited эндпоинт)
По фичам Biome v2.3: css.parser.tailwindDirectives снимает исключение
CSS из Biome (globals.css снова под формат-контролем; линт CSS выключен
override-ом — tailwind-функции theme() и пр. правила пока не знают),
lineEnding auto повторяет поведение prettier endOfLine: auto (CRLF в
Windows-чекаутах, LF на CI). Однократный формат-дифф globals.css
45+/45- — расхождения CSS-форматтера Biome с Prettier.
Один инструмент вместо девяти dev-зависимостей. Замеры на этом репо
(483 файла, медиана из 3 прогонов, один и тот же компьютер):
- eslint . ~20.4s -> biome lint . ~2s
- prettier --check . ~8.8s -> biome format . ~0.2s
- суммарно линт+формат ~29s -> biome check . ~2-3s (~10x)
Паритет с прежними правилами:
- форматирование бинарно совместимо с Prettier-конфигом (biome format
--write тронул 9 файлов из ~480 — микроразличия);
- запрет window.confirm/alert/open/prompt и navigator.clipboard
(Telegram WebView) перенесён GritQL-плагином
biome-plugins/telegram-webview-guards.grit c теми же сообщениями
и исключениями для src/platform/** и clipboard.ts; плагин сразу
нашёл window.open в Wheel.tsx под старым eslint-disable —
переведён на biome-ignore;
- react-hooks-правила: useExhaustiveDependencies/useHookAtTopLevel;
- новые для проекта правила (a11y и пр.) не включались или понижены
до warning, чтобы миграция не смешивалась с чисткой кода — включать
можно отдельными PR.
Ограничения (задокументированы): сортировка tailwind-классов
(prettier-plugin-tailwindcss) в Biome пока nursery — не включена;
CSS исключён из Biome (парсер спотыкается о Tailwind-синтаксис
globals.css) — файл один и правится редко.
CI не меняется: имена npm-скриптов lint/format:check сохранены.
lint-staged переведён на biome check --write.
UI для купонов из BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot#3042
(API: PR #3044 бота):
- /admin/coupons — список партий с погашениями и offset-пагинацией;
- /admin/coupons/create — мастер партии (тариф, дни, количество,
учётная оптовая цена, срок), после создания — экран со ссылками
(копирование всех, скачивание .txt);
- /admin/coupons/:id — карточка со статистикой, экспорт актуальных
ссылок, отзыв непогашенных за PermissionGate coupons:edit
с подтверждением и тостом;
- /coupon/:token — публичная страница купона: тариф/срок, кнопка
активации в боте, для залогиненных — активация прямо в кабинете
с маппингом структурированных кодов ошибок {code, message};
- пункт меню в разделе тарифов (гейт coupons:read), лениво
загружаемые роуты, локали ru/en (zh/fa падают на ru-фолбэк).
Backend now serves a dedicated recurring-payments legal document, so:
- Add adminLegalPagesApi.get/updateRecurrentPayments and infoApi.getRecurrentPayments
(+ InfoVisibility.recurrent).
- AdminLegalPages: new 'Рекуррентные платежи' editor tab (DocumentEditor now driven
by a DOCUMENT_API dispatch map instead of privacy/offer ternaries).
- PublicLegal: add 'recurrent' doc; add public /recurrent-payments route.
- Re-add the recurrent link to the login LegalFooter (was removed pending backend).
- i18n: admin.legalPages.tabs.recurrent for ru/en/fa/zh (footer.recurrent already existed).
type-check, eslint, prettier and build all pass.
The login-page footer linked to /offer, /privacy and /recurrent-payments with
target=_blank, but none of those routes existed, so opening them hit the SPA
catch-all, which redirects unauthenticated users to /login — every footer link
just opened another login tab.
- Add a public PublicLegal page that fetches the offer / privacy document from the
existing public /cabinet/info endpoints and renders sanitized HTML (DOMPurify via
the shared formatContent helper).
- Register public /offer and /privacy routes.
- Extract sanitizeHtml/formatContent into src/utils/legalContent.ts and reuse from
Info.tsx (was duplicated).
- Drop the /recurrent-payments footer link: there is no recurring-payments legal
document or endpoint in the backend, so it had no real destination. Re-add once
such a document exists.
type-check, eslint, prettier and build all pass.
Panel 2.8.0 removed the server-side happ-encrypt endpoint, so for users
without a stored crypto link the backend leaves {{HAPP_CRYPT4_LINK}}
unresolved and the subscriptionLink button silently disappeared
(isValidDeepLink requires '://').
- BlockButtons: resolve button templates client-side at render (with username,
like the panel's own subpage) instead of dropping the button; collapse
double-prefixed happ://crypt4/happ://cryptN/... resolvedUrl from old backends
- templateEngine: collapse a hardcoded happ://cryptN/ prefix before
{{HAPP_CRYPT[34]_LINK}}; cache crypt-link generation (jsencrypt RSA-4096 is
slow on weak devices and re-randomizes every call)
- Connection: in happ_cryptolink mode force the crypt link only when the button
fell back to the plain subscription link or kept unresolved templates - an
explicit Subpage link (e.g. happ://add/...) now wins, so Subpage edits apply
Adds a legal footer (Public Offer / Privacy / Recurring Payments) under the
login card, gated by CABINET_FOOTER_ENABLED (backend endpoint added in bot
PR #3011), plus an admin toggle in BrandingTab and ru/en/fa/zh i18n.
Footer-only subset of PR #464 — excludes the unrelated storePartnerClickId
helper and the version/CHANGELOG churn.
Co-authored-by: smediainfo <dev@matrixvpn.top>
The panel renamed the subscription-request-history field userUuid (uuid)
-> userId (number) in 2.8.0. The field is never read in the UI (render
uses id/requestAt/requestIp/userAgent), so this is a type-accuracy fix
only. tsc --noEmit passes.
Add an /admin/tickets/:ticketId route that pre-selects the ticket, and a
StartParamNavigator that maps a Telegram Mini App start param (admin_ticket_<id>,
delivered by a group-chat t.me/<bot>/<app>?startapp deep link) to that route.
This lets the bot's admin ticket notification buttons open the cabinet straight on
the ticket — web_app buttons for private chats, the startapp deep link for groups
where web_app is unavailable. Selection mirrors the URL param (cleared on the bare
/admin/tickets list). The static /admin/tickets/settings route still out-ranks the
new dynamic segment.
Pairs with bot feature BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot#2988.
Remove '/cabinet/auth/merge/' from AUTH_ENDPOINTS so the request
interceptor attaches the Authorization header. The backend merge
preview/execute endpoints require an authenticated initiator
(get_current_cabinet_user); omitting the token produced
401 'Authentication required' and merges never completed after
Telegram confirmation or email-code verification.
- useFeatureFlags: кэш флагов в localStorage — нижняя навигация больше
не прыгает на холодном старте (таб «Рефералы»/«Колесо» появлялся после
загрузки terms/config)
- applyThemeColors: частичный/битый ответ /branding/colors добивается
дефолтами вместо падения всего приложения в ErrorBoundary
- карточка «Связаться с поддержкой»: кнопка больше не дублирует заголовок
(«Написать», без переноса)
- «Мои подписки»: заголовок и «Купить ещё» в одну строку на 390px
- StatCard: подписи плиток переносятся на две строки вместо обрезки
многоточием («Бонус новому польз…»)
- guard config.default_quick_amounts with ?? [] so the edit page survives a
cabinet deployed ahead of the bot
- roll back the first faq reorder request when the second fails so both
questions don't end up with the same display_order
- stop overriding the aurora palette in render for the legacy seed colors
- add the missing legalPages / displayMode / quickAmounts keys to fa and zh
Companion to the bot-side change: the variables hint now renders two
groups — type-specific vars and common ones ({service_name},
{cabinet_url}, {support_username}, {username}, {email}, {date}) that
work in every template. The block is visible even for types with no
vars of their own (previously it was hidden entirely, looking like
placeholders didn't exist). Common chips insert at cursor the same way.
'String contained an illegal UTF-16 sequence' on first Mini App / site
open for users with a truncated emoji in their Telegram name.
The existing surrogate guard only patched the ENCODE direction
(encodeURI/encodeURIComponent). But Telegram percent-encodes such names
as CESU-8 (%ED%A0%BD) in tgWebAppData, and decodeURI/decodeURIComponent
throw on those bytes in every engine (JSC wording is the reported one) —
any decode of init-data-derived strings crashed into the ErrorBoundary.
Not valibot: valibot 1.0.0 has no UTF-16 well-formedness validation
(verified against the installed package), and upstream pins it exactly,
so there is nothing to bump.
decodeURI/decodeURIComponent now try the native decoder first and fall
back to lenient WHATWG-style UTF-8 decoding with U+FFFD replacement —
the same semantics URLSearchParams applies to the same bytes. Decoded
values still flow through existing validation (getSafeRedirectPath etc),
so nothing becomes less strict.
Companion to the bot-side fix: defaults now arrive with {placeholders}
instead of baked-in sample values (example.com links).
- inline preview tab (iframe srcDoc) — works on mobile and in Telegram;
the separate desktop-only preview page and its route are removed
- preview/test render the CURRENT editor content with sample values
- test email: recipient input + detailed backend error messages
- variable chips insert at cursor instead of copying to clipboard
- 'insert default template' button to migrate broken saved overrides
- fa added to language tabs
- Lava returns to a path-based result URL (/balance/top-up/result/:method) because Lava
Business rejects query strings in success/fail URLs. Add the route and read the method
from the path param as a fallback (alongside ?method=) so external-browser redirects
still poll the right payment. Pairs with the backend fix.
- ConnectedAccounts: the "Привязка Telegram временно недоступна" message overflowed the
card (it sat in the non-shrinking action column and never wrapped). Constrain its width
and wrap it (max-w + break-words) so it stays inside the card. Verified by rendering.
Both reported in the Bedolaga bug topic.
- health probe: tolerant timeout (12s) + retry before flagging the backend down. A
hardcoded 5s probe racing auth bootstrap falsely showed ServiceUnavailableScreen on
slow devices / cold mobile connections while the 30s API requests would have
succeeded ("works on one device, not another on the same Wi-Fi"). The recovery poll
self-reschedules with the tolerant timeout so slow devices auto-recover.
- TopUpAmount: fetch payment methods with a real query (fixes the infinite spinner on a
cold cache / browser-back) and use canonical RUB for quick-amount chips so FX rounding
can't reject a min-amount selection in non-RUB locales.
- settings UI: render secret values as a masked password input (pairs with the backend
secret masking); leaving the field empty keeps the stored secret.
- deps: npm audit fix (18 -> 5 advisories).
Also bundles in-progress settings env-lock UI work.
The hint claimed the provider opens 'inside the MiniApp/tab' — that is the broken behavior that caused #654272 (a same-WebView navigation to the provider can't hand off to a bank app / SBP). After the fix the link opens in the EXTERNAL browser inside Telegram regardless of the toggle. Rewrote the hint in all four locales: ON = open immediately (no button panel), OFF = show an 'Open payment' button; both open externally in Telegram so bank-app/SBP payments work; Stars/CryptoBot (t.me/ links) always open natively and ignore the flag.
Note: the external-browser open is unconditional (both toggle states, all methods incl. WATA) — the toggle only controls auto-open vs a button tap.