Files
LuPhoto/internal/config/config.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

399 lines
11 KiB
Go

package config
import (
"errors"
"fmt"
"io/fs"
"net/netip"
"os"
"path/filepath"
"sort"
"strings"
"time"
"github.com/BurntSushi/toml"
)
const DefaultPath = "/etc/luphoto/config.toml"
type Config struct {
Server Server `toml:"server"`
Paths Paths `toml:"paths"`
Images Images `toml:"images"`
Loading Loading `toml:"loading"`
Build Build `toml:"build"`
Protection Protection `toml:"protection"`
Source string `toml:"-"`
State string `toml:"-"`
}
type Server struct {
Mode string `toml:"mode"`
Listen string `toml:"listen"`
BaseURL string `toml:"base_url"`
TrustedProxies []string `toml:"trusted_proxies"`
ClientIPHeader string `toml:"client_ip_header"`
}
type Paths struct {
Albums string `toml:"albums"`
Output string `toml:"output"`
Cache string `toml:"cache"`
}
type Quality struct {
Top int `toml:"top"`
Mid int `toml:"mid"`
Low int `toml:"low"`
}
type Images struct {
TileSize int `toml:"tile_size"`
Overlap int `toml:"overlap"`
Format string `toml:"format"`
Quality Quality `toml:"quality"`
MinLevels int `toml:"min_levels"`
SeedPx int `toml:"seed_px"`
TileNames string `toml:"tile_names"`
ScrambleCells bool `toml:"scramble_cells"`
MinGrid int `toml:"min_grid"`
}
type Loading struct {
BudgetMS int `toml:"budget_ms"`
MaxDPR float64 `toml:"max_dpr"`
Concurrency int `toml:"concurrency"`
}
type Build struct {
Watch bool `toml:"watch"`
Debounce Duration `toml:"debounce"`
Workers int `toml:"workers"`
KeepBuilds int `toml:"keep_builds"`
}
type Protection struct {
BlockContextMenu bool `toml:"block_context_menu"`
HotlinkAllow []string `toml:"hotlink_allow"`
Decoys int `toml:"decoys"`
Gate GateMode `toml:"gate"`
PowBits int `toml:"pow_bits"`
PhotoLimit int `toml:"photo_limit"`
MinEntropy int `toml:"min_entropy"`
LandingLimit int `toml:"landing_limit"`
Window Duration `toml:"window"`
PassTTL Duration `toml:"pass_ttl"`
}
type GateMode string
func (g *GateMode) UnmarshalTOML(value any) error {
switch v := value.(type) {
case string:
*g = GateMode(strings.TrimSpace(v))
case bool:
if v {
*g = "server"
} else {
*g = "off"
}
default:
return fmt.Errorf("protection.gate must be \"server\" or \"off\"")
}
return nil
}
type Duration struct {
time.Duration
}
func (d *Duration) UnmarshalText(text []byte) error {
parsed, err := time.ParseDuration(strings.TrimSpace(string(text)))
if err != nil {
return err
}
d.Duration = parsed
return nil
}
func (d Duration) MarshalText() ([]byte, error) {
return []byte(d.Duration.String()), nil
}
func Defaults() Config {
return Config{
Server: Server{
Mode: "export",
Listen: "127.0.0.1:8080",
BaseURL: "https://photos.luciochen.com",
TrustedProxies: []string{"127.0.0.1/32", "::1/128"},
ClientIPHeader: "X-Forwarded-For",
},
Paths: Paths{
Albums: "/srv/luphoto/albums",
},
Images: Images{
TileSize: 512,
Overlap: 1,
Format: "webp",
Quality: Quality{Top: 90, Mid: 88, Low: 88},
MinLevels: 6,
SeedPx: 48,
TileNames: "hashed",
ScrambleCells: true,
MinGrid: 3,
},
Loading: Loading{
BudgetMS: 3000,
MaxDPR: 2.0,
Concurrency: 6,
},
Build: Build{
Watch: true,
Debounce: Duration{30 * time.Second},
Workers: 2,
KeepBuilds: 3,
},
Protection: Protection{
BlockContextMenu: true,
HotlinkAllow: []string{"photos.luciochen.com"},
Decoys: 4,
Gate: "server",
PowBits: 20,
PhotoLimit: 400,
MinEntropy: 20,
LandingLimit: 5,
Window: Duration{10 * time.Minute},
PassTTL: Duration{12 * time.Hour},
},
}
}
func Load(path string) (*Config, error) {
cfg := Defaults()
data, err := os.ReadFile(path)
switch {
case err == nil:
meta, decodeErr := toml.Decode(string(data), &cfg)
if decodeErr != nil {
return nil, fmt.Errorf("config %s: %w", path, decodeErr)
}
if unknown := meta.Undecoded(); len(unknown) > 0 {
keys := make([]string, len(unknown))
for i, key := range unknown {
keys[i] = key.String()
}
sort.Strings(keys)
return nil, fmt.Errorf("config %s: unknown keys: %s", path, strings.Join(keys, ", "))
}
cfg.Source = path
case errors.Is(err, fs.ErrNotExist):
cfg.Source = ""
default:
return nil, fmt.Errorf("config %s: %w", path, err)
}
if err := cfg.resolvePaths(); err != nil {
return nil, err
}
if err := cfg.Validate(); err != nil {
return nil, fmt.Errorf("config %s: %w", path, err)
}
return &cfg, nil
}
func (c *Config) resolvePaths() error {
dataRoot, cacheRoot, err := defaultRoots()
if err != nil {
return err
}
if c.Paths.Output == "" {
c.Paths.Output = filepath.Join(dataRoot, "site")
}
if c.Paths.Cache == "" {
c.Paths.Cache = cacheRoot
}
for _, p := range []*string{&c.Paths.Albums, &c.Paths.Output, &c.Paths.Cache} {
abs, err := filepath.Abs(*p)
if err != nil {
return err
}
*p = abs
}
c.State = filepath.Join(filepath.Dir(c.Paths.Output), "state")
return nil
}
func defaultRoots() (string, string, error) {
if os.Geteuid() == 0 || os.Getenv("INVOCATION_ID") != "" {
return "/var/lib/luphoto", "/var/cache/luphoto", nil
}
dataHome := os.Getenv("XDG_DATA_HOME")
if dataHome == "" {
home, err := os.UserHomeDir()
if err != nil {
return "", "", fmt.Errorf("no data directory: %w", err)
}
dataHome = filepath.Join(home, ".local", "share")
}
cacheHome, err := os.UserCacheDir()
if err != nil {
return "", "", fmt.Errorf("no cache directory: %w", err)
}
return filepath.Join(dataHome, "luphoto"), filepath.Join(cacheHome, "luphoto"), nil
}
func (c *Config) Validate() error {
var problems []string
add := func(format string, args ...any) {
problems = append(problems, fmt.Sprintf(format, args...))
}
switch c.Server.Mode {
case "serve", "export":
default:
add("server.mode must be \"serve\" or \"export\", got %q", c.Server.Mode)
}
if c.Server.Listen == "" {
add("server.listen is empty")
}
if c.Server.BaseURL != "" && !strings.HasPrefix(c.Server.BaseURL, "http://") && !strings.HasPrefix(c.Server.BaseURL, "https://") {
add("server.base_url must start with http:// or https://")
}
if c.Paths.Albums == "" {
add("paths.albums is empty")
}
if c.Paths.Output == c.Paths.Cache {
add("paths.output and paths.cache must differ")
}
if within(c.Paths.Output, c.Paths.Albums) || within(c.Paths.Albums, c.Paths.Output) {
add("paths.output and paths.albums must not contain each other")
}
img := c.Images
if img.TileSize < 64 || img.TileSize > 8192 {
add("images.tile_size must be between 64 and 8192")
}
if img.Overlap < 0 || img.Overlap*2 >= img.TileSize {
add("images.overlap must be at least 0 and below half of tile_size")
}
switch img.Format {
case "webp", "avif":
default:
add("images.format must be \"webp\" or \"avif\", got %q", img.Format)
}
for _, q := range []struct {
name string
value int
}{{"top", img.Quality.Top}, {"mid", img.Quality.Mid}, {"low", img.Quality.Low}} {
if q.value < 1 || q.value > 100 {
add("images.quality.%s must be between 1 and 100", q.name)
}
}
if img.MinLevels < 1 || img.MinLevels > 24 {
add("images.min_levels must be between 1 and 24")
}
if img.SeedPx < 8 || img.SeedPx > 512 {
add("images.seed_px must be between 8 and 512")
}
if img.TileNames != "hashed" {
add("images.tile_names must be \"hashed\"")
}
if img.MinGrid < 1 || img.MinGrid > 8 {
add("images.min_grid must be between 1 and 8")
}
if c.Loading.BudgetMS < 100 {
add("loading.budget_ms must be at least 100")
}
if c.Loading.MaxDPR < 1 || c.Loading.MaxDPR > 4 {
add("loading.max_dpr must be between 1 and 4")
}
if c.Loading.Concurrency < 1 || c.Loading.Concurrency > 64 {
add("loading.concurrency must be between 1 and 64")
}
if c.Build.Debounce.Duration < 0 {
add("build.debounce must not be negative")
}
if c.Build.Workers < 1 || c.Build.Workers > 256 {
add("build.workers must be between 1 and 256")
}
if c.Build.KeepBuilds < 1 {
add("build.keep_builds must be at least 1")
}
if c.Protection.Decoys < 0 || c.Protection.Decoys > 16 {
add("protection.decoys must be between 0 and 16")
}
p := c.Protection
switch p.Gate {
case "server", "off":
default:
add("protection.gate must be \"server\" or \"off\", got %q", p.Gate)
}
if p.PowBits < 10 || p.PowBits > 26 {
add("protection.pow_bits must be between 10 and 26")
}
if p.PhotoLimit < 1 || p.PhotoLimit > 1000000 {
add("protection.photo_limit must be between 1 and 1000000")
}
if p.MinEntropy < 0 || p.MinEntropy > 100 {
add("protection.min_entropy must be between 0 and 100")
}
if p.LandingLimit < 1 || p.LandingLimit > 10000 {
add("protection.landing_limit must be between 1 and 10000")
}
if p.Window.Duration < time.Minute || p.Window.Duration > 24*time.Hour {
add("protection.window must be between 1m and 24h")
}
if p.PassTTL.Duration < time.Minute || p.PassTTL.Duration > 30*24*time.Hour {
add("protection.pass_ttl must be between 1m and 720h")
}
if _, err := ParsePrefixes(c.Server.TrustedProxies); err != nil {
add("server.trusted_proxies: %v", err)
}
if h := c.Server.ClientIPHeader; h != "" && strings.IndexFunc(h, func(r rune) bool {
return !(r == '-' || r >= '0' && r <= '9' || r >= 'A' && r <= 'Z' || r >= 'a' && r <= 'z')
}) >= 0 {
add("server.client_ip_header %q is not a header name", h)
}
for _, host := range c.Protection.HotlinkAllow {
if host == "" || strings.ContainsAny(host, "/ ") {
add("protection.hotlink_allow entry %q is not a host name", host)
}
}
if len(problems) > 0 {
return errors.New(strings.Join(problems, "; "))
}
return nil
}
func ParsePrefixes(values []string) ([]netip.Prefix, error) {
out := make([]netip.Prefix, 0, len(values))
for _, value := range values {
value = strings.TrimSpace(value)
if strings.Contains(value, "/") {
prefix, err := netip.ParsePrefix(value)
if err != nil {
return nil, fmt.Errorf("%q is not a CIDR", value)
}
if prefix.Addr().Is4In6() {
prefix = netip.PrefixFrom(prefix.Addr().Unmap(), max(0, prefix.Bits()-96))
}
out = append(out, prefix.Masked())
continue
}
addr, err := netip.ParseAddr(value)
if err != nil {
return nil, fmt.Errorf("%q is not an address or CIDR", value)
}
addr = addr.Unmap()
out = append(out, netip.PrefixFrom(addr, addr.BitLen()))
}
return out, nil
}
func within(parent, child string) bool {
rel, err := filepath.Rel(parent, child)
if err != nil {
return false
}
return rel == "." || (rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)))
}