Documentation
¶
Overview ¶
Package tmaauth validates and creates Telegram Mini App init data, the signed query string a Mini App receives in window.Telegram.WebApp.initData.
Create a validator with NewTmaAuth using the bot token that issued the init data and a maximum age, then call TmaAuth.ParseToken on the raw init data sent by the client. Clients commonly send it in an Authorization header as "tma <initData>" (see AuthorizationPrefixTMA); strip the scheme before parsing. A TmaAuth holds no resources and needs no cleanup.
Usage ¶
import (
"errors"
"net/http"
"os"
"strings"
"time"
"github.com/go-sphere/telegram-bot/tmaauth"
)
var auth = tmaauth.NewTmaAuth(os.Getenv("TELEGRAM_BOT_TOKEN"), 24*time.Hour)
func userID(r *http.Request) (int64, error) {
initData, ok := strings.CutPrefix(r.Header.Get("Authorization"), tmaauth.AuthorizationPrefixTMA+" ")
if !ok {
return 0, errors.New("missing tma authorization")
}
claims, err := auth.ParseToken(r.Context(), initData)
if err != nil {
return 0, err // invalid signature, expired, or malformed
}
return claims.User.ID, nil
}
TmaAuth.GenerateToken signs Claims with the same token; it is mainly useful for tests and local development, because real init data is created by Telegram.
Validation errors come from github.com/telegram-mini-apps/init-data-golang and can be matched with errors.Is against its exported errors, such as ErrSignInvalid and ErrExpired.
Index ¶
Examples ¶
Constants ¶
const AuthorizationPrefixTMA = "tma"
AuthorizationPrefixTMA is the Authorization header scheme used by Telegram Mini App clients: "Authorization: tma <initData>". The package does not parse headers; callers strip the scheme and the following space before calling TmaAuth.ParseToken.
Variables ¶
var ErrEmptyBotToken = errors.New("tmaauth: bot token is empty")
ErrEmptyBotToken is returned by ParseToken and GenerateToken when the TmaAuth has an empty or whitespace-only bot token, typically a missing configuration value.
Functions ¶
This section is empty.
Types ¶
type Claims ¶
Claims is the parsed Mini App init data, an alias for github.com/telegram-mini-apps/init-data-golang.InitData. User.ID identifies the Telegram user.
type TmaAuth ¶
type TmaAuth struct {
// contains filtered or unexported fields
}
TmaAuth validates and signs Mini App init data for one bot token. Create it with NewTmaAuth. With an empty or whitespace-only bot token (including the zero value) ParseToken and GenerateToken return ErrEmptyBotToken, because a signature keyed by an empty token can be forged by anyone. A TmaAuth is immutable and safe for concurrent use.
func NewTmaAuth ¶
NewTmaAuth returns a TmaAuth for the bot token that issued the init data. expIn is the maximum accepted age of init data, measured from its auth_date; zero or negative disables the expiration check, which is not recommended for production.
func (*TmaAuth) GenerateToken ¶
GenerateToken signs claims with the bot token and returns init data in the query string format accepted by ParseToken. claims.AuthDateRaw (Unix seconds) becomes auth_date; claims.Hash is ignored. Real init data is created by Telegram, so this is mainly useful for tests and local tools.
It returns ErrEmptyBotToken when the TmaAuth has an empty or whitespace-only bot token, and an error when claims is nil or cannot be encoded. ctx is not used.
Example ¶
package main
import (
"context"
"fmt"
"time"
"github.com/go-sphere/telegram-bot/tmaauth"
initdata "github.com/telegram-mini-apps/init-data-golang"
)
const botToken = "123456:test-bot-token"
func main() {
auth := tmaauth.NewTmaAuth(botToken, time.Hour)
token, err := auth.GenerateToken(context.Background(), &tmaauth.Claims{
User: initdata.User{ID: 7, Username: "tester"},
AuthDateRaw: int(time.Now().Unix()),
})
if err != nil {
fmt.Println("generate:", err)
return
}
// A test client would send: "Authorization: tma " + token
claims, err := auth.ParseToken(context.Background(), token)
if err != nil {
fmt.Println("parse:", err)
return
}
fmt.Println(claims.User.ID, claims.User.Username)
}
Output: 7 tester
func (*TmaAuth) ParseToken ¶
ParseToken validates the raw init data query string token (without the "tma " scheme) and returns its parsed claims.
It returns ErrEmptyBotToken when the TmaAuth has an empty or whitespace-only bot token. Otherwise it returns an error, with zero Claims, when the query is malformed, the hash is missing or does not match the bot token, auth_date is missing or invalid while an expiration is configured, or the data is older than expIn. These errors wrap or equal the exported errors of github.com/telegram-mini-apps/init-data-golang (for example ErrSignInvalid, ErrExpired, ErrSignMissing); match them with errors.Is. ctx is not used.
Example ¶
package main
import (
"context"
"fmt"
"net/url"
"strconv"
"time"
"github.com/go-sphere/telegram-bot/tmaauth"
initdata "github.com/telegram-mini-apps/init-data-golang"
)
const botToken = "123456:test-bot-token"
// signedInitData builds init data the way Telegram does, signing it with
// botToken, so the examples run without a real Mini App client.
func signedInitData(user string, authDate time.Time) string {
hash := initdata.Sign(map[string]string{"user": user}, botToken, authDate)
q := url.Values{}
q.Set("user", user)
q.Set("auth_date", strconv.FormatInt(authDate.Unix(), 10))
q.Set("hash", hash)
return q.Encode()
}
func main() {
auth := tmaauth.NewTmaAuth(botToken, time.Hour)
initData := signedInitData(`{"id":42,"first_name":"Ada","username":"ada"}`, time.Now())
claims, err := auth.ParseToken(context.Background(), initData)
if err != nil {
fmt.Println("invalid init data:", err)
return
}
fmt.Println(claims.User.ID, claims.User.Username)
}
Output: 42 ada
Example (Invalid) ¶
package main
import (
"context"
"errors"
"fmt"
"net/url"
"strconv"
"time"
"github.com/go-sphere/telegram-bot/tmaauth"
initdata "github.com/telegram-mini-apps/init-data-golang"
)
const botToken = "123456:test-bot-token"
// signedInitData builds init data the way Telegram does, signing it with
// botToken, so the examples run without a real Mini App client.
func signedInitData(user string, authDate time.Time) string {
hash := initdata.Sign(map[string]string{"user": user}, botToken, authDate)
q := url.Values{}
q.Set("user", user)
q.Set("auth_date", strconv.FormatInt(authDate.Unix(), 10))
q.Set("hash", hash)
return q.Encode()
}
func main() {
auth := tmaauth.NewTmaAuth(botToken, time.Hour)
// Signed by a different bot token.
other := tmaauth.NewTmaAuth("654321:other-token", time.Hour)
foreign, err := other.GenerateToken(context.Background(), &tmaauth.Claims{
User: initdata.User{ID: 42},
AuthDateRaw: int(time.Now().Unix()),
})
if err != nil {
fmt.Println("generate:", err)
return
}
_, err = auth.ParseToken(context.Background(), foreign)
fmt.Println("bad signature:", errors.Is(err, initdata.ErrSignInvalid))
// Correctly signed, but older than the one hour limit.
stale := signedInitData(`{"id":42}`, time.Now().Add(-2*time.Hour))
_, err = auth.ParseToken(context.Background(), stale)
fmt.Println("expired:", errors.Is(err, initdata.ErrExpired))
}
Output: bad signature: true expired: true