refactor(lib): keep server URL state local

Signed-off-by: Jason Cameron <jason.cameron@stanwith.me>
This commit is contained in:
Jason Cameron
2026-05-14 01:10:29 -04:00
parent c184028d42
commit b250fea00b
4 changed files with 190 additions and 48 deletions
+50 -15
View File
@@ -13,6 +13,7 @@ import (
"net/url"
"strconv"
"strings"
"sync"
"time"
"github.com/golang-jwt/jwt/v5"
@@ -97,6 +98,8 @@ type Server struct {
OGTags *ogtags.OGTagCache
logger *slog.Logger
opts Options
basePrefix string
publicURL string
ed25519Priv ed25519.PrivateKey
hs512Secret []byte
}
@@ -123,6 +126,50 @@ func (s *Server) getRequestLogger(r *http.Request) (*slog.Logger, *http.Request)
return lg, r
}
var anubisBasePrefixMu sync.Mutex
func (s *Server) configuredBasePrefix() string {
if s.basePrefix != "" {
return s.basePrefix
}
return strings.TrimRight(s.opts.BasePrefix, "/")
}
func (s *Server) configuredPublicURL() string {
if s.publicURL != "" {
return s.publicURL
}
return s.opts.PublicUrl
}
func (s *Server) prefixedPath(path string) string {
if !strings.HasPrefix(path, "/") {
path = "/" + path
}
return s.configuredBasePrefix() + path
}
func (s *Server) cookiePath() string {
basePrefix := s.configuredBasePrefix()
if basePrefix == "" {
return "/"
}
return basePrefix + "/"
}
func (s *Server) withAnubisBasePrefix(fn func()) {
anubisBasePrefixMu.Lock()
defer anubisBasePrefixMu.Unlock()
oldBasePrefix := anubis.BasePrefix
anubis.BasePrefix = s.configuredBasePrefix()
defer func() {
anubis.BasePrefix = oldBasePrefix
}()
fn()
}
func (s *Server) getTokenKeyfunc() jwt.Keyfunc {
// return ED25519 key if HS512 is not set
if len(s.hs512Secret) == 0 {
@@ -246,11 +293,7 @@ func (s *Server) maybeReverseProxy(w http.ResponseWriter, r *http.Request, httpS
return
}
// Adjust cookie path if base prefix is not empty
cookiePath := "/"
if anubis.BasePrefix != "" {
cookiePath = strings.TrimSuffix(anubis.BasePrefix, "/") + "/"
}
cookiePath := s.cookiePath()
cr, rule, err := s.check(r, lg)
if err != nil {
@@ -344,11 +387,7 @@ func (s *Server) maybeReverseProxy(w http.ResponseWriter, r *http.Request, httpS
}
func (s *Server) checkRules(w http.ResponseWriter, r *http.Request, cr policy.CheckResult, lg *slog.Logger, rule *policy.Bot) bool {
// Adjust cookie path if base prefix is not empty
cookiePath := "/"
if anubis.BasePrefix != "" {
cookiePath = strings.TrimSuffix(anubis.BasePrefix, "/") + "/"
}
cookiePath := s.cookiePath()
localizer := localization.GetLocalizer(r)
@@ -511,11 +550,7 @@ func (s *Server) PassChallenge(w http.ResponseWriter, r *http.Request) {
return
}
// Adjust cookie path if base prefix is not empty
cookiePath := "/"
if anubis.BasePrefix != "" {
cookiePath = strings.TrimSuffix(anubis.BasePrefix, "/") + "/"
}
cookiePath := s.cookiePath()
if _, err := r.Cookie(anubis.TestCookieName); errors.Is(err, http.ErrNoCookie) {
s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})