- CHANGELOG.md:v2.8.0 条目(中英双语); - README.md:版本行 2.7.1→2.8.0 + 愿景第 6 条(知识可证明); - doc/releases/v2.8.0.md:双语发版说明(亮点/用法/已知限制); - skills/marqdo-dev/index.mq.md:新增 prove 任务(路径/目录模式/ require_lean/json;参数用 + 行声明升参,check 与 narrative-ratio 通过); - 设计文档 §12.5 标记已合入;发版链接统一指向 doc/releases/v2.8.0.md。
96 lines
1.7 KiB
Go
Executable File
96 lines
1.7 KiB
Go
Executable File
// Package ratelimit ports login attempt throttling from the Rust web plugin.
|
|
package ratelimit
|
|
|
|
import (
|
|
"fmt"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
const (
|
|
maxFails = 5
|
|
windowSec = 900 // 15 minutes
|
|
lockMsg = "Too many failed login attempts. Try again in about 15 minutes."
|
|
)
|
|
|
|
type window struct {
|
|
count uint32
|
|
start int64
|
|
}
|
|
|
|
var (
|
|
mu sync.Mutex
|
|
attempts map[string]*window
|
|
)
|
|
|
|
func nowSecs() int64 {
|
|
return time.Now().Unix()
|
|
}
|
|
|
|
func key(ip, username string) string {
|
|
return ip + "|" + username
|
|
}
|
|
|
|
// Reset clears attempt counters (between listens / tests).
|
|
func Reset() {
|
|
mu.Lock()
|
|
defer mu.Unlock()
|
|
attempts = map[string]*window{}
|
|
}
|
|
|
|
func ensureMap() {
|
|
if attempts == nil {
|
|
attempts = map[string]*window{}
|
|
}
|
|
}
|
|
|
|
// Check returns an error when the client is temporarily locked out.
|
|
func Check(ip, username string) error {
|
|
k := key(ip, username)
|
|
now := nowSecs()
|
|
mu.Lock()
|
|
defer mu.Unlock()
|
|
ensureMap()
|
|
w, ok := attempts[k]
|
|
if !ok {
|
|
return nil
|
|
}
|
|
if now-w.start < windowSec && w.count >= maxFails {
|
|
return fmt.Errorf("%s", lockMsg)
|
|
}
|
|
if now-w.start >= windowSec {
|
|
delete(attempts, k)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// RecordFailure increments the failure counter for IP+username.
|
|
func RecordFailure(ip, username string) {
|
|
k := key(ip, username)
|
|
now := nowSecs()
|
|
mu.Lock()
|
|
defer mu.Unlock()
|
|
ensureMap()
|
|
w, ok := attempts[k]
|
|
if !ok {
|
|
attempts[k] = &window{count: 1, start: now}
|
|
return
|
|
}
|
|
if now-w.start >= windowSec {
|
|
w.count = 0
|
|
w.start = now
|
|
}
|
|
if w.count < ^uint32(0) {
|
|
w.count++
|
|
}
|
|
}
|
|
|
|
// ClearSuccess removes the counter after a successful login.
|
|
func ClearSuccess(ip, username string) {
|
|
k := key(ip, username)
|
|
mu.Lock()
|
|
defer mu.Unlock()
|
|
ensureMap()
|
|
delete(attempts, k)
|
|
}
|