Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 68 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -515,15 +515,80 @@ Validate request from Telegram Webapp

https://core.telegram.org/bots/webapps#validating-data-received-via-the-mini-app

Load the bot token at startup.

```go
// get url values from request
values := req.URL.Query()
token := os.Getenv("TELEGRAM_BOT_TOKEN")
if token == "" {
log.Fatal("TELEGRAM_BOT_TOKEN is not set or empty")
}
```

user, ok := bot.ValidateWebappRequest(values, os.Getenv("TELEGRAM_BOT_TOKEN"))
In the request handler, pass the decoded query values.

```go
user, ok := bot.ValidateWebappRequest(req.URL.Query(), token)
if !ok {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
log.Println(user.ID)
```

It returns only the user. Use `ValidateWebAppInitData` when the full init data is needed.

### `ValidateWebAppInitData(initData, token string) (*WebAppInitData, error)`

Parse the raw `Telegram.WebApp.initData` string and validate its hash with the bot token

https://core.telegram.org/bots/webapps#validating-data-received-via-the-mini-app

```go
data, err := bot.ValidateWebAppInitData(initData, token)
if err == nil {
err = data.CheckAuthDate(time.Hour)
}
if errors.Is(err, bot.ErrorWebAppInitDataExpired) {
http.Error(w, "Expired", http.StatusUnauthorized)
return
}
if err != nil {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
if data.User != nil {
log.Println(data.User.ID)
}
```

### `ValidateWebAppInitDataSignature(initData string, botID int64, publicKey ed25519.PublicKey) (*WebAppInitData, error)`

Parse the raw `Telegram.WebApp.initData` string and validate its Ed25519 signature, for a third party that has the bot ID but not the token

The returned `Hash` is passed through without verification.

https://core.telegram.org/bots/webapps#validating-data-for-third-party-use

Decode the public key at startup.

```go
publicKey, err := hex.DecodeString(bot.WebAppPublicKeyHex)
if err != nil {
panic(err)
}
```

In the request handler, pass the raw init data and the decoded key.

```go
data, err := bot.ValidateWebAppInitDataSignature(initData, botID, publicKey)
if err == nil {
err = data.CheckAuthDate(time.Hour)
}
if err != nil {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
```

### `FileDownloadLink(f *models.File) string`
Expand Down
64 changes: 28 additions & 36 deletions common.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,9 @@ package bot

import (
"crypto/hmac"
"crypto/sha256"
"encoding/json"
"fmt"
"math/rand"
"net/url"
"sort"
"strings"
"sync"
"time"
Expand Down Expand Up @@ -103,48 +100,43 @@ type WebAppUser struct {

// ValidateWebappRequest validates Mini App init data.
// values must already be decoded, as returned by url.ParseQuery or http.Request.URL.Query.
// The function does not modify values.
// It uses the first value per key and leaves values unchanged.
// An empty token, LF in signed names or values, or '=' in signed names returns nil, false.
func ValidateWebappRequest(values url.Values, token string) (user *WebAppUser, ok bool) {
h := values.Get("hash")
fields := prepareWebAppRequest(values, token)
if fields == nil {
return nil, false
}

var vals []string
expected := webAppHMAC(token, webAppDataCheckString(fields))
if !hmac.Equal([]byte(expected), []byte(values.Get("hash"))) {
return nil, false
}

var u WebAppUser

for k, v := range values {
if k == "hash" {
continue
}
if len(v) == 0 {
if v, ok := fields["user"]; ok {
if err := json.Unmarshal([]byte(v), &u); err != nil {
return nil, false
}
vv := v[0]
vals = append(vals, k+"="+vv)
if k == "user" {
errDecodeUser := json.Unmarshal([]byte(vv), &u)
if errDecodeUser != nil {
return nil, false
}
}
}

sort.Slice(vals, func(i, j int) bool {
return vals[i] < vals[j]
})

hmac1 := hmac.New(sha256.New, []byte("WebAppData"))
hmac1.Write([]byte(token))
r1 := hmac1.Sum(nil)

data := []byte(strings.Join(vals, "\n"))

hmac2 := hmac.New(sha256.New, r1)
hmac2.Write(data)
r2 := hmac2.Sum(nil)
return &u, true
}

if h != fmt.Sprintf("%x", r2) {
return nil, false
func prepareWebAppRequest(values url.Values, token string) map[string]string {
if token == "" {
return nil
}

return &u, true
fields := make(map[string]string, len(values))
for k, v := range values {
if k == "hash" {
continue
}
if len(v) == 0 || !isUnambiguousWebAppField(k, v[0]) {
return nil
}
fields[k] = v[0]
}
return fields
}
4 changes: 4 additions & 0 deletions errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ var (
ErrorNotFound = errors.New("not found")
ErrorConflict = errors.New("conflict")
ErrorWebhookReplyUnavailable = errors.New("webhook reply unavailable")
ErrorWebAppInitDataMalformed = errors.New("malformed web app data")
ErrorWebAppInitDataUnsigned = errors.New("web app data has no hash or signature")
ErrorWebAppInitDataInvalid = errors.New("invalid web app data hash or signature")
ErrorWebAppInitDataExpired = errors.New("web app data expired")
)

type TooManyRequestsError struct {
Expand Down
Loading
Loading