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>
128 lines
3.9 KiB
Go
128 lines
3.9 KiB
Go
package api
|
|
|
|
import (
|
|
"crypto/hmac"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"net/url"
|
|
"sort"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
// InitData is what a validated Mini App launch tells us.
|
|
type InitData struct {
|
|
User InitUser
|
|
AuthDate time.Time
|
|
StartParam string
|
|
}
|
|
|
|
// InitUser is the Telegram user who opened the Mini App.
|
|
type InitUser struct {
|
|
ID int64 `json:"id"`
|
|
FirstName string `json:"first_name"`
|
|
Username string `json:"username"`
|
|
LanguageCode string `json:"language_code"`
|
|
}
|
|
|
|
// Errors from ValidateInitData.
|
|
var (
|
|
ErrInitDataMissing = errors.New("api: no init data")
|
|
ErrInitDataInvalid = errors.New("api: init data signature is wrong")
|
|
ErrInitDataExpired = errors.New("api: init data is too old")
|
|
)
|
|
|
|
// ValidateInitData checks the initData string a Mini App got from
|
|
// Telegram, as described in "Validating data received via the Mini App":
|
|
//
|
|
// secret_key = HMAC_SHA256(key="WebAppData", message=bot_token)
|
|
// hash = hex(HMAC_SHA256(key=secret_key, message=data_check_string))
|
|
//
|
|
// where data_check_string is every received field except hash, as
|
|
// key=value, sorted by key and joined with line feeds. Only somebody who
|
|
// knows the bot token can produce a matching hash, so a valid initData
|
|
// proves that Telegram vouches for the user in it.
|
|
//
|
|
// maxAge bounds how old the launch may be. Without that bound a leaked
|
|
// initData string would work forever.
|
|
func ValidateInitData(raw, botToken string, maxAge time.Duration, now time.Time) (*InitData, error) {
|
|
if raw == "" {
|
|
return nil, ErrInitDataMissing
|
|
}
|
|
values, err := url.ParseQuery(raw)
|
|
if err != nil {
|
|
return nil, ErrInitDataInvalid
|
|
}
|
|
got, err := hex.DecodeString(values.Get("hash"))
|
|
if err != nil || len(got) != sha256.Size {
|
|
return nil, ErrInitDataInvalid
|
|
}
|
|
secret := hmacSHA256([]byte("WebAppData"), []byte(botToken))
|
|
// The documented string leaves out only "hash". Some clients built
|
|
// theirs without "signature" as well; both are accepted, since either
|
|
// way the hash can only be made with the bot token.
|
|
if !hmac.Equal(got, hmacSHA256(secret, []byte(checkString(values, "hash")))) &&
|
|
!hmac.Equal(got, hmacSHA256(secret, []byte(checkString(values, "hash", "signature")))) {
|
|
return nil, ErrInitDataInvalid
|
|
}
|
|
sec, err := strconv.ParseInt(values.Get("auth_date"), 10, 64)
|
|
if err != nil {
|
|
return nil, ErrInitDataInvalid
|
|
}
|
|
d := &InitData{AuthDate: time.Unix(sec, 0), StartParam: values.Get("start_param")}
|
|
if maxAge > 0 && now.Sub(d.AuthDate) > maxAge {
|
|
return nil, ErrInitDataExpired
|
|
}
|
|
if d.AuthDate.After(now.Add(5 * time.Minute)) {
|
|
return nil, ErrInitDataInvalid // dated in the future
|
|
}
|
|
if err := json.Unmarshal([]byte(values.Get("user")), &d.User); err != nil || d.User.ID == 0 {
|
|
return nil, ErrInitDataInvalid
|
|
}
|
|
return d, nil
|
|
}
|
|
|
|
func checkString(values url.Values, skip ...string) string {
|
|
keys := make([]string, 0, len(values))
|
|
next:
|
|
for k := range values {
|
|
for _, s := range skip {
|
|
if k == s {
|
|
continue next
|
|
}
|
|
}
|
|
keys = append(keys, k)
|
|
}
|
|
sort.Strings(keys)
|
|
lines := make([]string, 0, len(keys))
|
|
for _, k := range keys {
|
|
lines = append(lines, k+"="+values.Get(k))
|
|
}
|
|
return strings.Join(lines, "\n")
|
|
}
|
|
|
|
func hmacSHA256(key, msg []byte) []byte {
|
|
m := hmac.New(sha256.New, key)
|
|
m.Write(msg)
|
|
return m.Sum(nil)
|
|
}
|
|
|
|
// SignInitData builds a valid initData string. Telegram does this in
|
|
// production; tests and local tools use it to act as a Mini App.
|
|
func SignInitData(botToken string, user InitUser, authDate time.Time, startParam string) string {
|
|
u, _ := json.Marshal(user)
|
|
values := url.Values{}
|
|
values.Set("auth_date", strconv.FormatInt(authDate.Unix(), 10))
|
|
values.Set("user", string(u))
|
|
values.Set("query_id", "AAF0test")
|
|
if startParam != "" {
|
|
values.Set("start_param", startParam)
|
|
}
|
|
secret := hmacSHA256([]byte("WebAppData"), []byte(botToken))
|
|
values.Set("hash", hex.EncodeToString(hmacSHA256(secret, []byte(checkString(values, "hash")))))
|
|
return values.Encode()
|
|
}
|