-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathberghain.go
More file actions
90 lines (72 loc) · 1.88 KB
/
Copy pathberghain.go
File metadata and controls
90 lines (72 loc) · 1.88 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package berghain
import (
"crypto/hmac"
"crypto/sha256"
"hash"
"log/slog"
"net/http"
"sync"
"time"
)
type LevelConfig struct {
Countdown int
Duration time.Duration
Type ValidationType
// Captcha configuration, required for the turnstile, hcaptcha and
// recaptcha validation types.
CaptchaSitekey string
CaptchaSecret string
// CaptchaVerifyURL overrides the provider siteverify endpoint,
// e.g. for regional endpoints or tests.
CaptchaVerifyURL string
// CaptchaSkipHostnameCheck disables binding the provider-reported
// hostname to the request identity. Provider test keys report a
// fixed hostname, so tests need this; production setups do not.
CaptchaSkipHostnameCheck bool
captchaBodyOnce sync.Once
captchaBody []byte
}
type Berghain struct {
Levels []*LevelConfig
TrustedDomains []string
// HTTPClient is used for captcha siteverify requests.
// Defaults to a client with a 5 second timeout.
HTTPClient *http.Client
secret []byte
hmac sync.Pool
}
var hashAlgo = sha256.New
func NewBerghain(secret []byte) *Berghain {
return &Berghain{
secret: secret,
hmac: sync.Pool{
New: func() any {
return NewZeroHasher(hmac.New(hashAlgo, secret))
},
},
}
}
var defaultHTTPClient = &http.Client{Timeout: 5 * time.Second}
func (b *Berghain) httpClient() *http.Client {
if b.HTTPClient != nil {
return b.HTTPClient
}
return defaultHTTPClient
}
func (b *Berghain) acquireHMAC() hash.Hash {
return b.hmac.Get().(hash.Hash)
}
func (b *Berghain) releaseHMAC(h hash.Hash) {
h.Reset()
b.hmac.Put(h)
}
func (b *Berghain) LevelConfig(level uint8) *LevelConfig {
if level == 0 {
slog.Warn("level cannot be zero, correcting", "old", 0, "new", 1)
}
if level > uint8(len(b.Levels)) {
slog.Warn("level too high, correcting", "old", level, "new", len(b.Levels))
}
level = min(uint8(len(b.Levels)), max(1, level))
return b.Levels[level-1]
}