Files
LuPhoto/internal/keys/keys.go
T
lucioandClaude Opus 5.5 c87aad0254 Risk-based robot check with server-issued photo keys
The main page and direct photo links open without a prompt. Each
photo's pool is sealed with its own key, handed out by POST /k
(served by the daemon in serve and export mode). The hold-and-solve
card appears only for low-entropy clicks into a collection, too many
low-entropy landings from one IP, or more than photo_limit photos per
window, with escalating proof-of-work and a 429 cap. Build ids now
sort chronologically within the same second.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 22:45:50 -08:00

449 lines
11 KiB
Go

package keys
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/binary"
"encoding/hex"
"encoding/json"
"hash"
"net"
"net/http"
"net/netip"
"net/url"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/luciochen233/luphoto/internal/protect"
"github.com/luciochen233/luphoto/internal/site"
)
const (
bodyLimit = 4 << 10
maxPhotos = 8
tokenRaw = 24
tokenLen = 32
macLen = tokenRaw - 5
challengeTTL = 5 * time.Minute
clockSkew = 30 * time.Second
usedCapacity = 1 << 15
maxNonce = 1 << 53
contextNav = "nav"
contextLand = "land"
challengeKind = 'c'
passKind = 'p'
pageKind = 'g'
pageTTL = 30 * time.Minute
)
type Settings struct {
Output string
Gate string
Hosts []string
Trusted []netip.Prefix
IPHeader string
PowBits int
PhotoLimit int
MinEntropy int
LandingLimit int
Window time.Duration
PassTTL time.Duration
}
type Service struct {
settings atomic.Pointer[Settings]
table atomic.Pointer[table]
macs sync.Pool
builds builds
used used
}
type used struct {
mu sync.Mutex
seen map[[macLen]byte]struct{}
ring [][macLen]byte
next int
}
func (u *used) add(mac [macLen]byte) bool {
u.mu.Lock()
defer u.mu.Unlock()
if _, ok := u.seen[mac]; ok {
return false
}
if len(u.ring) < usedCapacity {
u.ring = append(u.ring, mac)
} else {
delete(u.seen, u.ring[u.next])
u.ring[u.next] = mac
u.next = (u.next + 1) % usedCapacity
}
u.seen[mac] = struct{}{}
return true
}
func New(siteKey []byte, settings Settings) *Service {
s := &Service{}
key := append([]byte(nil), siteKey...)
s.macs.New = func() any { return hmac.New(sha256.New, key) }
s.used.seen = make(map[[macLen]byte]struct{})
s.Update(settings)
return s
}
func (s *Service) Update(settings Settings) {
hosts := make([]string, 0, len(settings.Hosts))
for _, h := range settings.Hosts {
if h = strings.ToLower(strings.TrimSpace(h)); h != "" {
hosts = append(hosts, h)
}
}
settings.Hosts = hosts
previous := s.settings.Swap(&settings)
if previous == nil || previous.Window != settings.Window || s.table.Load() == nil {
s.table.Store(newTable(settings.Window))
}
if previous == nil || previous.Output != settings.Output {
s.builds.reload(settings.Output)
}
}
func (s *Service) Reload() {
if set := s.settings.Load(); set != nil {
s.builds.reload(set.Output)
}
}
func (s *Service) sign(kind byte, bucket [16]byte, head []byte, scope ...string) [32]byte {
mac := s.macs.Get().(hash.Hash)
mac.Reset()
var buf [1 + 16 + 5]byte
buf[0] = kind
copy(buf[1:], bucket[:])
copy(buf[17:], head)
mac.Write(buf[:])
for _, part := range scope {
mac.Write([]byte{0})
mac.Write([]byte(part))
}
var out [32]byte
mac.Sum(out[:0])
s.macs.Put(mac)
return out
}
func (s *Service) token(kind byte, bucket [16]byte, stamp uint32, extra byte, scope ...string) string {
var raw [tokenRaw]byte
binary.BigEndian.PutUint32(raw[:4], stamp)
raw[4] = extra
sum := s.sign(kind, bucket, raw[:5], scope...)
copy(raw[5:], sum[:macLen])
return base64.RawURLEncoding.EncodeToString(raw[:])
}
func (s *Service) open(kind byte, bucket [16]byte, text string, scope ...string) (uint32, byte, [macLen]byte, bool) {
var raw [tokenRaw]byte
var mac [macLen]byte
if len(text) != tokenLen {
return 0, 0, mac, false
}
if n, err := base64.RawURLEncoding.Decode(raw[:], []byte(text)); err != nil || n != tokenRaw {
return 0, 0, mac, false
}
sum := s.sign(kind, bucket, raw[:5], scope...)
if !hmac.Equal(sum[:macLen], raw[5:]) {
return 0, 0, mac, false
}
copy(mac[:], raw[5:])
return binary.BigEndian.Uint32(raw[:4]), raw[4], mac, true
}
func (s *Service) passValid(bucket [16]byte, text string, now time.Time, ttl time.Duration) bool {
expiry, _, _, ok := s.open(passKind, bucket, text)
if !ok {
return false
}
at := time.Unix(int64(expiry), 0)
return now.Before(at) && at.Sub(now) <= ttl+clockSkew
}
func (s *Service) pageValid(bucket [16]byte, text, build, album string, now time.Time) bool {
if text == "" {
return false
}
expiry, _, _, ok := s.open(pageKind, bucket, text, build, album)
if !ok {
return false
}
at := time.Unix(int64(expiry), 0)
return now.Before(at) && at.Sub(now) <= pageTTL+clockSkew
}
func (s *Service) solved(bucket [16]byte, c *challengeAnswer, now time.Time) bool {
if c == nil || c.Nonce > maxNonce {
return false
}
issued, bits, mac, ok := s.open(challengeKind, bucket, c.Token)
if !ok || bits < 1 || bits > 32 {
return false
}
at := time.Unix(int64(issued), 0)
if now.Sub(at) > challengeTTL || at.Sub(now) > clockSkew {
return false
}
var msg [tokenLen + 8]byte
copy(msg[:], c.Token)
binary.BigEndian.PutUint64(msg[tokenLen:], c.Nonce)
sum := sha256.Sum256(msg[:])
if binary.BigEndian.Uint32(sum[:4])>>(32-uint(bits)) != 0 {
return false
}
return s.used.add(mac)
}
type challengeAnswer struct {
Token string `json:"token"`
Nonce uint64 `json:"nonce"`
}
type request struct {
Build string `json:"build"`
Album string `json:"album"`
Photos []string `json:"photos"`
Context string `json:"context"`
Entropy float64 `json:"entropy"`
Pass string `json:"pass"`
Page string `json:"page"`
Challenge *challengeAnswer `json:"challenge"`
}
type granted struct {
Keys map[string]string `json:"keys"`
Pass string `json:"pass,omitempty"`
Page string `json:"page,omitempty"`
Stale bool `json:"stale,omitempty"`
}
type puzzle struct {
Token string `json:"token"`
Bits int `json:"bits"`
}
type challenged struct {
Challenge puzzle `json:"challenge"`
Stale bool `json:"stale,omitempty"`
}
type failure struct {
Error string `json:"error"`
}
func reply(w http.ResponseWriter, status int, body any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
enc := json.NewEncoder(w)
enc.SetEscapeHTML(false)
_ = enc.Encode(body)
}
func (s *Service) ServeHTTP(w http.ResponseWriter, r *http.Request) {
header := w.Header()
header.Set("Cache-Control", "no-store")
set := s.settings.Load()
if set.Gate != site.GateServer {
reply(w, http.StatusNotFound, failure{"off"})
return
}
if r.Method != http.MethodPost {
header.Set("Allow", "POST")
reply(w, http.StatusMethodNotAllowed, failure{"method"})
return
}
if !allowedOrigin(r, set.Hosts) {
reply(w, http.StatusForbidden, failure{"origin"})
return
}
r.Body = http.MaxBytesReader(w, r.Body, bodyLimit)
var req request
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
reply(w, http.StatusBadRequest, failure{"body"})
return
}
if len(req.Photos) > maxPhotos || (req.Context != contextNav && req.Context != contextLand) || !(req.Entropy >= 0 && req.Entropy <= 100) {
reply(w, http.StatusBadRequest, failure{"request"})
return
}
info := s.builds.get(set.Output, req.Build)
if info == nil {
reply(w, http.StatusBadRequest, failure{"build"})
return
}
members := info.album(req.Album)
if members == nil {
reply(w, http.StatusBadRequest, failure{"album"})
return
}
photos := req.Photos[:0]
for _, h := range req.Photos {
if _, ok := members[h]; !ok {
continue
}
dup := false
for _, seen := range photos {
if seen == h {
dup = true
break
}
}
if !dup {
photos = append(photos, h)
}
}
now := time.Now()
bucket := bucketOf(clientIP(r, set))
pass := req.Pass != "" && s.passValid(bucket, req.Pass, now, set.PassTTL)
stale := req.Pass != "" && !pass
page := s.pageValid(bucket, req.Page, req.Build, req.Album, now)
solved := s.solved(bucket, req.Challenge, now)
out := s.table.Load().decide(bucket, now, input{
nav: req.Context == contextNav,
low: req.Entropy < float64(set.MinEntropy),
pass: pass,
page: page,
solved: solved,
photos: len(photos),
photoLimit: set.PhotoLimit,
landings: set.LandingLimit,
powBits: set.PowBits,
})
switch out.verdict {
case limited:
header.Set("Retry-After", strconv.Itoa(max(1, int((out.retry+time.Second-1)/time.Second))))
reply(w, http.StatusTooManyRequests, failure{"limit"})
case challenge:
reply(w, http.StatusOK, challenged{Challenge: puzzle{Token: s.token(challengeKind, bucket, uint32(now.Unix()), byte(out.bits)), Bits: out.bits}, Stale: stale})
default:
body := granted{Keys: make(map[string]string, len(photos)), Stale: stale && !solved}
keyer := protect.NewKeyer(info.secret)
for _, h := range photos {
k := keyer.Photo(h)
body.Keys[h] = hex.EncodeToString(k[:])
}
if solved {
body.Pass = s.token(passKind, bucket, uint32(now.Add(set.PassTTL).Unix()), 1)
}
if !page {
body.Page = s.token(pageKind, bucket, uint32(now.Add(pageTTL).Unix()), 1, req.Build, req.Album)
}
reply(w, http.StatusOK, body)
}
}
func Only(keys http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
header := w.Header()
header.Set("X-Content-Type-Options", "nosniff")
header.Set("Referrer-Policy", "strict-origin-when-cross-origin")
if r.URL.Path != site.KeyPath {
header.Set("Cache-Control", "no-store")
http.NotFound(w, r)
return
}
keys.ServeHTTP(w, r)
})
}
func hostOf(hostport string) string {
if h, _, err := net.SplitHostPort(hostport); err == nil {
return strings.ToLower(h)
}
return strings.ToLower(strings.Trim(hostport, "[]"))
}
func allowedOrigin(r *http.Request, hosts []string) bool {
source := r.Header.Get("Origin")
if source == "" {
source = r.Header.Get("Referer")
}
if source == "" || source == "null" {
return false
}
u, err := url.Parse(source)
if err != nil || u.Host == "" || (u.Scheme != "http" && u.Scheme != "https") {
return false
}
host := strings.ToLower(u.Hostname())
if host == hostOf(r.Host) {
return true
}
for _, allowed := range hosts {
if host == allowed {
return true
}
}
return false
}
func trusted(addr netip.Addr, prefixes []netip.Prefix) bool {
for _, p := range prefixes {
if p.Contains(addr) {
return true
}
}
return false
}
func clientIP(r *http.Request, set *Settings) netip.Addr {
var peer netip.Addr
if ap, err := netip.ParseAddrPort(r.RemoteAddr); err == nil {
peer = ap.Addr().Unmap()
} else if a, err := netip.ParseAddr(r.RemoteAddr); err == nil {
peer = a.Unmap()
}
if set.IPHeader == "" || !peer.IsValid() || !trusted(peer, set.Trusted) {
return peer
}
values := r.Header.Values(set.IPHeader)
var leftmost netip.Addr
for i := len(values) - 1; i >= 0; i-- {
rest := values[i]
for rest != "" {
part := rest
if at := strings.LastIndexByte(rest, ','); at >= 0 {
part, rest = rest[at+1:], rest[:at]
} else {
rest = ""
}
addr, err := netip.ParseAddr(strings.TrimSpace(part))
if err != nil {
if ap, err := netip.ParseAddrPort(strings.TrimSpace(part)); err == nil {
addr = ap.Addr()
} else {
return peer
}
}
addr = addr.Unmap()
if !trusted(addr, set.Trusted) {
return addr
}
leftmost = addr
}
}
if leftmost.IsValid() {
return leftmost
}
return peer
}
func bucketOf(addr netip.Addr) [16]byte {
key := addr.As16()
if addr.Is6() {
clear(key[8:])
}
return key
}