-
Notifications
You must be signed in to change notification settings - Fork 6
/
validity.go
67 lines (54 loc) · 1.36 KB
/
validity.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package micha
import (
"crypto/hmac"
"crypto/sha256"
"errors"
"fmt"
"net/url"
"sort"
"strings"
)
var (
ErrInvalidHash = errors.New("invalid hash")
)
// ValidateAuthCallback - https://core.telegram.org/widgets/login#checking-authorization
func ValidateAuthCallback(values url.Values, botToken string) error {
secret := sha256.Sum256([]byte(botToken))
return validateHash(values, secret[:])
}
// ValidateWabAppData - https://core.telegram.org/bots/webapps#validating-data-received-via-the-mini-app
func ValidateWabAppData(values url.Values, botToken string) error {
hm := hmac.New(sha256.New, []byte("WebAppData"))
_, err := hm.Write([]byte(botToken))
if err != nil {
return err
}
secret := hm.Sum(nil)
return validateHash(values, secret)
}
func validateHash(values url.Values, secret []byte) error {
hm := hmac.New(sha256.New, secret)
_, err := hm.Write([]byte(buildCheckString(values)))
if err != nil {
return err
}
if fmt.Sprintf("%x", hm.Sum(nil)) != values.Get("hash") {
return ErrInvalidHash
}
return nil
}
func buildCheckString(values url.Values) string {
keys := []string{}
for key := range values {
if key == "hash" {
continue
}
keys = append(keys, key)
}
sort.Strings(keys)
parts := []string{}
for _, key := range keys {
parts = append(parts, fmt.Sprintf("%s=%s", key, values.Get(key)))
}
return strings.Join(parts, "\n")
}