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() }