Files
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

256 lines
6.3 KiB
Go

package app
import (
"context"
"log"
"net/http"
"net/url"
"os"
"os/signal"
"sync"
"sync/atomic"
"syscall"
"time"
"github.com/luciochen233/luphoto/internal/build"
"github.com/luciochen233/luphoto/internal/config"
"github.com/luciochen233/luphoto/internal/keys"
"github.com/luciochen233/luphoto/internal/process"
"github.com/luciochen233/luphoto/internal/server"
"github.com/luciochen233/luphoto/internal/site"
"github.com/luciochen233/luphoto/internal/watch"
)
const shutdownTimeout = 10 * time.Second
type daemon struct {
mode string
configPath string
logger *log.Logger
cfg atomic.Pointer[config.Config]
builds chan string
keys *keys.Service
handler *server.Handler
root http.Handler
server *server.Server
watchCancel context.CancelFunc
watchDone chan struct{}
watchedRoot string
watchedDelay time.Duration
watching bool
}
func Run(ctx context.Context, mode, configPath string, cfg *config.Config, logger *log.Logger) error {
d := &daemon{mode: mode, configPath: configPath, logger: logger, builds: make(chan string, 1)}
d.cfg.Store(cfg)
siteKey, err := process.SiteKey(cfg.State)
if err != nil {
return err
}
d.keys = keys.New(siteKey, keySettings(cfg))
if mode == "serve" {
d.handler = server.NewHandler(handlerSettings(cfg), d.keys)
d.root = d.handler
} else {
d.root = keys.Only(d.keys)
}
var builder sync.WaitGroup
builder.Add(1)
go func() {
defer builder.Done()
d.buildLoop(ctx)
}()
d.requestBuild("startup")
if d.listens(cfg) {
srv, err := server.Start(cfg.Server.Listen, d.root, logger)
if err != nil {
return err
}
d.server = srv
if mode != "serve" {
logger.Printf("export: serving only %s on %s", site.KeyPath, cfg.Server.Listen)
}
}
d.syncWatcher(ctx, cfg)
hup := make(chan os.Signal, 1)
signal.Notify(hup, syscall.SIGHUP)
defer signal.Stop(hup)
for {
select {
case <-ctx.Done():
logger.Printf("%s: shutting down", mode)
d.stopWatcher()
var err error
if d.server != nil {
err = d.server.Shutdown(shutdownTimeout)
}
builder.Wait()
return err
case <-hup:
d.reload(ctx)
}
}
}
func (d *daemon) listens(cfg *config.Config) bool {
return d.mode == "serve" || string(cfg.Protection.Gate) == site.GateServer
}
func handlerSettings(cfg *config.Config) server.Settings {
return server.Settings{Output: cfg.Paths.Output, HotlinkAllow: cfg.Protection.HotlinkAllow}
}
func keySettings(cfg *config.Config) keys.Settings {
trusted, _ := config.ParsePrefixes(cfg.Server.TrustedProxies)
hosts := append([]string(nil), cfg.Protection.HotlinkAllow...)
if u, err := url.Parse(cfg.Server.BaseURL); err == nil && u.Hostname() != "" {
hosts = append(hosts, u.Hostname())
}
p := cfg.Protection
return keys.Settings{
Output: cfg.Paths.Output,
Gate: string(p.Gate),
Hosts: hosts,
Trusted: trusted,
IPHeader: cfg.Server.ClientIPHeader,
PowBits: p.PowBits,
PhotoLimit: p.PhotoLimit,
MinEntropy: p.MinEntropy,
LandingLimit: p.LandingLimit,
Window: p.Window.Duration,
PassTTL: p.PassTTL.Duration,
}
}
func (d *daemon) requestBuild(reason string) {
select {
case d.builds <- reason:
default:
d.logger.Printf("rebuild queued (%s)", reason)
}
}
func (d *daemon) buildLoop(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
case reason := <-d.builds:
cfg := d.cfg.Load()
d.logger.Printf("build started (%s)", reason)
summary, err := build.Run(ctx, cfg, d.logger)
if err != nil {
if ctx.Err() != nil {
return
}
d.logger.Printf("build failed: %v; previous build stays live", err)
continue
}
d.keys.Reload()
d.logger.Print(summary.String())
}
}
}
func (d *daemon) syncWatcher(ctx context.Context, cfg *config.Config) {
want := cfg.Build.Watch
delay := cfg.Build.Debounce.Duration
if want == d.watching && cfg.Paths.Albums == d.watchedRoot && delay == d.watchedDelay {
return
}
d.stopWatcher()
d.watching = want
d.watchedRoot = cfg.Paths.Albums
d.watchedDelay = delay
if !want {
d.logger.Printf("watch: disabled by build.watch")
return
}
watchCtx, cancel := context.WithCancel(ctx)
done := make(chan struct{})
d.watchCancel = cancel
d.watchDone = done
root := cfg.Paths.Albums
go func() {
defer close(done)
for {
err := watch.Run(watchCtx, root, delay, func(name string) {
d.requestBuild("change in " + name)
}, d.logger)
if watchCtx.Err() != nil {
return
}
d.logger.Printf("watch: %v; restarting in 5s", err)
select {
case <-watchCtx.Done():
return
case <-time.After(5 * time.Second):
}
}
}()
}
func (d *daemon) stopWatcher() {
if d.watchCancel != nil {
d.watchCancel()
<-d.watchDone
d.watchCancel = nil
d.watchDone = nil
}
}
func (d *daemon) reload(ctx context.Context) {
next, err := config.Load(d.configPath)
if err != nil {
d.logger.Printf("reload: keeping the current config: %v", err)
return
}
previous := d.cfg.Load()
if next.Server.Mode != previous.Server.Mode {
d.logger.Printf("reload: server.mode changed to %q; restart the service to switch modes", next.Server.Mode)
}
want := d.listens(next)
switch {
case !want && d.server != nil:
old := d.server
d.server = nil
go func() {
if err := old.Shutdown(shutdownTimeout); err != nil {
d.logger.Printf("reload: closing listener: %v", err)
}
}()
case want && d.server == nil:
srv, err := server.Start(next.Server.Listen, d.root, d.logger)
if err != nil {
d.logger.Printf("reload: cannot listen on %s: %v", next.Server.Listen, err)
} else {
d.server = srv
}
case want && next.Server.Listen != previous.Server.Listen:
srv, err := server.Start(next.Server.Listen, d.root, d.logger)
if err != nil {
d.logger.Printf("reload: cannot listen on %s, keeping %s: %v", next.Server.Listen, previous.Server.Listen, err)
next.Server.Listen = previous.Server.Listen
} else {
old := d.server
d.server = srv
go func() {
if err := old.Shutdown(shutdownTimeout); err != nil {
d.logger.Printf("reload: closing old listener: %v", err)
}
}()
}
}
d.cfg.Store(next)
if d.handler != nil {
d.handler.Update(handlerSettings(next))
}
d.keys.Update(keySettings(next))
d.syncWatcher(ctx, next)
d.logger.Printf("reload: config %s applied", d.configPath)
d.requestBuild("SIGHUP")
}