Phase 6: Mini App

A Telegram Mini App served by the core under /app/, embedded in the binary.

- API under /app/api/ with initData validated (HMAC, age) on every call
- Pages: Home, Queue, Buy (target, product, invoice), History, Groups,
  group detail (Overview, Settings, Wallet, Usage) and Me
- Every action runs through the same service, billing and scheduler code
  as the chat, so limits, prices and admin checks are decided on the server
- Texts come from the catalog over the API; layout mirrors for RTL
- Front end in web/miniapp (Vite, React, TypeScript); the build is
  committed and guarded by a source hash test; the Docker image rebuilds it
- MINIAPP_ENABLED with an https PUBLIC_URL; entry points from /app, group
  settings and the over-limit offer
- Browser test (make miniapp-e2e) against a core in test mode
- Fix: each download attempt gets its own scratch directory, so a retry
  cannot lose its file to the cleanup of the failed attempt

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Michilis
2026-11-18 10:27:20 +00:00
co-authored by Claude Fable 5.2
parent 51371da0e0
commit 4f11f939a0
55 changed files with 7069 additions and 6 deletions
+58 -1
View File
@@ -49,7 +49,8 @@ phase; sections for later phases say so.
| `internal/db` | Schema migrations and queries for SQLite and Postgres. |
| `internal/i18n` | go-i18n wrapper, locale aware formatting. |
| `internal/tg` | Narrow Bot API interface, error helpers, the fake Bot API server. |
| `internal/api` | HTTP server: health check, Telegram webhook. |
| `internal/api` | HTTP server: health check, payment webhook, worker protocol, Mini App API. |
| `web/miniapp` | The Mini App front end (Vite, React, TypeScript) and its build, embedded with `go:embed`. |
| `locales` | Translation catalogs, embedded in the binary. |
Dependencies point one way: `bot` uses `service`, `service` uses `sched`,
@@ -351,6 +352,58 @@ Admin-only actions are checked in one place each: `requireAdmin` for
commands and `cbSetting` for buttons, both through `groups.Admins`, which
asks Telegram and caches the answer.
## The Mini App
The Mini App is a second front end to the same rules. It is a single page
app, built once and embedded in the core binary, served under `/app/`, with
a JSON API under `/app/api/`.
```
browser (inside Telegram) core
index.html, app.js, index.css <---- GET /app/... embedded files
Authorization: tma <initData> ----> /app/api/... api.MiniApp
validate initData (HMAC, age)
load user, refuse banned
call bot.App*, service, billing
```
**Authentication.** Telegram gives the app an `initData` string signed with
a key derived from the bot token. The app sends it with every call and
`api.ValidateInitData` checks it every time. There are no sessions and no
cookies, so there is nothing to steal besides a string that expires. The
user ID comes from the validated string and from nowhere else.
**Nothing is decided in the browser.** The app shows prices, limits and
buttons, but every operation goes through the code the chat uses:
| App action | Runs |
| --- | --- |
| Look a link up | `bot.AppProbe`: `service.Gate`, rate limit, `service.Probe` |
| Start a download, resend | `bot.AppDownload`, `bot.AppResend`: `service.Preview`, then `service.Start` |
| Cancel | `sched.CancelDelivery`, owner checked |
| Prioritize | credits or a `skip_queue` invoice, like the chat button |
| Buy | `billing.CreatePurchase`; the price comes from the core's price list |
| Payment detection | `billing.Check`, which asks LNbits |
| Group pages | `groups.Admins.IsAdmin` on every call, then the same settings rows |
So a cache hit, a resend or a tampered request meets the same limits and
the same ledger as a message in the chat. Files and status messages always
arrive in the user's private chat with the bot; a web page cannot receive
them.
**Texts.** The app has no text of its own. `GET /app/api/i18n` returns the
`app` table of the catalog plus the tables it shares with the chat
(product names, units, button and setting labels), in the user's language
with the usual fallback, placeholders rewritten from `{{.Name}}` to
`{Name}` and plurals as CLDR forms. The response also carries the text
direction. The style sheet uses logical properties only, so `dir="rtl"`
mirrors the layout.
**Build.** `web/miniapp/dist` is committed, so `go build` needs no Node.js.
The build writes a hash of its sources next to its output and a Go test
recomputes it, which catches a source change committed without a rebuild.
The Docker image rebuilds the front end from source.
## Internationalization
Handlers never contain user-facing text. They call `i18n.Bundle` with a
@@ -376,6 +429,10 @@ all output. URLs are redacted before they are logged.
`tg/fakeserver`, an HTTP server that speaks enough of the Bot API to push
updates in and record every call, including multipart uploads.
- One opt-in test runs the real yt-dlp against a public test file.
- The Mini App API is tested over real HTTP with initData signed like
Telegram signs it. `make miniapp-e2e` additionally opens the built app in
headless Chromium against a core in test mode and clicks through every
flow; it is opt-in because it needs a browser.
- Payments are tested against `billing/lnbitstest`, a fake LNbits that
speaks the real request and response shapes and lets a test pay invoices,
replay or drop webhooks and take the server down.
+139
View File
@@ -516,3 +516,142 @@ Read from the LNbits source at `v0.12.12` (the target) and `v1.7.1` (current).
change at runtime.
- `/privacy`, `/terms` and `/support` are short texts in the catalog.
Replace them with your own before running a public bot.
## Phase 6
### Verified Telegram Mini App facts
Checked against https://core.telegram.org/bots/webapps on 2026-11-18.
- The page must load `https://telegram.org/js/telegram-web-app.js` in its
head. It provides `window.Telegram.WebApp`.
- `initData` is a query string. It is valid when
`hex(HMAC_SHA256(key=HMAC_SHA256(key="WebAppData", msg=bot_token), msg=data_check_string))`
equals its `hash` field, where the check string is every other field as
`key=value`, sorted by key, joined with line feeds.
- `start_param` in initData carries the `startapp` value of a
`https://t.me/<bot>?startapp=<value>` link. Such links open the bot's
main Mini App, which is set in @BotFather. No Bot API method sets it.
- A launch from an inline keyboard `web_app` button has no start
parameter. Those buttons work in private chats only.
- Theme colors arrive as CSS variables (`--tg-theme-...`), safe areas as
`--tg-safe-area-inset-...` and `--tg-content-safe-area-inset-...`.
- `openLink` opens a URL in the system browser. The page does not say that
it accepts schemes other than http and https.
### Authentication
- Every API call carries `Authorization: tma <initData>`. The core
validates it on each request. There is no session, cookie or token of
our own, so a call can never be more trusted than Telegram's signature.
- initData older than 24 hours is refused, and so is one dated more than
five minutes ahead. Telegram does not refresh initData while an app
stays open, so an app left open for a day has to be opened again. A
shorter window would log people out mid-use; no window would make a
leaked string valid forever.
- The check string is tried as documented (all fields but `hash`), and
also without `signature`. Either way only the bot token can produce the
hash.
- A call without valid initData gets `401` and one sentence in the
language of the browser. A banned user gets `403`.
- The API exists only when `MINIAPP_ENABLED=true`. That setting requires
an https `PUBLIC_URL` and the core refuses to start otherwise (plain
http is accepted for localhost, for development).
### What the app can do, and where the result goes
- A web page cannot receive files. Downloads started in the app, and
resends from its history, post their status message and file in the
user's private chat with the bot. The app says so and shows progress on
the Queue tab.
- Downloads from the app are personal: they resolve entitlement like a
private chat (own pass, own credits, free), never a group's wallet.
- The front end is never trusted. It shows every format and every
product; the core applies limits and prices when the call arrives. A
price sent by the client is ignored for passes, and credits must be an
amount the billing service accepts.
- The shop sells passes and credits. "Pay for this file only" needs a
refused download behind it and stays in the chat; "skip the queue" is
the Prioritize button on the Queue tab. Donations stay in the chat.
- Buy, step 1: the targets offered are the user and the groups they
administer. The API accepts any group the bot is in, the same rule as in
chat, where anybody may pay for a group.
- Payment detection: the app asks `GET /app/api/purchase/<id>` every 2.5
seconds, and each call asks LNbits. This works without a webhook. A
paid purchase also produces the usual "Paid" message in the chat.
- The QR code is made by the core and sent as a PNG data URL, so the app
ships no QR library.
- "Open in wallet" goes through the existing `/pay/<id>` page with
`openLink`, because `openLink` is only documented for web addresses.
- Queue and history are polled (queue every 2 seconds while visible).
There is no push channel; polling is simple and the numbers are small.
- "Audio only" on the Me tab is the default format MP3. Turning it off
returns to "ask every time".
- Rate limits: link lookups share the chat's budget (`RATE_USER_PER_MINUTE`),
starts and resends get twice that, invoices 10 per minute per user.
### Groups in the app
- Telegram has no "list my groups" call. The Groups tab shows groups where
the bot is present, has seen the user at least once, and Telegram
confirms the user as an admin right now (cached for five minutes, like
in chat).
- Every group endpoint checks admin status again. A demoted admin loses
access; a group the bot left is "not found" for everybody.
- Settings are saved as a whole and validated field by field. Site lists
accept a host name or a pasted link and store the host.
- Size and duration caps for a group can only be set here. They can lower
the tier's limit, never raise it; a higher value is stored as the tier's.
- Usage by member covers the last 7 days.
### Front end
- Vite, React and TypeScript, no router and no UI library. About 77 KB of
JavaScript after gzip.
- The build output `web/miniapp/dist` is committed, so `go build` and
`go install` work without Node.js. `make miniapp` rebuilds it. A Go test
fails when it is older than its sources. The Docker build rebuilds it.
- File names are stable (`assets/app.js`) to keep diffs small. The core
sends `Cache-Control: no-cache` with an ETag of the content, so clients
revalidate and pick up a new build at once.
- A Content-Security-Policy allows scripts from the app itself and
telegram.org only, and framing by Telegram's web clients only.
- The lookup card in the app has no thumbnail. An image loaded by the
browser would reveal the user's IP address to the video site; in chat the
thumbnail is fetched by Telegram's servers instead.
- All text comes from the catalog over the API. A test fails when the app
asks for a key the catalog lacks, or when markup contains a literal
sentence.
- Right to left: the direction comes from the language (`ar`, `he`, `fa`,
`ur` and a few more are known as RTL), and the style sheet uses logical
properties. No RTL catalog ships yet, so this is tested by forcing the
direction in the browser test.
- The bot's menu button is left alone. Replacing it with the app would
hide the command list, which is translated per language.
- The built-in catalogs decide the language list on the Me tab. The app
follows the user's language setting, or the Telegram language when none
is set, and reloads its texts when it changes.
### What could and could not be run here
- The API tests run on SQLite and Postgres like the rest of the suite.
- The browser test (`make miniapp-e2e`) ran here in headless Chromium:
lookup and download, cancel, resend, buying a pass, group settings,
group top-up, preferences, a deep link, forced RTL, and the notice
outside Telegram. It is not part of `make check`, because it needs a
browser.
- The app was not opened inside a real Telegram client. The bridge script
is replaced by a stand-in in the browser test. Theme colors, the back
button and haptics follow the documentation but were not seen on a
phone.
- `npm audit` reports an advisory for `picomatch`, a dependency of Vite.
It is a build tool and is not part of what the core serves.
### Fixed on the way
- A worker used one scratch directory per job. When a download failed and
the retry started on another slot of the same worker before the first
slot had finished reporting, the first slot's cleanup deleted the
retry's file, and the job failed with an internal error. It showed up as
a rare test failure on a busy machine. Every attempt now has its own
directory, and a test holds the two slots in exactly that order.
+39
View File
@@ -118,6 +118,7 @@ Put a TLS reverse proxy (Caddy, nginx, Traefik) in front and set
`PUBLIC_URL=https://bot.example.com` when you want any of:
- instant payment settlement (LNbits webhook) and the "Open in wallet" button
- the Mini App
- remote workers across the internet
- Telegram webhooks instead of long polling (`TELEGRAM_MODE=webhook`,
`WEBHOOK_URL`, `WEBHOOK_SECRET`)
@@ -129,12 +130,50 @@ Routes the proxy must pass through:
| `/telegram/webhook` | Telegram (webhook mode only) |
| `/lnbits/webhook/<secret>` | LNbits |
| `/pay/<id>` | Users pressing "Open in wallet" |
| `/app/...` | The Mini App and its API, opened by Telegram clients |
| `/worker/v1/...` | Remote workers. Allow long requests (30 s) and large uploads. |
| `/healthz` | Your monitoring |
Without `PUBLIC_URL` the bot still works: long polling for Telegram,
polling for payments, workers on the same network.
## The Mini App
The Mini App is a small web page that Telegram opens inside the chat. The
core serves it; there is nothing extra to host.
1. Give the core a public HTTPS address and set it (see the section above).
Telegram refuses Mini Apps over plain http.
```sh
PUBLIC_URL=https://bot.example.com
MINIAPP_ENABLED=true
```
2. Restart the core, then open `https://bot.example.com/app/` in a browser.
You should see one sentence asking you to open the page from Telegram.
That means the app is served and refuses strangers, as it should.
3. Tell Telegram where the app lives. In @BotFather: `/mybots`, pick the
bot, **Bot Settings**, **Configure Mini App**, **Enable Mini App**, and
enter `https://bot.example.com/app/`. This is the bot's "main Mini App".
It adds a **Launch app** button to the bot's profile and makes the link
`https://t.me/<your bot>?startapp` work, which the bot uses in groups.
4. Send `/app` to the bot and press the button.
With the app on, `/app` shows an "Open app" button, group admins get a
link from `/settings` straight into their group's page, and a download
that is over the limit offers the shop inside the app.
The app has no login of its own. Telegram signs who the user is, and the
core checks that signature with the bot token on every call. A signature
older than 24 hours is refused, so an app left open for a day asks to be
opened again.
If step 3 is skipped, the button in private chats still works. Only the
`?startapp` links from groups and the profile button need it.
## Health and logs
- `GET /healthz` on the core answers 200 while the database is reachable.