Compare commits

..

12 Commits

Author SHA1 Message Date
developer 8fe1bdba6b Merge pull request 'release: v1.6.0 — promo deep-link seeds EN variant (+ UI nits)' (#135) from development into master 2026-06-23 21:02:19 +00:00
developer 7923b3cc09 Merge pull request 'release v1.5.1: support-relay card + topic-reopen fixes' (#133) from development into master 2026-06-23 16:54:01 +00:00
developer 4891216749 Merge pull request 'release v1.5.0: Telegram bot support relay' (#131) from development into master 2026-06-23 16:16:04 +00:00
developer f1b8769c89 Merge pull request 'release: v1.4.1 — Telegram nav (windowed, own back button, debug panel)' (#129) from development into master 2026-06-23 13:27:31 +00:00
developer b6f28a2423 Merge pull request 'release: v1.4.0 — Telegram launch diagnostic + dynamic SDK load' (#127) from development into master 2026-06-23 08:40:09 +00:00
developer e32ee9ce68 Merge pull request 'Release: development → master' (#125) from development into master 2026-06-22 22:36:42 +00:00
developer dc946a1faf Merge pull request 'release v1.2.2: edge HTTP/3 stall fix + db-size dashboard threshold' (#121) from development into master 2026-06-22 19:50:58 +00:00
developer 384bd143d0 Merge pull request 'Promote development → master: banner tip set + banner/push language fix' (#114) from development into master 2026-06-22 18:28:00 +00:00
developer c5d22fceca Merge pull request 'Promote development → master: Erudit blank star + dictionary v1.3.0 pin' (#111) from development into master 2026-06-22 13:12:01 +00:00
developer deaa7a29c5 Merge pull request 'Promote development → master (docs finalize + UI tweaks + Telegram name fallback)' (#108) from development into master 2026-06-22 07:27:40 +00:00
developer 24017bcb7f Merge pull request 'Promote development → master (deploy v2: versioning + visible jobs + rollback)' (#106) from development into master 2026-06-22 06:01:03 +00:00
developer 2c4f4b10dc Merge pull request 'Promote development → master (initial production release: pre-release line + Stage 18)' (#104) from development into master 2026-06-22 05:05:48 +00:00
12 changed files with 31 additions and 352 deletions
+3 -9
View File
@@ -42,12 +42,7 @@ Three executables plus per-platform side-services:
users, a weighted fair rotation — §10), users, a weighted fair rotation — §10),
and a client **board-style** setting (bonus-label and a client **board-style** setting (bonus-label
mode). The visual/interaction design system is documented in mode). The visual/interaction design system is documented in
[`UI_DESIGN.md`](UI_DESIGN.md). Inside the Telegram Mini App the client additionally [`UI_DESIGN.md`](UI_DESIGN.md).
tracks Telegram's live theme switch (`themeChanged`), fits the full device safe-area
insets (the bottom/home-indicator strip taking the bottom bar's colour), exposes
Telegram's native **Settings** button into the in-app settings, and syncs the
device-independent display preferences (theme, reduce-motion, board labels — **not** the
interface language) across the user's Telegram devices via **CloudStorage**.
- **`platform/telegram`** — the Telegram side-service (module - **`platform/telegram`** — the Telegram side-service (module
`scrabble/platform/telegram`), split into two binaries that share the bot token `scrabble/platform/telegram`), split into two binaries that share the bot token
(**one bot**, one optional game channel, §3): (**one bot**, one optional game channel, §3):
@@ -157,8 +152,7 @@ arrive from a platform rather than completing a mandatory registration).
- **Single bot.** The platform side-service runs **one bot** (one token + one optional - **Single bot.** The platform side-service runs **one bot** (one token + one optional
game channel), split into a home **validator** and a remote **bot** that share the game channel), split into a home **validator** and a remote **bot** that share the
token. `ValidateInitData` (the validator) validates `initData` against that single token. `ValidateInitData` (the validator) validates `initData` against that single
token, **rejects a bot user** (the signed `is_bot` flag), and returns only the Telegram token and returns only the Telegram user identity — there is no per-bot "service
user identity — there is no per-bot "service
language" and no supported-languages set on the wire. The bot's chat messages and language" and no supported-languages set on the wire. The bot's chat messages and
out-of-app push are out-of-app push are
rendered in the recipient's **interface language** (`preferred_language`, en/ru), not in rendered in the recipient's **interface language** (`preferred_language`, en/ru), not in
@@ -978,7 +972,7 @@ edits take effect on the next `profile.get` (open/reconnect/foreground), not mid
| Concern | Enforced by | | Concern | Enforced by |
| --- | --- | | --- | --- |
| Public rate limiting / anti-abuse | gateway (per-IP public/email/admin classes, per-user authenticated class; a request body cap of `GATEWAY_MAX_BODY_BYTES`; rejections are metered, summarised to the backend and surfaced in the admin console with a conservative reversible auto-flag — §11). In prod a **temporary IP ban** (`GATEWAY_ABUSE_BAN_ENABLED`) blocks an IP that sustains rejections or trips a **honeypot** decoy path / **honeytoken**, refused with 429 before any work; operators lift bans from the console. Off in the shared-NAT test contour, where the client IP is not real (§11) | | Public rate limiting / anti-abuse | gateway (per-IP public/email/admin classes, per-user authenticated class; a request body cap of `GATEWAY_MAX_BODY_BYTES`; rejections are metered, summarised to the backend and surfaced in the admin console with a conservative reversible auto-flag — §11). In prod a **temporary IP ban** (`GATEWAY_ABUSE_BAN_ENABLED`) blocks an IP that sustains rejections or trips a **honeypot** decoy path / **honeytoken**, refused with 429 before any work; operators lift bans from the console. Off in the shared-NAT test contour, where the client IP is not real (§11) |
| Telegram initData validation (bot-token HMAC) | the Telegram **validator**; the gateway delegates it over gRPC, so the bot token (the HMAC secret) lives only in the validator and the bot, never in the gateway. The validator also **rejects a bot principal** (the signed `is_bot` flag) before any account is provisioned | | Telegram initData validation (bot-token HMAC) | the Telegram **validator**; the gateway delegates it over gRPC, so the bot token (the HMAC secret) lives only in the validator and the bot, never in the gateway |
| Session minting; email-code / guest validation | gateway (with backend) | | Session minting; email-code / guest validation | gateway (with backend) |
| Session → `user_id` resolution, `X-User-ID` injection | gateway | | Session → `user_id` resolution, `X-User-ID` injection | gateway |
| Authorisation, ownership, state transitions | backend (`X-User-ID` is the sole identity input) | | Authorisation, ownership, state transitions | backend (`X-User-ID` is the sole identity input) |
+2 -6
View File
@@ -30,8 +30,7 @@ A player arrives from a platform (Telegram first), via email login, or as an
ephemeral guest. The gateway validates the credential once and mints a thin ephemeral guest. The gateway validates the credential once and mints a thin
session token; the backend resolves it to an internal `user_id`. A **Telegram Mini session token; the backend resolves it to an internal `user_id`. A **Telegram Mini
App** launch authenticates from the platform's signed `initData`, themes the UI to App** launch authenticates from the platform's signed `initData`, themes the UI to
the Telegram colours (re-theming live if you switch Telegram's light/dark mode) and fits the Telegram colours, and — on first contact — seeds the new account's interface
the device safe-area, and — on first contact — seeds the new account's interface
language from the Telegram client. If a launch cannot reach the backend (for example during a language from the Telegram client. If a launch cannot reach the backend (for example during a
deployment), the Mini App retries quietly and then shows a small "couldn't load" screen with a deployment), the Mini App retries quietly and then shows a small "couldn't load" screen with a
**Retry** button, rather than dropping to the web sign-in, which has no place inside Telegram. **Retry** button, rather than dropping to the web sign-in, which has no place inside Telegram.
@@ -250,10 +249,7 @@ is first created — so robot games are timed correctly before you ever open thi
daily away window (on a 10-minute grid, at most 12 hours, wrapping midnight) and the daily away window (on a 10-minute grid, at most 12 hours, wrapping midnight) and the
block toggles. The profile form is edited inline (no separate edit mode). Linking block toggles. The profile form is edited inline (no separate edit mode). Linking
an email or Telegram and merging accounts are covered under "Accounts, linking & an email or Telegram and merging accounts are covered under "Accounts, linking &
merge". Inside the Telegram Mini App, Telegram's own ⋮ menu also offers a **Settings** merge".
entry that opens this screen, and your display preferences (theme, board-label style and
reduce-motion — not the interface language, which follows your account) sync across your
Telegram devices.
**Preferences (which variants you can be matched into).** A profile setting picks the game **Preferences (which variants you can be matched into).** A profile setting picks the game
variants — Erudite, Russian Scrabble and English Scrabble, shown **Erudite-first** — you allow variants — Erudite, Russian Scrabble and English Scrabble, shown **Erudite-first** — you allow
+2 -8
View File
@@ -31,9 +31,7 @@ top-1 подсказку, безлимитную проверку слова с
эфемерный гость. Gateway один раз валидирует доступ и выдаёт тонкий эфемерный гость. Gateway один раз валидирует доступ и выдаёт тонкий
session-токен; backend сопоставляет его с внутренним `user_id`. Запуск **Telegram session-токен; backend сопоставляет его с внутренним `user_id`. Запуск **Telegram
Mini App** авторизует по подписанным `initData` платформы, перекрашивает интерфейс Mini App** авторизует по подписанным `initData` платформы, перекрашивает интерфейс
в цвета Telegram (перекрашиваясь вживую при смене светлой/тёмной темы Telegram) и в цвета Telegram и — при первом контакте — задаёт язык интерфейса нового аккаунта по
вписывается в безопасные зоны экрана (safe-area), а — при первом контакте — задаёт язык
интерфейса нового аккаунта по
языку Telegram-клиента. Если запуск не может достучаться до бэкенда (например, во время языку Telegram-клиента. Если запуск не может достучаться до бэкенда (например, во время
деплоя), Mini App тихо повторяет попытки, а затем показывает небольшой экран «не удалось деплоя), Mini App тихо повторяет попытки, а затем показывает небольшой экран «не удалось
загрузить» с кнопкой **Повторить**, вместо того чтобы сбрасывать на веб-вход, которому внутри загрузить» с кнопкой **Повторить**, вместо того чтобы сбрасывать на веб-вход, которому внутри
@@ -257,11 +255,7 @@ UTC; при создании аккаунта она подставляется
игры с роботом таймились правильно ещё до открытия этой формы), суточного окна отсутствия игры с роботом таймились правильно ещё до открытия этой формы), суточного окна отсутствия
(away; сетка по 10 минут, не более 12 часов, с переходом через полночь) и переключателей блокировок. Форма профиля редактируется (away; сетка по 10 минут, не более 12 часов, с переходом через полночь) и переключателей блокировок. Форма профиля редактируется
сразу (без отдельного режима редактирования). Привязка email и Telegram, а также сразу (без отдельного режима редактирования). Привязка email и Telegram, а также
слияние аккаунтов вынесены в раздел «Аккаунты, привязка и слияние». Внутри Telegram слияние аккаунтов вынесены в раздел «Аккаунты, привязка и слияние».
Mini App пункт **Settings** в системном меню «⋮» Telegram также открывает этот экран, а
ваши настройки отображения (тема, стиль подписей клеток и reduce-motion — кроме языка
интерфейса, который следует за аккаунтом) синхронизируются между вашими устройствами в
Telegram.
**Предпочтения (в какие варианты тебя можно подбирать).** Настройка профиля задаёт варианты **Предпочтения (в какие варианты тебя можно подбирать).** Настройка профиля задаёт варианты
игры — Эрудит, русский Scrabble и английский Scrabble, показанные **сначала Эрудит**, — в игры — Эрудит, русский Scrabble и английский Scrabble, показанные **сначала Эрудит**, — в
@@ -18,8 +18,7 @@ import (
) )
// ErrInvalidInitData is returned when initData fails HMAC validation, is missing // ErrInvalidInitData is returned when initData fails HMAC validation, is missing
// the hash, is malformed, is older than the freshness window, or identifies a bot // the hash, is malformed, or is older than the freshness window.
// user (is_bot), which is denied.
var ErrInvalidInitData = errors.New("initdata: invalid telegram init data") var ErrInvalidInitData = errors.New("initdata: invalid telegram init data")
// defaultMaxAge bounds how old a validated initData payload may be. // defaultMaxAge bounds how old a validated initData payload may be.
@@ -121,7 +120,6 @@ func parseUser(userJSON string) (User, error) {
} }
var u struct { var u struct {
ID int64 `json:"id"` ID int64 `json:"id"`
IsBot bool `json:"is_bot"`
Username string `json:"username"` Username string `json:"username"`
FirstName string `json:"first_name"` FirstName string `json:"first_name"`
LanguageCode string `json:"language_code"` LanguageCode string `json:"language_code"`
@@ -129,12 +127,6 @@ func parseUser(userJSON string) (User, error) {
if err := json.Unmarshal([]byte(userJSON), &u); err != nil || u.ID == 0 { if err := json.Unmarshal([]byte(userJSON), &u); err != nil || u.ID == 0 {
return User{}, ErrInvalidInitData return User{}, ErrInvalidInitData
} }
// Deny bot principals: the HMAC has already proved Telegram signed this payload, so is_bot==true
// is Telegram itself attesting the launching user is a bot. A real user opening the Mini App
// never carries it, so reject defensively rather than provision an account for a bot.
if u.IsBot {
return User{}, ErrInvalidInitData
}
return User{ return User{
ExternalID: strconv.FormatInt(u.ID, 10), ExternalID: strconv.FormatInt(u.ID, 10),
Username: u.Username, Username: u.Username,
@@ -83,28 +83,3 @@ func TestValidateRejects(t *testing.T) {
} }
}) })
} }
func TestValidateBotUser(t *testing.T) {
t.Run("is_bot true is denied", func(t *testing.T) {
initData := signInitData(testToken, map[string]string{
"auth_date": strconv.FormatInt(time.Now().Unix(), 10),
"user": `{"id":42,"is_bot":true,"first_name":"Robo"}`,
})
if _, err := NewHMACValidator(testToken).Validate(initData); !errors.Is(err, ErrInvalidInitData) {
t.Errorf("err = %v, want ErrInvalidInitData", err)
}
})
t.Run("is_bot false is allowed", func(t *testing.T) {
initData := signInitData(testToken, map[string]string{
"auth_date": strconv.FormatInt(time.Now().Unix(), 10),
"user": `{"id":42,"is_bot":false,"first_name":"Thomas"}`,
})
u, err := NewHMACValidator(testToken).Validate(initData)
if err != nil {
t.Fatalf("validate: %v", err)
}
if u.ExternalID != "42" || u.FirstName != "Thomas" {
t.Errorf("user = %+v, want {42 Thomas}", u)
}
})
}
-5
View File
@@ -49,11 +49,6 @@
/* Telegram device safe-area top (the notch); TG's own nav controls sit between it and /* Telegram device safe-area top (the notch); TG's own nav controls sit between it and
--tg-content-top, so the in-app header aligns to that band, 0 elsewhere. */ --tg-content-top, so the in-app header aligns to that band, 0 elsewhere. */
--tg-safe-top: 0px; --tg-safe-top: 0px;
/* Telegram device safe-area bottom / sides (home indicator; landscape notch), 0 elsewhere —
the screen pads its bottom and left/right edges by these so content clears the cut-outs. */
--tg-safe-bottom: 0px;
--tg-safe-left: 0px;
--tg-safe-right: 0px;
--font: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, --font: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial,
"Noto Sans", "Liberation Sans", sans-serif; "Noto Sans", "Liberation Sans", sans-serif;
--shadow: 0 1px 2px rgba(0, 0, 0, 0.08), 0 6px 16px rgba(0, 0, 0, 0.06); --shadow: 0 1px 2px rgba(0, 0, 0, 0.08), 0 6px 16px rgba(0, 0, 0, 0.06);
-17
View File
@@ -101,12 +101,6 @@
bottom input — chat, word-check — stays above an open soft keyboard without the page bottom input — chat, word-check — stays above an open soft keyboard without the page
scrolling; falls back to the full height where the var is unset. */ scrolling; falls back to the full height where the var is unset. */
height: var(--vvh, 100%); height: var(--vvh, 100%);
/* Clear the landscape notch sides inside Telegram (0 elsewhere). The top inset is owned by the
header; the home-indicator (bottom) inset is owned by the bottom bar — the .tabbar paints its
own chrome into it, and a screen with no tab bar pads its content (.content:last-child) — so
the strip takes the bar's colour rather than the detached content background. */
padding-left: var(--tg-safe-left, 0px);
padding-right: var(--tg-safe-right, 0px);
} }
.content { .content {
flex: 0 1 auto; flex: 0 1 auto;
@@ -122,18 +116,7 @@
display: flex; display: flex;
flex-direction: column; flex-direction: column;
} }
/* No tab bar → the content is the bottom-most element: pad it by the device home-indicator inset
so it clears the cut-out, the strip taking the content's own background. With a tab bar the
.tabbar owns that inset instead (and content is not the last child, so this does not apply). */
.content:last-child {
padding-bottom: var(--tg-safe-bottom, 0px);
}
.tabbar { .tabbar {
flex: 0 0 auto; flex: 0 0 auto;
/* Extend the bottom bar's chrome (the TabBar's --bg-elev) under the device home indicator
inside Telegram (the inset is 0 elsewhere), so the safe-area strip reads as part of the bar
instead of the content background showing through. */
background: var(--bg-elev);
padding-bottom: var(--tg-safe-bottom, 0px);
} }
</style> </style>
+17 -87
View File
@@ -9,7 +9,7 @@ import { GatewayError } from './client';
import { navigate, router } from './router.svelte'; import { navigate, router } from './router.svelte';
import { errorKey, localeFrom, setLocale, t, type Locale } from './i18n/index.svelte'; import { errorKey, localeFrom, setLocale, t, type Locale } from './i18n/index.svelte';
import { languageNeedsServerSync } from './language'; import { languageNeedsServerSync } from './language';
import { applyReduceMotion, applyTelegramTheme, applyTheme, type ThemePref, type TelegramThemeParams } from './theme'; import { applyReduceMotion, applyTelegramTheme, applyTheme, type ThemePref } from './theme';
import { import {
insideTelegram, insideTelegram,
collectTelegramDiag, collectTelegramDiag,
@@ -18,21 +18,15 @@ import {
hasLaunchFragment, hasLaunchFragment,
loadTelegramSDK, loadTelegramSDK,
telegramColorScheme, telegramColorScheme,
telegramThemeParams,
telegramContentSafeAreaTop, telegramContentSafeAreaTop,
telegramSafeAreaInset, telegramSafeAreaTop,
telegramDisableVerticalSwipes, telegramDisableVerticalSwipes,
telegramShowSettingsButton,
telegramHaptic, telegramHaptic,
telegramLaunch, telegramLaunch,
type TelegramLaunch, type TelegramLaunch,
telegramOnEvent, telegramOnEvent,
telegramSetChrome, telegramSetChrome,
telegramCloudAvailable,
telegramCloudGet,
telegramCloudSet,
} from './telegram'; } from './telegram';
import { CLOUD_PREFS_KEY, decodeClientPrefs, encodeClientPrefs } from './cloudprefs';
import { parseStartParam } from './deeplink'; import { parseStartParam } from './deeplink';
import { clearSession, loadPrefs, loadSession, saveSession, savePrefs } from './session'; import { clearSession, loadPrefs, loadSession, saveSession, savePrefs } from './session';
import { connection, reportOffline, reportOnline, resetConnection } from './connection.svelte'; import { connection, reportOffline, reportOnline, resetConnection } from './connection.svelte';
@@ -533,25 +527,17 @@ function syncTelegramChrome(): void {
} }
/** /**
* syncTelegramSafeArea mirrors Telegram's safe-area insets into CSS vars: the content-safe-area top * syncTelegramSafeArea mirrors Telegram's content-safe-area top inset (the height its native
* (the height Telegram's native nav overlays the viewport in fullscreen) into --tg-content-top * nav overlays the viewport in fullscreen) into the --tg-content-top CSS var and toggles a
* (which also toggles the `tg-fullscreen` class so the header drops below the nav and centres the * `tg-fullscreen` class, so the header can drop below the nav and centre the title in its
* title in its band), and the device safe-area insets — notch / status bar (top), home indicator * band. Called on launch and on Telegram's safe-area / fullscreen change events.
* (bottom) and the landscape notch sides (left / right) — into --tg-safe-top / --tg-safe-bottom /
* --tg-safe-left / --tg-safe-right, so the header, rack and screen edges clear the device cut-outs.
* Called on launch and on Telegram's safe-area / fullscreen change events.
*/ */
function syncTelegramSafeArea(): void { function syncTelegramSafeArea(): void {
if (typeof document === 'undefined') return; if (typeof document === 'undefined') return;
const root = document.documentElement;
const top = telegramContentSafeAreaTop(); const top = telegramContentSafeAreaTop();
const safe = telegramSafeAreaInset(); document.documentElement.style.setProperty('--tg-content-top', `${top}px`);
root.style.setProperty('--tg-content-top', `${top}px`); document.documentElement.style.setProperty('--tg-safe-top', `${telegramSafeAreaTop()}px`);
root.style.setProperty('--tg-safe-top', `${safe.top}px`); document.documentElement.classList.toggle('tg-fullscreen', top > 0);
root.style.setProperty('--tg-safe-bottom', `${safe.bottom}px`);
root.style.setProperty('--tg-safe-left', `${safe.left}px`);
root.style.setProperty('--tg-safe-right', `${safe.right}px`);
root.classList.toggle('tg-fullscreen', top > 0);
} }
/** /**
@@ -568,31 +554,20 @@ function syncViewportHeight(): void {
} }
/** /**
* syncTelegramTheme re-applies Telegram's theme integration — the themeParams token overrides, * applyTelegramChrome applies a Mini App launch's visual integration: Telegram's authoritative
* Telegram's authoritative colour scheme, and the matching chrome — from theme, or from the SDK's * colour scheme and theme, the matching header / background / bottom chrome, the safe-area insets,
* current themeParams when omitted. Called on launch with the launch snapshot and live on the * the swipe-down guard, and immersive fullscreen on mobile. It is idempotent, so both the initial
* themeChanged event, so switching Telegram's light/dark theme while the app is open is picked up * bootstrap and a manual launch retry call it.
* without a relaunch.
*/ */
function syncTelegramTheme(theme: TelegramThemeParams | undefined = telegramThemeParams()): void { function applyTelegramChrome(launch: TelegramLaunch): void {
if (theme) applyTelegramTheme(theme); if (launch.theme) applyTelegramTheme(launch.theme);
// Inside Telegram the colour scheme is Telegram's to decide; force it explicitly so the OS // Inside Telegram the colour scheme is Telegram's to decide; force it explicitly so the OS
// prefers-color-scheme (which leaks into the Telegram Desktop webview) cannot fight it. Falls // prefers-color-scheme (which leaks into the Telegram Desktop webview) cannot fight it. Falls
// back to the stored preference when the SDK omits it. // back to the stored preference when the SDK omits it.
applyTheme(telegramColorScheme() ?? app.theme); applyTheme(telegramColorScheme() ?? app.theme);
// Match Telegram's chrome to the app and stop its swipe-down-to-minimise from fighting tile
// drag / board scroll.
syncTelegramChrome(); syncTelegramChrome();
}
/**
* applyTelegramChrome applies a Mini App launch's visual integration: Telegram's authoritative
* colour scheme and theme (syncTelegramTheme), the matching header / background / bottom chrome,
* the safe-area insets, and the swipe-down-to-minimise guard. It is idempotent, so both the
* initial bootstrap and a manual launch retry call it.
*/
function applyTelegramChrome(launch: TelegramLaunch): void {
syncTelegramTheme(launch.theme);
// Mirror the safe-area insets and stop Telegram's swipe-down-to-minimise from fighting tile drag
// / board scroll.
syncTelegramSafeArea(); syncTelegramSafeArea();
telegramDisableVerticalSwipes(); telegramDisableVerticalSwipes();
} }
@@ -646,19 +621,10 @@ export async function bootstrap(): Promise<void> {
if (insideTelegram()) { if (insideTelegram()) {
const launch = telegramLaunch(); const launch = telegramLaunch();
applyTelegramChrome(launch); applyTelegramChrome(launch);
// Pull the device-independent display prefs (theme / reduce-motion / board labels) from
// CloudStorage in the background so a change on another device follows the user here; the local
// values applied above render instantly, so this reconciles without blocking launch.
void reconcileCloudPrefs();
// Re-sync the safe-area insets whenever Telegram's chrome changes (registered once per load). // Re-sync the safe-area insets whenever Telegram's chrome changes (registered once per load).
telegramOnEvent('contentSafeAreaChanged', syncTelegramSafeArea); telegramOnEvent('contentSafeAreaChanged', syncTelegramSafeArea);
telegramOnEvent('safeAreaChanged', syncTelegramSafeArea); telegramOnEvent('safeAreaChanged', syncTelegramSafeArea);
telegramOnEvent('fullscreenChanged', syncTelegramSafeArea); telegramOnEvent('fullscreenChanged', syncTelegramSafeArea);
// Re-apply the theme live when the user switches Telegram's light/dark mode while the app is open.
telegramOnEvent('themeChanged', () => syncTelegramTheme());
// Telegram's native Settings button (Bot API 7.0) opens our Settings screen; the in-app gear
// entry stays the primary path. No-op on clients predating the button.
telegramShowSettingsButton(() => navigate('/settings'));
await bootTelegram(launch); await bootTelegram(launch);
app.ready = true; app.ready = true;
return; return;
@@ -845,42 +811,6 @@ function persistPrefs(): void {
reduceMotion: app.reduceMotion, reduceMotion: app.reduceMotion,
boardLabels: app.boardLabels, boardLabels: app.boardLabels,
}); });
// Mirror the device-independent display prefs to Telegram CloudStorage so they follow the user
// across devices (no-op outside Telegram / on a client predating it). Locale is excluded — it
// syncs via the durable account (Profile.preferredLanguage) instead.
void telegramCloudSet(
CLOUD_PREFS_KEY,
encodeClientPrefs({ theme: app.theme, reduceMotion: app.reduceMotion, boardLabels: app.boardLabels }),
);
}
/**
* reconcileCloudPrefs pulls the device-independent display prefs (theme / reduce-motion / board
* labels) from Telegram CloudStorage and applies any that differ from the current values, so a
* change made on another Telegram device follows the user here. The local store is the
* instant-render cache (read synchronously at boot); this runs once on launch after it and persists
* what it applied. Theme is not re-applied visually — inside Telegram the colour scheme is
* Telegram's to decide — only its stored value is updated. A no-op outside Telegram or when
* CloudStorage is unavailable; locale is never synced this way (it has its own server reconciler).
*/
async function reconcileCloudPrefs(): Promise<void> {
if (!telegramCloudAvailable()) return;
const cloud = decodeClientPrefs(await telegramCloudGet(CLOUD_PREFS_KEY));
let changed = false;
if (cloud.theme !== undefined && cloud.theme !== app.theme) {
app.theme = cloud.theme;
changed = true;
}
if (cloud.reduceMotion !== undefined && cloud.reduceMotion !== app.reduceMotion) {
app.reduceMotion = cloud.reduceMotion;
applyReduceMotion(app.reduceMotion);
changed = true;
}
if (cloud.boardLabels !== undefined && cloud.boardLabels !== app.boardLabels) {
app.boardLabels = cloud.boardLabels;
changed = true;
}
if (changed) persistPrefs();
} }
export function setTheme(theme: ThemePref): void { export function setTheme(theme: ThemePref): void {
-31
View File
@@ -1,31 +0,0 @@
import { describe, expect, it } from 'vitest';
import { CLOUD_PREFS_KEY, decodeClientPrefs, encodeClientPrefs } from './cloudprefs';
describe('cloudprefs', () => {
it('round-trips the synced client prefs', () => {
const p = { theme: 'dark', reduceMotion: true, boardLabels: 'classic' } as const;
expect(decodeClientPrefs(encodeClientPrefs(p))).toEqual(p);
});
it('never encodes the locale (it syncs via the durable account instead)', () => {
const raw = encodeClientPrefs({ theme: 'light', reduceMotion: false, boardLabels: 'none' });
expect(raw).not.toContain('locale');
});
it('returns an empty partial for missing or malformed input', () => {
expect(decodeClientPrefs(null)).toEqual({});
expect(decodeClientPrefs(undefined)).toEqual({});
expect(decodeClientPrefs('')).toEqual({});
expect(decodeClientPrefs('not json')).toEqual({});
expect(decodeClientPrefs('[1,2,3]')).toEqual({});
});
it('keeps only valid fields and drops unknown or mistyped ones', () => {
const raw = JSON.stringify({ theme: 'neon', reduceMotion: 'yes', boardLabels: 'classic', locale: 'ru' });
expect(decodeClientPrefs(raw)).toEqual({ boardLabels: 'classic' });
});
it('exposes the CloudStorage key', () => {
expect(CLOUD_PREFS_KEY).toBe('prefs');
});
});
-49
View File
@@ -1,49 +0,0 @@
// Telegram CloudStorage sync for the device-independent client display preferences — theme,
// reduce-motion and board labels — so they follow the user across their Telegram devices. The
// interface language is intentionally excluded: it has its own server-side sync
// (Profile.preferredLanguage) plus an on-launch reconciler, and mixing it in here would fight that.
// The pure encode/decode is kept free of the SDK and the DOM so it unit-tests in the node
// environment; the CloudStorage transport wrappers live in telegram.ts and the wiring (mirror on
// save, reconcile on launch) in app.svelte.ts.
import type { ThemePref } from './theme';
import type { BoardLabelMode } from './boardlabels';
/** ClientPrefs is the subset of preferences synced across devices via Telegram CloudStorage. */
export interface ClientPrefs {
theme: ThemePref;
reduceMotion: boolean;
boardLabels: BoardLabelMode;
}
/** CLOUD_PREFS_KEY is the Telegram CloudStorage key holding the JSON-encoded ClientPrefs. */
export const CLOUD_PREFS_KEY = 'prefs';
/** encodeClientPrefs serialises the synced client prefs (and only those — never the locale). */
export function encodeClientPrefs(p: ClientPrefs): string {
return JSON.stringify({ theme: p.theme, reduceMotion: p.reduceMotion, boardLabels: p.boardLabels });
}
/**
* decodeClientPrefs parses a CloudStorage payload into a partial ClientPrefs, keeping only valid
* fields and dropping anything unknown, mistyped or malformed — so a value written by a newer or
* older build, or a corrupt entry, never throws and never applies a bad setting. A missing field
* stays absent, so the caller leaves the corresponding local value untouched.
*/
export function decodeClientPrefs(raw: string | null | undefined): Partial<ClientPrefs> {
if (!raw) return {};
let o: Record<string, unknown>;
try {
o = JSON.parse(raw) as Record<string, unknown>;
} catch {
return {};
}
if (!o || typeof o !== 'object') return {};
const out: Partial<ClientPrefs> = {};
if (o.theme === 'auto' || o.theme === 'light' || o.theme === 'dark') out.theme = o.theme;
if (typeof o.reduceMotion === 'boolean') out.reduceMotion = o.reduceMotion;
if (o.boardLabels === 'beginner' || o.boardLabels === 'classic' || o.boardLabels === 'none') {
out.boardLabels = o.boardLabels;
}
return out;
}
-35
View File
@@ -7,9 +7,6 @@ import {
routeExternalLinkInTelegram, routeExternalLinkInTelegram,
telegramLaunch, telegramLaunch,
telegramOpenExternalLink, telegramOpenExternalLink,
telegramThemeParams,
telegramSafeAreaInset,
telegramShowSettingsButton,
} from './telegram'; } from './telegram';
function stubWebApp(initData: string, startParam?: string) { function stubWebApp(initData: string, startParam?: string) {
@@ -47,20 +44,6 @@ describe('telegram launch detection', () => {
expect(launch.startParam).toBe('g123'); expect(launch.startParam).toBe('g123');
expect(launch.theme?.bg_color).toBe('#101418'); expect(launch.theme?.bg_color).toBe('#101418');
}); });
it('telegramThemeParams reads the live palette (undefined outside Telegram)', () => {
expect(telegramThemeParams()).toBeUndefined();
stubWebApp('query_id=abc');
expect(telegramThemeParams()?.bg_color).toBe('#101418');
});
it('telegramSafeAreaInset returns zeros outside Telegram and the SDK insets inside', () => {
expect(telegramSafeAreaInset()).toEqual({ top: 0, bottom: 0, left: 0, right: 0 });
vi.stubGlobal('window', {
Telegram: { WebApp: { initData: 'x', safeAreaInset: { top: 59, bottom: 34, left: 0, right: 0 } } },
});
expect(telegramSafeAreaInset()).toEqual({ top: 59, bottom: 34, left: 0, right: 0 });
});
}); });
describe('telegramOpenExternalLink', () => { describe('telegramOpenExternalLink', () => {
@@ -78,24 +61,6 @@ describe('telegramOpenExternalLink', () => {
}); });
}); });
describe('telegramShowSettingsButton', () => {
afterEach(() => vi.unstubAllGlobals());
it('shows the native Settings button and wires its click inside Telegram', () => {
const onClick = vi.fn();
const show = vi.fn();
const handler = vi.fn();
vi.stubGlobal('window', { Telegram: { WebApp: { SettingsButton: { onClick, show } } } });
telegramShowSettingsButton(handler);
expect(onClick).toHaveBeenCalledWith(handler);
expect(show).toHaveBeenCalled();
});
it('is a no-op without the SDK button (older client / outside Telegram)', () => {
expect(() => telegramShowSettingsButton(() => {})).not.toThrow();
});
});
describe('routeExternalLinkInTelegram', () => { describe('routeExternalLinkInTelegram', () => {
afterEach(() => vi.unstubAllGlobals()); afterEach(() => vi.unstubAllGlobals());
+6 -71
View File
@@ -41,16 +41,6 @@ interface TelegramWebApp {
onClick?: (cb: () => void) => void; onClick?: (cb: () => void) => void;
offClick?: (cb: () => void) => void; offClick?: (cb: () => void) => void;
}; };
SettingsButton?: {
show?: () => void;
hide?: () => void;
onClick?: (cb: () => void) => void;
offClick?: (cb: () => void) => void;
};
CloudStorage?: {
getItem?: (key: string, cb: (err: string | null, value?: string) => void) => void;
setItem?: (key: string, value: string, cb?: (err: string | null, ok?: boolean) => void) => void;
};
} }
function webApp(): TelegramWebApp | undefined { function webApp(): TelegramWebApp | undefined {
@@ -253,15 +243,6 @@ export function telegramColorScheme(): 'light' | 'dark' | undefined {
return webApp()?.colorScheme; return webApp()?.colorScheme;
} }
/**
* telegramThemeParams returns Telegram's current theme palette (WebApp.themeParams), or undefined
* outside Telegram. It reads the live value rather than a launch snapshot, so the themeChanged
* event can re-apply the palette when the user switches Telegram's light/dark theme mid-session.
*/
export function telegramThemeParams(): TelegramThemeParams | undefined {
return webApp()?.themeParams;
}
/** /**
* telegramSetChrome paints Telegram's own header, background and bottom bar to match the * telegramSetChrome paints Telegram's own header, background and bottom bar to match the
* app's colours, so the surrounding Telegram chrome does not clash with the UI. No-op * app's colours, so the surrounding Telegram chrome does not clash with the UI. No-op
@@ -284,15 +265,13 @@ export function telegramContentSafeAreaTop(): number {
} }
/** /**
* telegramSafeAreaInset returns the device safe-area insets (px) — the notch / status bar (top), * telegramSafeAreaTop returns the device safe-area top inset (px) — the notch / status bar
* the home indicator (bottom) and, in landscape, the notch sides (left / right) — from the SDK's * (Bot API 8.0). Telegram's own nav controls sit in the band between it and
* safeAreaInset (Bot API 8.0). All 0 outside Telegram or on a client predating it, so callers can * telegramContentSafeAreaTop, so aligning our header to that band lines it up with them. 0
* pad defensively. Telegram's own nav controls sit in the band between the top inset and * outside Telegram or on older clients.
* telegramContentSafeAreaTop, so aligning our header to that band lines it up with them.
*/ */
export function telegramSafeAreaInset(): { top: number; bottom: number; left: number; right: number } { export function telegramSafeAreaTop(): number {
const i = webApp()?.safeAreaInset; return webApp()?.safeAreaInset?.top ?? 0;
return { top: i?.top ?? 0, bottom: i?.bottom ?? 0, left: i?.left ?? 0, right: i?.right ?? 0 };
} }
/** /**
@@ -303,50 +282,6 @@ export function telegramDisableVerticalSwipes(): void {
webApp()?.disableVerticalSwipes?.(); webApp()?.disableVerticalSwipes?.();
} }
/**
* telegramShowSettingsButton reveals Telegram's native Settings button (in the Mini App's ⋮ menu,
* Bot API 7.0) and routes its taps to handler. A no-op outside Telegram or on a client predating
* the button, so the app's own in-app settings entry stays the primary path. The app registers it
* once per launch (Telegram hides the button when the Mini App closes), so there is no offClick.
*/
export function telegramShowSettingsButton(handler: () => void): void {
const b = webApp()?.SettingsButton;
if (!b?.show) return;
b.onClick?.(handler);
b.show();
}
/** telegramCloudAvailable reports whether Telegram CloudStorage (Bot API 6.9) is usable. */
export function telegramCloudAvailable(): boolean {
return !!webApp()?.CloudStorage?.getItem;
}
/**
* telegramCloudGet reads a value from Telegram CloudStorage, resolving null when the key is absent,
* CloudStorage is unavailable (outside Telegram / a client predating Bot API 6.9), or the read
* errors — so the caller can fall back to the local value.
*/
export function telegramCloudGet(key: string): Promise<string | null> {
const cs = webApp()?.CloudStorage;
if (!cs?.getItem) return Promise.resolve(null);
return new Promise((resolve) => {
cs.getItem!(key, (err, value) => resolve(err ? null : (value ?? null)));
});
}
/**
* telegramCloudSet writes a value to Telegram CloudStorage, resolving once the write settles. It is
* best-effort: a no-op outside Telegram / on an older client, and it swallows write errors, since
* the local store remains the source of truth.
*/
export function telegramCloudSet(key: string, value: string): Promise<void> {
const cs = webApp()?.CloudStorage;
if (!cs?.setItem) return Promise.resolve();
return new Promise((resolve) => {
cs.setItem!(key, value, () => resolve());
});
}
/** Haptic is the set of feedbacks the app triggers. */ /** Haptic is the set of feedbacks the app triggers. */
export type Haptic = 'select' | 'success' | 'error' | 'warning' | 'light' | 'medium' | 'heavy'; export type Haptic = 'select' | 'success' | 'error' | 'warning' | 'light' | 'medium' | 'heavy';