{"repo_name": "anubis", "file_name": "/anubis/cmd/anubis/main.go", "inference_info": {"prefix_code": "package main\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"crypto/ed25519\"\n\t\"crypto/rand\"\n\t\"crypto/tls\"\n\t\"embed\"\n\t\"encoding/hex\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io/fs\"\n\t\"log\"\n\t\"log/slog\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/http/httputil\"\n\t\"net/url\"\n\t\"os\"\n\t\"os/signal\"\n\t\"path/filepath\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/TecharoHQ/anubis/data\"\n\t\"github.com/TecharoHQ/anubis/internal\"\n\tlibanubis \"github.com/TecharoHQ/anubis/lib\"\n\tbotPolicy \"github.com/TecharoHQ/anubis/lib/policy\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/lib/thoth\"\n\t\"github.com/TecharoHQ/anubis/web\"\n\t\"github.com/facebookgo/flagenv\"\n\t_ \"github.com/joho/godotenv/autoload\"\n\t\"github.com/prometheus/client_golang/prometheus/promhttp\"\n\thealthv1 \"google.golang.org/grpc/health/grpc_health_v1\"\n)\n\nvar (\n\tbasePrefix = flag.String(\"base-prefix\", \"\", \"base prefix (root URL) the application is served under e.g. /myapp\")\n\tbind = flag.String(\"bind\", \":8923\", \"network address to bind HTTP to\")\n\tbindNetwork = flag.String(\"bind-network\", \"tcp\", \"network family to bind HTTP to, e.g. unix, tcp\")\n\tchallengeDifficulty = flag.Int(\"difficulty\", anubis.DefaultDifficulty, \"difficulty of the challenge\")\n\tcookieDomain = flag.String(\"cookie-domain\", \"\", \"if set, the top-level domain that the Anubis cookie will be valid for\")\n\tcookieDynamicDomain = flag.Bool(\"cookie-dynamic-domain\", false, \"if set, automatically set the cookie Domain value based on the request domain\")\n\tcookieExpiration = flag.Duration(\"cookie-expiration-time\", anubis.CookieDefaultExpirationTime, \"The amount of time the authorization cookie is valid for\")\n\tcookiePrefix = flag.String(\"cookie-prefix\", \"techaro.lol-anubis\", \"prefix for browser cookies created by Anubis\")\n\tcookiePartitioned = flag.Bool(\"cookie-partitioned\", false, \"if true, sets the partitioned flag on Anubis cookies, enabling CHIPS support\")\n\tforcedLanguage = flag.String(\"forced-language\", \"\", \"if set, this language is being used instead of the one from the request's Accept-Language header\")\n\ths512Secret = flag.String(\"hs512-secret\", \"\", \"secret used to sign JWTs, uses ed25519 if not set\")\n\tcookieSecure = flag.Bool(\"cookie-secure\", true, \"if true, sets the secure flag on Anubis cookies\")\n\ted25519PrivateKeyHex = flag.String(\"ed25519-private-key-hex\", \"\", \"private key used to sign JWTs, if not set a random one will be assigned\")\n\ted25519PrivateKeyHexFile = flag.String(\"ed25519-private-key-hex-file\", \"\", \"file name containing value for ed25519-private-key-hex\")\n\tmetricsBind = flag.String(\"metrics-bind\", \":9090\", \"network address to bind metrics to\")\n\tmetricsBindNetwork = flag.String(\"metrics-bind-network\", \"tcp\", \"network family for the metrics server to bind to\")\n\tsocketMode = flag.String(\"socket-mode\", \"0770\", \"socket mode (permissions) for unix domain sockets.\")\n\trobotsTxt = flag.Bool(\"serve-robots-txt\", false, \"serve a robots.txt file that disallows all robots\")\n\tpolicyFname = flag.String(\"policy-fname\", \"\", \"full path to anubis policy document (defaults to a sensible built-in policy)\")\n\tredirectDomains = flag.String(\"redirect-domains\", \"\", \"list of domains separated by commas which anubis is allowed to redirect to. Leaving this unset allows any domain.\")\n\tslogLevel = flag.String(\"slog-level\", \"INFO\", \"logging level (see https://pkg.go.dev/log/slog#hdr-Levels)\")\n\tstripBasePrefix = flag.Bool(\"strip-base-prefix\", false, \"if true, strips the base prefix from requests forwarded to the target server\")\n\ttarget = flag.String(\"target\", \"http://localhost:3923\", \"target to reverse proxy to, set to an empty string to disable proxying when only using auth request\")\n\ttargetSNI = flag.String(\"target-sni\", \"\", \"if set, the value of the TLS handshake hostname when forwarding requests to the target\")\n\ttargetHost = flag.String(\"target-host\", \"\", \"if set, the value of the Host header when forwarding requests to the target\")\n\ttargetInsecureSkipVerify = flag.Bool(\"target-insecure-skip-verify\", false, \"if true, skips TLS validation for the backend\")\n\thealthcheck = flag.Bool(\"healthcheck\", false, \"run a health check against Anubis\")\n\tuseRemoteAddress = flag.Bool(\"use-remote-address\", false, \"read the client's IP address from the network request, useful for debugging and running Anubis on bare metal\")\n\tdebugBenchmarkJS = flag.Bool(\"debug-benchmark-js\", false, \"respond to every request with a challenge for benchmarking hashrate\")\n\togPassthrough = flag.Bool(\"og-passthrough\", false, \"enable Open Graph tag passthrough\")\n\togTimeToLive = flag.Duration(\"og-expiry-time\", 24*time.Hour, \"Open Graph tag cache expiration time\")\n\togCacheConsiderHost = flag.Bool(\"og-cache-consider-host\", false, \"enable or disable the use of the host in the Open Graph tag cache\")\n\textractResources = flag.String(\"extract-resources\", \"\", \"if set, extract the static resources to the specified folder\")\n\twebmasterEmail = flag.String(\"webmaster-email\", \"\", \"if set, displays webmaster's email on the reject page for appeals\")\n\tversionFlag = flag.Bool(\"version\", false, \"print Anubis version\")\n\txffStripPrivate = flag.Bool(\"xff-strip-private\", true, \"if set, strip private addresses from X-Forwarded-For\")\n\n\tthothInsecure = flag.Bool(\"thoth-insecure\", false, \"if set, connect to Thoth over plain HTTP/2, don't enable this unless support told you to\")\n\tthothURL = flag.String(\"thoth-url\", \"\", \"if set, URL for Thoth, the IP reputation database for Anubis\")\n\tthothToken = flag.String(\"thoth-token\", \"\", \"if set, API token for Thoth, the IP reputation database for Anubis\")\n)\n\nfunc keyFromHex(value string) (ed25519.PrivateKey, error) {\n\tkeyBytes, err := hex.DecodeString(value)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"supplied key is not hex-encoded: %w\", err)\n\t}\n\n\tif len(keyBytes) != ed25519.SeedSize {\n\t\treturn nil, fmt.Errorf(\"supplied key is not %d bytes long, got %d bytes\", ed25519.SeedSize, len(keyBytes))\n\t}\n\n\treturn ed25519.NewKeyFromSeed(keyBytes), nil\n}\n\nfunc doHealthCheck() error {\n\tresp, err := http.Get(\"http://localhost\" + *metricsBind + \"/healthz\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to fetch metrics: %w\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn fmt.Errorf(\"unexpected status code: %d\", resp.StatusCode)\n\t}\n\n\treturn nil\n}\n\n// parseBindNetFromAddr determine bind network and address based on the given network and address.\nfunc parseBindNetFromAddr(address string) (string, string) {\n\tdefaultScheme := \"http://\"\n\tif !strings.Contains(address, \"://\") {\n\t\tif strings.HasPrefix(address, \":\") {\n\t\t\taddress = defaultScheme + \"localhost\" + address\n\t\t} else {\n\t\t\taddress = defaultScheme + address\n\t\t}\n\t}\n\n\tbindUri, err := url.Parse(address)\n\tif err != nil {\n\t\tlog.Fatal(fmt.Errorf(\"failed to parse bind URL: %w\", err))\n\t}\n\n\tswitch bindUri.Scheme {\n\tcase \"unix\":\n\t\treturn \"unix\", bindUri.Path\n\tcase \"tcp\", \"http\", \"https\":\n\t\treturn \"tcp\", bindUri.Host\n\tdefault:\n\t\tlog.Fatal(fmt.Errorf(\"unsupported network scheme %s in address %s\", bindUri.Scheme, address))\n\t}\n\treturn \"\", address\n}\n\nfunc setupListener(network string, address string) (net.Listener, string) {\n\tformattedAddress := \"\"\n\n\tif network == \"\" {\n\t\t// keep compatibility\n\t\tnetwork, address = parseBindNetFromAddr(address)\n\t}\n\n\tswitch network {\n\tcase \"unix\":\n\t\tformattedAddress = \"unix:\" + address\n\tcase \"tcp\":\n\t\tif strings.HasPrefix(address, \":\") { // assume it's just a port e.g. :4259\n\t\t\tformattedAddress = \"http://localhost\" + address\n\t\t} else {\n\t\t\tformattedAddress = \"http://\" + address\n\t\t}\n\tdefault:\n\t\tformattedAddress = fmt.Sprintf(`(%s) %s`, network, address)\n\t}\n\n\tlistener, err := net.Listen(network, address)\n\tif err != nil {\n\t\tlog.Fatal(fmt.Errorf(\"failed to bind to %s: %w\", formattedAddress, err))\n\t}\n\n\t// additional permission handling for unix sockets\n\tif network == \"unix\" {\n\t\tmode, err := strconv.ParseUint(*socketMode, 8, 0)\n\t\tif err != nil {\n\t\t\tlistener.Close()\n\t\t\tlog.Fatal(fmt.Errorf(\"could not parse socket mode %s: %w\", *socketMode, err))\n\t\t}\n\n\t\terr = os.Chmod(address, os.FileMode(mode))\n\t\tif err != nil {\n\t\t\terr := listener.Close()\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"failed to close listener: %v\", err)\n\t\t\t}\n\t\t\tlog.Fatal(fmt.Errorf(\"could not change socket mode: %w\", err))\n\t\t}\n\t}\n\n\treturn listener, formattedAddress\n}\n\n", "suffix_code": "\n\nfunc main() {\n\tflagenv.Parse()\n\tflag.Parse()\n\n\tif *versionFlag {\n\t\tfmt.Println(\"Anubis\", anubis.Version)\n\t\treturn\n\t}\n\n\tinternal.InitSlog(*slogLevel)\n\tinternal.SetHealth(\"anubis\", healthv1.HealthCheckResponse_NOT_SERVING)\n\n\tif *healthcheck {\n\t\tlog.Println(\"running healthcheck\")\n\t\tif err := doHealthCheck(); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\treturn\n\t}\n\n\tif *extractResources != \"\" {\n\t\tif err := extractEmbedFS(data.BotPolicies, \".\", *extractResources); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tif err := extractEmbedFS(web.Static, \"static\", *extractResources); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Printf(\"Extracted embedded static files to %s\\n\", *extractResources)\n\t\treturn\n\t}\n\n\t// install signal handler\n\tctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)\n\tdefer stop()\n\n\twg := new(sync.WaitGroup)\n\n\tif *metricsBind != \"\" {\n\t\twg.Add(1)\n\t\tgo metricsServer(ctx, wg.Done)\n\t}\n\n\tvar rp http.Handler\n\t// when using anubis via Systemd and environment variables, then it is not possible to set targe to an empty string but only to space\n\tif strings.TrimSpace(*target) != \"\" {\n\t\tvar err error\n\t\trp, err = makeReverseProxy(*target, *targetSNI, *targetHost, *targetInsecureSkipVerify)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"can't make reverse proxy: %v\", err)\n\t\t}\n\t}\n\n\tif *cookieDomain != \"\" && *cookieDynamicDomain {\n\t\tlog.Fatalf(\"you can't set COOKIE_DOMAIN and COOKIE_DYNAMIC_DOMAIN at the same time\")\n\t}\n\n\t// Thoth configuration\n\tswitch {\n\tcase *thothURL != \"\" && *thothToken == \"\":\n\t\tslog.Warn(\"THOTH_URL is set but no THOTH_TOKEN is set\")\n\tcase *thothURL == \"\" && *thothToken != \"\":\n\t\tslog.Warn(\"THOTH_TOKEN is set but no THOTH_URL is set\")\n\tcase *thothURL != \"\" && *thothToken != \"\":\n\t\tslog.Debug(\"connecting to Thoth\")\n\t\tthothClient, err := thoth.New(ctx, *thothURL, *thothToken, *thothInsecure)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"can't dial thoth at %s: %v\", *thothURL, err)\n\t\t}\n\n\t\tctx = thoth.With(ctx, thothClient)\n\t}\n\n\tpolicy, err := libanubis.LoadPoliciesOrDefault(ctx, *policyFname, *challengeDifficulty)\n\tif err != nil {\n\t\tlog.Fatalf(\"can't parse policy file: %v\", err)\n\t}\n\n\truleErrorIDs := make(map[string]string)\n\tfor _, rule := range policy.Bots {\n\t\tif rule.Action != config.RuleDeny {\n\t\t\tcontinue\n\t\t}\n\n\t\thash := rule.Hash()\n\t\truleErrorIDs[rule.Name] = hash\n\t}\n\n\t// replace the bot policy rules with a single rule that always benchmarks\n\tif *debugBenchmarkJS {\n\t\tpolicy.Bots = []botPolicy.Bot{{\n\t\t\tName: \"\",\n\t\t\tRules: botPolicy.NewHeaderExistsChecker(\"User-Agent\"),\n\t\t\tAction: config.RuleBenchmark,\n\t\t}}\n\t}\n\tif *basePrefix != \"\" && !strings.HasPrefix(*basePrefix, \"/\") {\n\t\tlog.Fatalf(\"[misconfiguration] base-prefix must start with a slash, eg: /%s\", *basePrefix)\n\t} else if strings.HasSuffix(*basePrefix, \"/\") {\n\t\tlog.Fatalf(\"[misconfiguration] base-prefix must not end with a slash\")\n\t}\n\tif *stripBasePrefix && *basePrefix == \"\" {\n\t\tlog.Fatalf(\"[misconfiguration] strip-base-prefix is set to true, but base-prefix is not set, \" +\n\t\t\t\"this may result in unexpected behavior\")\n\t}\n\n\tvar ed25519Priv ed25519.PrivateKey\n\tif *hs512Secret != \"\" && (*ed25519PrivateKeyHex != \"\" || *ed25519PrivateKeyHexFile != \"\") {\n\t\tlog.Fatal(\"do not specify both HS512 and ED25519 secrets\")\n\t} else if *hs512Secret != \"\" {\n\t\ted25519Priv = ed25519.PrivateKey(*hs512Secret)\n\t} else if *ed25519PrivateKeyHex != \"\" && *ed25519PrivateKeyHexFile != \"\" {\n\t\tlog.Fatal(\"do not specify both ED25519_PRIVATE_KEY_HEX and ED25519_PRIVATE_KEY_HEX_FILE\")\n\t} else if *ed25519PrivateKeyHex != \"\" {\n\t\ted25519Priv, err = keyFromHex(*ed25519PrivateKeyHex)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to parse and validate ED25519_PRIVATE_KEY_HEX: %v\", err)\n\t\t}\n\t} else if *ed25519PrivateKeyHexFile != \"\" {\n\t\thexFile, err := os.ReadFile(*ed25519PrivateKeyHexFile)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to read ED25519_PRIVATE_KEY_HEX_FILE %s: %v\", *ed25519PrivateKeyHexFile, err)\n\t\t}\n\n\t\ted25519Priv, err = keyFromHex(string(bytes.TrimSpace(hexFile)))\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to parse and validate content of ED25519_PRIVATE_KEY_HEX_FILE: %v\", err)\n\t\t}\n\t} else {\n\t\t_, ed25519Priv, err = ed25519.GenerateKey(rand.Reader)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to generate ed25519 key: %v\", err)\n\t\t}\n\n\t\tslog.Warn(\"generating random key, Anubis will have strange behavior when multiple instances are behind the same load balancer target, for more information: see https://anubis.techaro.lol/docs/admin/installation#key-generation\")\n\t}\n\n\tvar redirectDomainsList []string\n\tif *redirectDomains != \"\" {\n\t\tdomains := strings.Split(*redirectDomains, \",\")\n\t\tfor _, domain := range domains {\n\t\t\t_, err = url.Parse(domain)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"cannot parse redirect-domain %q: %s\", domain, err.Error())\n\t\t\t}\n\t\t\tredirectDomainsList = append(redirectDomainsList, strings.TrimSpace(domain))\n\t\t}\n\t} else {\n\t\tslog.Warn(\"REDIRECT_DOMAINS is not set, Anubis will only redirect to the same domain a request is coming from, see https://anubis.techaro.lol/docs/admin/configuration/redirect-domains\")\n\t}\n\n\tanubis.CookieName = *cookiePrefix + \"-auth\"\n\tanubis.TestCookieName = *cookiePrefix + \"-cookie-verification\"\n\tanubis.ForcedLanguage = *forcedLanguage\n\n\t// If OpenGraph configuration values are not set in the config file, use the\n\t// values from flags / envvars.\n\tif !policy.OpenGraph.Enabled {\n\t\tpolicy.OpenGraph.Enabled = *ogPassthrough\n\t\tpolicy.OpenGraph.ConsiderHost = *ogCacheConsiderHost\n\t\tpolicy.OpenGraph.TimeToLive = *ogTimeToLive\n\t\tpolicy.OpenGraph.Override = map[string]string{}\n\t}\n\n\ts, err := libanubis.New(libanubis.Options{\n\t\tBasePrefix: *basePrefix,\n\t\tStripBasePrefix: *stripBasePrefix,\n\t\tNext: rp,\n\t\tPolicy: policy,\n\t\tServeRobotsTXT: *robotsTxt,\n\t\tED25519PrivateKey: ed25519Priv,\n\t\tHS512Secret: []byte(*hs512Secret),\n\t\tCookieDomain: *cookieDomain,\n\t\tCookieDynamicDomain: *cookieDynamicDomain,\n\t\tCookieExpiration: *cookieExpiration,\n\t\tCookiePartitioned: *cookiePartitioned,\n\t\tRedirectDomains: redirectDomainsList,\n\t\tTarget: *target,\n\t\tWebmasterEmail: *webmasterEmail,\n\t\tOpenGraph: policy.OpenGraph,\n\t\tCookieSecure: *cookieSecure,\n\t})\n\tif err != nil {\n\t\tlog.Fatalf(\"can't construct libanubis.Server: %v\", err)\n\t}\n\n\tvar h http.Handler\n\th = s\n\th = internal.RemoteXRealIP(*useRemoteAddress, *bindNetwork, h)\n\th = internal.XForwardedForToXRealIP(h)\n\th = internal.XForwardedForUpdate(*xffStripPrivate, h)\n\th = internal.JA4H(h)\n\n\tsrv := http.Server{Handler: h, ErrorLog: internal.GetFilteredHTTPLogger()}\n\tlistener, listenerUrl := setupListener(*bindNetwork, *bind)\n\tslog.Info(\n\t\t\"listening\",\n\t\t\"url\", listenerUrl,\n\t\t\"difficulty\", *challengeDifficulty,\n\t\t\"serveRobotsTXT\", *robotsTxt,\n\t\t\"target\", *target,\n\t\t\"version\", anubis.Version,\n\t\t\"use-remote-address\", *useRemoteAddress,\n\t\t\"debug-benchmark-js\", *debugBenchmarkJS,\n\t\t\"og-passthrough\", *ogPassthrough,\n\t\t\"og-expiry-time\", *ogTimeToLive,\n\t\t\"base-prefix\", *basePrefix,\n\t\t\"cookie-expiration-time\", *cookieExpiration,\n\t\t\"rule-error-ids\", ruleErrorIDs,\n\t)\n\n\tgo func() {\n\t\t<-ctx.Done()\n\t\tc, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\t\tdefer cancel()\n\t\tif err := srv.Shutdown(c); err != nil {\n\t\t\tlog.Printf(\"cannot shut down: %v\", err)\n\t\t}\n\t}()\n\n\tinternal.SetHealth(\"anubis\", healthv1.HealthCheckResponse_SERVING)\n\n\tif err := srv.Serve(listener); !errors.Is(err, http.ErrServerClosed) {\n\t\tlog.Fatal(err)\n\t}\n\twg.Wait()\n}\n\nfunc metricsServer(ctx context.Context, done func()) {\n\tdefer done()\n\n\tmux := http.NewServeMux()\n\tmux.Handle(\"/metrics\", promhttp.Handler())\n\tmux.HandleFunc(\"/healthz\", func(w http.ResponseWriter, r *http.Request) {\n\t\tst, ok := internal.GetHealth(\"anubis\")\n\t\tif !ok {\n\t\t\tslog.Error(\"health service anubis does not exist, file a bug\")\n\t\t}\n\n\t\tswitch st {\n\t\tcase healthv1.HealthCheckResponse_NOT_SERVING:\n\t\t\thttp.Error(w, \"NOT OK\", http.StatusInternalServerError)\n\t\t\treturn\n\t\tcase healthv1.HealthCheckResponse_SERVING:\n\t\t\tfmt.Fprintln(w, \"OK\")\n\t\t\treturn\n\t\tdefault:\n\t\t\thttp.Error(w, \"UNKNOWN\", http.StatusFailedDependency)\n\t\t\treturn\n\t\t}\n\t})\n\n\tsrv := http.Server{Handler: mux, ErrorLog: internal.GetFilteredHTTPLogger()}\n\tlistener, metricsUrl := setupListener(*metricsBindNetwork, *metricsBind)\n\tslog.Debug(\"listening for metrics\", \"url\", metricsUrl)\n\n\tgo func() {\n\t\t<-ctx.Done()\n\t\tc, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\t\tdefer cancel()\n\t\tif err := srv.Shutdown(c); err != nil {\n\t\t\tlog.Printf(\"cannot shut down: %v\", err)\n\t\t}\n\t}()\n\n\tif err := srv.Serve(listener); !errors.Is(err, http.ErrServerClosed) {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc extractEmbedFS(fsys embed.FS, root string, destDir string) error {\n\treturn fs.WalkDir(fsys, root, func(path string, d fs.DirEntry, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\trelPath, err := filepath.Rel(root, path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdestPath := filepath.Join(destDir, root, relPath)\n\n\t\tif d.IsDir() {\n\t\t\treturn os.MkdirAll(destPath, 0o700)\n\t\t}\n\n\t\tembeddedData, err := fs.ReadFile(fsys, path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn os.WriteFile(destPath, embeddedData, 0o644)\n\t})\n}\n", "middle_code": "func makeReverseProxy(target string, targetSNI string, targetHost string, insecureSkipVerify bool) (http.Handler, error) {\n\ttargetUri, err := url.Parse(target)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to parse target URL: %w\", err)\n\t}\n\ttransport := http.DefaultTransport.(*http.Transport).Clone()\n\tif targetUri.Scheme == \"unix\" {\n\t\taddr := targetUri.Path\n\t\ttargetUri.Path = \"\"\n\t\ttransport.DialContext = func(ctx context.Context, _, _ string) (net.Conn, error) {\n\t\t\tdialer := net.Dialer{}\n\t\t\treturn dialer.DialContext(ctx, \"unix\", addr)\n\t\t}\n\t\ttransport.RegisterProtocol(\"unix\", libanubis.UnixRoundTripper{Transport: transport})\n\t}\n\tif insecureSkipVerify || targetSNI != \"\" {\n\t\ttransport.TLSClientConfig = &tls.Config{}\n\t\tif insecureSkipVerify {\n\t\t\tslog.Warn(\"TARGET_INSECURE_SKIP_VERIFY is set to true, TLS certificate validation will not be performed\", \"target\", target)\n\t\t\ttransport.TLSClientConfig.InsecureSkipVerify = true\n\t\t}\n\t\tif targetSNI != \"\" {\n\t\t\ttransport.TLSClientConfig.ServerName = targetSNI\n\t\t}\n\t}\n\trp := httputil.NewSingleHostReverseProxy(targetUri)\n\trp.Transport = transport\n\tif targetHost != \"\" {\n\t\toriginalDirector := rp.Director\n\t\trp.Director = func(req *http.Request) {\n\t\t\toriginalDirector(req)\n\t\t\treq.Host = targetHost\n\t\t}\n\t}\n\treturn rp, nil\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "go", "sub_task_type": null}, "context_code": [["/anubis/lib/config.go", "package lib\n\nimport (\n\t\"context\"\n\t\"crypto/ed25519\"\n\t\"crypto/rand\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log/slog\"\n\t\"net/http\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/TecharoHQ/anubis/data\"\n\t\"github.com/TecharoHQ/anubis/internal\"\n\t\"github.com/TecharoHQ/anubis/internal/ogtags\"\n\t\"github.com/TecharoHQ/anubis/lib/challenge\"\n\t\"github.com/TecharoHQ/anubis/lib/localization\"\n\t\"github.com/TecharoHQ/anubis/lib/policy\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/web\"\n\t\"github.com/TecharoHQ/anubis/xess\"\n\t\"github.com/a-h/templ\"\n)\n\ntype Options struct {\n\tNext http.Handler\n\tPolicy *policy.ParsedConfig\n\tTarget string\n\tCookieDynamicDomain bool\n\tCookieDomain string\n\tCookieExpiration time.Duration\n\tCookiePartitioned bool\n\tBasePrefix string\n\tWebmasterEmail string\n\tRedirectDomains []string\n\tED25519PrivateKey ed25519.PrivateKey\n\tHS512Secret []byte\n\tStripBasePrefix bool\n\tOpenGraph config.OpenGraph\n\tServeRobotsTXT bool\n\tCookieSecure bool\n}\n\nfunc LoadPoliciesOrDefault(ctx context.Context, fname string, defaultDifficulty int) (*policy.ParsedConfig, error) {\n\tvar fin io.ReadCloser\n\tvar err error\n\n\tif fname != \"\" {\n\t\tfin, err = os.Open(fname)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"can't parse policy file %s: %w\", fname, err)\n\t\t}\n\t} else {\n\t\tfname = \"(data)/botPolicies.yaml\"\n\t\tfin, err = data.BotPolicies.Open(\"botPolicies.yaml\")\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"[unexpected] can't parse builtin policy file %s: %w\", fname, err)\n\t\t}\n\t}\n\n\tdefer func(fin io.ReadCloser) {\n\t\terr := fin.Close()\n\t\tif err != nil {\n\t\t\tslog.Error(\"failed to close policy file\", \"file\", fname, \"err\", err)\n\t\t}\n\t}(fin)\n\n\tanubisPolicy, err := policy.ParseConfig(ctx, fin, fname, defaultDifficulty)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't parse policy file %s: %w\", fname, err)\n\t}\n\tvar validationErrs []error\n\n\tfor _, b := range anubisPolicy.Bots {\n\t\tif _, ok := challenge.Get(b.Challenge.Algorithm); !ok {\n\t\t\tvalidationErrs = append(validationErrs, fmt.Errorf(\"%w %s\", policy.ErrChallengeRuleHasWrongAlgorithm, b.Challenge.Algorithm))\n\t\t}\n\t}\n\n\tif len(validationErrs) != 0 {\n\t\treturn nil, fmt.Errorf(\"can't do final validation of Anubis config: %w\", errors.Join(validationErrs...))\n\t}\n\n\treturn anubisPolicy, err\n}\n\nfunc New(opts Options) (*Server, error) {\n\tif opts.ED25519PrivateKey == nil && opts.HS512Secret == nil {\n\t\tslog.Debug(\"opts.PrivateKey not set, generating a new one\")\n\t\t_, priv, err := ed25519.GenerateKey(rand.Reader)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"lib: can't generate private key: %v\", err)\n\t\t}\n\t\topts.ED25519PrivateKey = priv\n\t}\n\n\tanubis.BasePrefix = opts.BasePrefix\n\n\tresult := &Server{\n\t\tnext: opts.Next,\n\t\ted25519Priv: opts.ED25519PrivateKey,\n\t\ths512Secret: opts.HS512Secret,\n\t\tpolicy: opts.Policy,\n\t\topts: opts,\n\t\tOGTags: ogtags.NewOGTagCache(opts.Target, opts.Policy.OpenGraph, opts.Policy.Store),\n\t\tstore: opts.Policy.Store,\n\t}\n\n\tmux := http.NewServeMux()\n\txess.Mount(mux)\n\n\t// Helper to add global prefix\n\tregisterWithPrefix := func(pattern string, handler http.Handler, method string) {\n\t\tif method != \"\" {\n\t\t\tmethod = method + \" \" // methods must end with a space to register with them\n\t\t}\n\n\t\t// Ensure there's no double slash when concatenating BasePrefix and pattern\n\t\tbasePrefix := strings.TrimSuffix(anubis.BasePrefix, \"/\")\n\t\tprefix := method + basePrefix\n\n\t\t// If pattern doesn't start with a slash, add one\n\t\tif !strings.HasPrefix(pattern, \"/\") {\n\t\t\tpattern = \"/\" + pattern\n\t\t}\n\n\t\tmux.Handle(prefix+pattern, handler)\n\t}\n\n\t// Ensure there's no double slash when concatenating BasePrefix and StaticPath\n\tstripPrefix := strings.TrimSuffix(anubis.BasePrefix, \"/\") + anubis.StaticPath\n\tregisterWithPrefix(anubis.StaticPath, internal.UnchangingCache(internal.NoBrowsing(http.StripPrefix(stripPrefix, http.FileServerFS(web.Static)))), \"\")\n\n\tif opts.ServeRobotsTXT {\n\t\tregisterWithPrefix(\"/robots.txt\", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\thttp.ServeFileFS(w, r, web.Static, \"static/robots.txt\")\n\t\t}), \"GET\")\n\t\tregisterWithPrefix(\"/.well-known/robots.txt\", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\thttp.ServeFileFS(w, r, web.Static, \"static/robots.txt\")\n\t\t}), \"GET\")\n\t}\n\n\tif opts.Policy.Impressum != nil {\n\t\tregisterWithPrefix(anubis.APIPrefix+\"imprint\", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\ttempl.Handler(\n\t\t\t\tweb.Base(opts.Policy.Impressum.Page.Title, opts.Policy.Impressum.Page, opts.Policy.Impressum, localization.GetLocalizer(r)),\n\t\t\t).ServeHTTP(w, r)\n\t\t}), \"GET\")\n\t}\n\n\tregisterWithPrefix(anubis.APIPrefix+\"pass-challenge\", http.HandlerFunc(result.PassChallenge), \"GET\")\n\tregisterWithPrefix(anubis.APIPrefix+\"check\", http.HandlerFunc(result.maybeReverseProxyHttpStatusOnly), \"\")\n\tregisterWithPrefix(\"/\", http.HandlerFunc(result.maybeReverseProxyOrPage), \"\")\n\n\t//goland:noinspection GoBoolExpressions\n\tif anubis.Version == \"devel\" {\n\t\t// make-challenge is only used in tests. Only enable while version is devel\n\t\tregisterWithPrefix(anubis.APIPrefix+\"make-challenge\", http.HandlerFunc(result.MakeChallenge), \"POST\")\n\t}\n\n\tfor _, implKind := range challenge.Methods() {\n\t\timpl, _ := challenge.Get(implKind)\n\t\timpl.Setup(mux)\n\t}\n\n\tresult.mux = mux\n\n\treturn result, nil\n}\n"], ["/anubis/lib/anubis.go", "package lib\n\nimport (\n\t\"context\"\n\t\"crypto/ed25519\"\n\t\"crypto/rand\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"slices\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/golang-jwt/jwt/v5\"\n\t\"github.com/google/cel-go/common/types\"\n\t\"github.com/google/uuid\"\n\n\t\"github.com/prometheus/client_golang/prometheus\"\n\t\"github.com/prometheus/client_golang/prometheus/promauto\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/TecharoHQ/anubis/decaymap\"\n\t\"github.com/TecharoHQ/anubis/internal\"\n\t\"github.com/TecharoHQ/anubis/internal/dnsbl\"\n\t\"github.com/TecharoHQ/anubis/internal/ogtags\"\n\t\"github.com/TecharoHQ/anubis/lib/challenge\"\n\t\"github.com/TecharoHQ/anubis/lib/localization\"\n\t\"github.com/TecharoHQ/anubis/lib/policy\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/checker\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n\n\t// challenge implementations\n\t_ \"github.com/TecharoHQ/anubis/lib/challenge/metarefresh\"\n\t_ \"github.com/TecharoHQ/anubis/lib/challenge/proofofwork\"\n)\n\nvar (\n\tchallengesIssued = promauto.NewCounterVec(prometheus.CounterOpts{\n\t\tName: \"anubis_challenges_issued\",\n\t\tHelp: \"The total number of challenges issued\",\n\t}, []string{\"method\"})\n\n\tchallengesValidated = promauto.NewCounterVec(prometheus.CounterOpts{\n\t\tName: \"anubis_challenges_validated\",\n\t\tHelp: \"The total number of challenges validated\",\n\t}, []string{\"method\"})\n\n\tdroneBLHits = promauto.NewCounterVec(prometheus.CounterOpts{\n\t\tName: \"anubis_dronebl_hits\",\n\t\tHelp: \"The total number of hits from DroneBL\",\n\t}, []string{\"status\"})\n\n\tfailedValidations = promauto.NewCounterVec(prometheus.CounterOpts{\n\t\tName: \"anubis_failed_validations\",\n\t\tHelp: \"The total number of failed validations\",\n\t}, []string{\"method\"})\n\n\trequestsProxied = promauto.NewCounterVec(prometheus.CounterOpts{\n\t\tName: \"anubis_proxied_requests_total\",\n\t\tHelp: \"Number of requests proxied through Anubis to upstream targets\",\n\t}, []string{\"host\"})\n)\n\ntype Server struct {\n\tnext http.Handler\n\tmux *http.ServeMux\n\tpolicy *policy.ParsedConfig\n\tOGTags *ogtags.OGTagCache\n\ted25519Priv ed25519.PrivateKey\n\ths512Secret []byte\n\topts Options\n\tstore store.Interface\n}\n\nfunc (s *Server) getTokenKeyfunc() jwt.Keyfunc {\n\t// return ED25519 key if HS512 is not set\n\tif len(s.hs512Secret) == 0 {\n\t\treturn func(token *jwt.Token) (interface{}, error) {\n\t\t\treturn s.ed25519Priv.Public().(ed25519.PublicKey), nil\n\t\t}\n\t} else {\n\t\treturn func(token *jwt.Token) (interface{}, error) {\n\t\t\treturn s.hs512Secret, nil\n\t\t}\n\t}\n}\n\nfunc (s *Server) challengeFor(r *http.Request) (*challenge.Challenge, error) {\n\tckies := r.CookiesNamed(anubis.TestCookieName)\n\n\tif len(ckies) == 0 {\n\t\treturn s.issueChallenge(r.Context(), r)\n\t}\n\n\tj := store.JSON[challenge.Challenge]{Underlying: s.store}\n\n\tckie := ckies[0]\n\tchall, err := j.Get(r.Context(), \"challenge:\"+ckie.Value)\n\tif err != nil {\n\t\tif errors.Is(err, store.ErrNotFound) {\n\t\t\treturn s.issueChallenge(r.Context(), r)\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\treturn &chall, nil\n}\n\nfunc (s *Server) issueChallenge(ctx context.Context, r *http.Request) (*challenge.Challenge, error) {\n\tid, err := uuid.NewV7()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar randomData = make([]byte, 256)\n\tif _, err := rand.Read(randomData); err != nil {\n\t\treturn nil, err\n\t}\n\n\tchall := challenge.Challenge{\n\t\tID: id.String(),\n\t\tRandomData: fmt.Sprintf(\"%x\", randomData),\n\t\tIssuedAt: time.Now(),\n\t\tMetadata: map[string]string{\n\t\t\t\"User-Agent\": r.Header.Get(\"User-Agent\"),\n\t\t\t\"X-Real-Ip\": r.Header.Get(\"X-Real-Ip\"),\n\t\t},\n\t}\n\n\tj := store.JSON[challenge.Challenge]{Underlying: s.store}\n\tif err := j.Set(ctx, \"challenge:\"+id.String(), chall, 30*time.Minute); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &chall, err\n}\n\nfunc (s *Server) maybeReverseProxyHttpStatusOnly(w http.ResponseWriter, r *http.Request) {\n\ts.maybeReverseProxy(w, r, true)\n}\n\nfunc (s *Server) maybeReverseProxyOrPage(w http.ResponseWriter, r *http.Request) {\n\ts.maybeReverseProxy(w, r, false)\n}\n\nfunc (s *Server) maybeReverseProxy(w http.ResponseWriter, r *http.Request, httpStatusOnly bool) {\n\tlg := internal.GetRequestLogger(r)\n\n\t// Adjust cookie path if base prefix is not empty\n\tcookiePath := \"/\"\n\tif anubis.BasePrefix != \"\" {\n\t\tcookiePath = strings.TrimSuffix(anubis.BasePrefix, \"/\") + \"/\"\n\t}\n\n\tcr, rule, err := s.check(r)\n\tif err != nil {\n\t\tlg.Error(\"check failed\", \"err\", err)\n\t\tlocalizer := localization.GetLocalizer(r)\n\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s \\\"maybeReverseProxy\\\"\", localizer.T(\"internal_server_error\")))\n\t\treturn\n\t}\n\n\tr.Header.Add(\"X-Anubis-Rule\", cr.Name)\n\tr.Header.Add(\"X-Anubis-Action\", string(cr.Rule))\n\tlg = lg.With(\"check_result\", cr)\n\tpolicy.Applications.WithLabelValues(cr.Name, string(cr.Rule)).Add(1)\n\n\tip := r.Header.Get(\"X-Real-Ip\")\n\n\tif s.handleDNSBL(w, r, ip, lg) {\n\t\treturn\n\t}\n\n\tif s.checkRules(w, r, cr, lg, rule) {\n\t\treturn\n\t}\n\n\tckie, err := r.Cookie(anubis.CookieName)\n\tif err != nil {\n\t\tlg.Debug(\"cookie not found\", \"path\", r.URL.Path)\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.RenderIndex(w, r, rule, httpStatusOnly)\n\t\treturn\n\t}\n\n\tif err := ckie.Valid(); err != nil {\n\t\tlg.Debug(\"cookie is invalid\", \"err\", err)\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.RenderIndex(w, r, rule, httpStatusOnly)\n\t\treturn\n\t}\n\n\tif time.Now().After(ckie.Expires) && !ckie.Expires.IsZero() {\n\t\tlg.Debug(\"cookie expired\", \"path\", r.URL.Path)\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.RenderIndex(w, r, rule, httpStatusOnly)\n\t\treturn\n\t}\n\n\ttoken, err := jwt.ParseWithClaims(ckie.Value, jwt.MapClaims{}, s.getTokenKeyfunc(), jwt.WithExpirationRequired(), jwt.WithStrictDecoding())\n\n\tif err != nil || !token.Valid {\n\t\tlg.Debug(\"invalid token\", \"path\", r.URL.Path, \"err\", err)\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.RenderIndex(w, r, rule, httpStatusOnly)\n\t\treturn\n\t}\n\n\tclaims, ok := token.Claims.(jwt.MapClaims)\n\tif !ok {\n\t\tlg.Debug(\"invalid token claims type\", \"path\", r.URL.Path)\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.RenderIndex(w, r, rule, httpStatusOnly)\n\t\treturn\n\t}\n\n\tpolicyRule, ok := claims[\"policyRule\"].(string)\n\tif !ok {\n\t\tlg.Debug(\"policyRule claim is not a string\")\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.RenderIndex(w, r, rule, httpStatusOnly)\n\t\treturn\n\t}\n\n\tif policyRule != rule.Hash() {\n\t\tlg.Debug(\"user originally passed with a different rule, issuing new challenge\", \"old\", policyRule, \"new\", rule.Name)\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.RenderIndex(w, r, rule, httpStatusOnly)\n\t\treturn\n\t}\n\n\tr.Header.Add(\"X-Anubis-Status\", \"PASS\")\n\ts.ServeHTTPNext(w, r)\n}\n\nfunc (s *Server) checkRules(w http.ResponseWriter, r *http.Request, cr policy.CheckResult, lg *slog.Logger, rule *policy.Bot) bool {\n\t// Adjust cookie path if base prefix is not empty\n\tcookiePath := \"/\"\n\tif anubis.BasePrefix != \"\" {\n\t\tcookiePath = strings.TrimSuffix(anubis.BasePrefix, \"/\") + \"/\"\n\t}\n\n\tlocalizer := localization.GetLocalizer(r)\n\n\tswitch cr.Rule {\n\tcase config.RuleAllow:\n\t\tlg.Debug(\"allowing traffic to origin (explicit)\")\n\t\ts.ServeHTTPNext(w, r)\n\t\treturn true\n\tcase config.RuleDeny:\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\tlg.Info(\"explicit deny\")\n\t\tif rule == nil {\n\t\t\tlg.Error(\"rule is nil, cannot calculate checksum\")\n\t\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s \\\"maybeReverseProxy.RuleDeny\\\"\", localizer.T(\"internal_server_error\")))\n\t\t\treturn true\n\t\t}\n\t\thash := rule.Hash()\n\n\t\tlg.Debug(\"rule hash\", \"hash\", hash)\n\t\ts.respondWithStatus(w, r, fmt.Sprintf(\"%s %s\", localizer.T(\"access_denied\"), hash), s.policy.StatusCodes.Deny)\n\t\treturn true\n\tcase config.RuleChallenge:\n\t\tlg.Debug(\"challenge requested\")\n\tcase config.RuleBenchmark:\n\t\tlg.Debug(\"serving benchmark page\")\n\t\ts.RenderBench(w, r)\n\t\treturn true\n\tdefault:\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\tslog.Error(\"CONFIG ERROR: unknown rule\", \"rule\", cr.Rule)\n\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s \\\"maybeReverseProxy.Rules\\\"\", localizer.T(\"internal_server_error\")))\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (s *Server) handleDNSBL(w http.ResponseWriter, r *http.Request, ip string, lg *slog.Logger) bool {\n\tdb := &store.JSON[dnsbl.DroneBLResponse]{Underlying: s.store, Prefix: \"dronebl:\"}\n\tif s.policy.DNSBL && ip != \"\" {\n\t\tresp, err := db.Get(r.Context(), ip)\n\t\tif err != nil {\n\t\t\tlg.Debug(\"looking up ip in dnsbl\")\n\t\t\tresp, err := dnsbl.Lookup(ip)\n\t\t\tif err != nil {\n\t\t\t\tlg.Error(\"can't look up ip in dnsbl\", \"err\", err)\n\t\t\t}\n\t\t\tdb.Set(r.Context(), ip, resp, 24*time.Hour)\n\t\t\tdroneBLHits.WithLabelValues(resp.String()).Inc()\n\t\t}\n\n\t\tif resp != dnsbl.AllGood {\n\t\t\tlg.Info(\"DNSBL hit\", \"status\", resp.String())\n\t\t\tlocalizer := localization.GetLocalizer(r)\n\t\t\ts.respondWithStatus(w, r, fmt.Sprintf(\"%s: %s, %s https://dronebl.org/lookup?ip=%s\",\n\t\t\t\tlocalizer.T(\"dronebl_entry\"),\n\t\t\t\tresp.String(),\n\t\t\t\tlocalizer.T(\"see_dronebl_lookup\"),\n\t\t\t\tip), s.policy.StatusCodes.Deny)\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (s *Server) MakeChallenge(w http.ResponseWriter, r *http.Request) {\n\tlg := internal.GetRequestLogger(r)\n\tlocalizer := localization.GetLocalizer(r)\n\n\tredir := r.FormValue(\"redir\")\n\tif redir == \"\" {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tencoder := json.NewEncoder(w)\n\t\tlg.Error(\"invalid invocation of MakeChallenge\", \"redir\", redir)\n\t\tencoder.Encode(struct {\n\t\t\tError string `json:\"error\"`\n\t\t}{\n\t\t\tError: localizer.T(\"invalid_invocation\"),\n\t\t})\n\t\treturn\n\t}\n\n\tr.URL.Path = redir\n\n\tencoder := json.NewEncoder(w)\n\tcr, rule, err := s.check(r)\n\tif err != nil {\n\t\tlg.Error(\"check failed\", \"err\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\terr := encoder.Encode(struct {\n\t\t\tError string `json:\"error\"`\n\t\t}{\n\t\t\tError: fmt.Sprintf(\"%s \\\"makeChallenge\\\"\", localizer.T(\"internal_server_error\")),\n\t\t})\n\t\tif err != nil {\n\t\t\tlg.Error(\"failed to encode error response\", \"err\", err)\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t}\n\t\treturn\n\t}\n\tlg = lg.With(\"check_result\", cr)\n\n\tchall, err := s.challengeFor(r)\n\tif err != nil {\n\t\tlg.Error(\"failed to fetch or issue challenge\", \"err\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\terr := encoder.Encode(struct {\n\t\t\tError string `json:\"error\"`\n\t\t}{\n\t\t\tError: fmt.Sprintf(\"%s \\\"makeChallenge\\\"\", localizer.T(\"internal_server_error\")),\n\t\t})\n\t\tif err != nil {\n\t\t\tlg.Error(\"failed to encode error response\", \"err\", err)\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t}\n\t\treturn\n\t}\n\n\ts.SetCookie(w, CookieOpts{Host: r.Host, Name: anubis.TestCookieName, Value: chall.ID})\n\n\terr = encoder.Encode(struct {\n\t\tRules *config.ChallengeRules `json:\"rules\"`\n\t\tChallenge string `json:\"challenge\"`\n\t}{\n\t\tChallenge: chall.RandomData,\n\t\tRules: rule.Challenge,\n\t})\n\tif err != nil {\n\t\tlg.Error(\"failed to encode challenge\", \"err\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\tlg.Debug(\"made challenge\", \"challenge\", chall, \"rules\", rule.Challenge, \"cr\", cr)\n\tchallengesIssued.WithLabelValues(\"api\").Inc()\n}\n\nfunc (s *Server) PassChallenge(w http.ResponseWriter, r *http.Request) {\n\tlg := internal.GetRequestLogger(r)\n\tlocalizer := localization.GetLocalizer(r)\n\n\tredir := r.FormValue(\"redir\")\n\tredirURL, err := url.ParseRequestURI(redir)\n\tif err != nil {\n\t\tlg.Error(\"invalid redirect\", \"err\", err)\n\t\ts.respondWithStatus(w, r, localizer.T(\"invalid_redirect\"), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tswitch redirURL.Scheme {\n\tcase \"\", \"http\", \"https\":\n\t\t// allowed\n\tdefault:\n\t\tlg.Error(\"XSS attempt blocked, invalid redirect scheme\", \"scheme\", redirURL.Scheme)\n\t\ts.respondWithStatus(w, r, localizer.T(\"invalid_redirect\"), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// Adjust cookie path if base prefix is not empty\n\tcookiePath := \"/\"\n\tif anubis.BasePrefix != \"\" {\n\t\tcookiePath = strings.TrimSuffix(anubis.BasePrefix, \"/\") + \"/\"\n\t}\n\n\tif _, err := r.Cookie(anubis.TestCookieName); errors.Is(err, http.ErrNoCookie) {\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.ClearCookie(w, CookieOpts{Name: anubis.TestCookieName, Host: r.Host})\n\t\tlg.Warn(\"user has cookies disabled, this is not an anubis bug\")\n\t\ts.respondWithError(w, r, localizer.T(\"cookies_disabled\"))\n\t\treturn\n\t}\n\n\t// used by the path checker rule\n\tr.URL = redirURL\n\n\turlParsed, err := r.URL.Parse(redir)\n\tif err != nil {\n\t\ts.respondWithError(w, r, localizer.T(\"redirect_not_parseable\"))\n\t\treturn\n\t}\n\tif (len(urlParsed.Host) > 0 && len(s.opts.RedirectDomains) != 0 && !slices.Contains(s.opts.RedirectDomains, urlParsed.Host)) || urlParsed.Host != r.URL.Host {\n\t\ts.respondWithError(w, r, localizer.T(\"redirect_domain_not_allowed\"))\n\t\treturn\n\t}\n\n\tcr, rule, err := s.check(r)\n\tif err != nil {\n\t\tlg.Error(\"check failed\", \"err\", err)\n\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s \\\"passChallenge\\\"\", localizer.T(\"internal_server_error\")))\n\t\treturn\n\t}\n\tlg = lg.With(\"check_result\", cr)\n\n\timpl, ok := challenge.Get(rule.Challenge.Algorithm)\n\tif !ok {\n\t\tlg.Error(\"check failed\", \"err\", err)\n\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s: %s\", localizer.T(\"internal_server_error\"), rule.Challenge.Algorithm))\n\t\treturn\n\t}\n\n\tchall, err := s.challengeFor(r)\n\tif err != nil {\n\t\tlg.Error(\"check failed\", \"err\", err)\n\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s: %s\", localizer.T(\"internal_server_error\"), rule.Challenge.Algorithm))\n\t\treturn\n\t}\n\n\tin := &challenge.ValidateInput{\n\t\tChallenge: chall,\n\t\tRule: rule,\n\t\tStore: s.store,\n\t}\n\n\tif err := impl.Validate(r, lg, in); err != nil {\n\t\tfailedValidations.WithLabelValues(rule.Challenge.Algorithm).Inc()\n\t\tvar cerr *challenge.Error\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\tlg.Debug(\"challenge validate call failed\", \"err\", err)\n\n\t\tswitch {\n\t\tcase errors.As(err, &cerr):\n\t\t\tswitch {\n\t\t\tcase errors.Is(err, challenge.ErrFailed):\n\t\t\t\ts.respondWithStatus(w, r, cerr.PublicReason, cerr.StatusCode)\n\t\t\tcase errors.Is(err, challenge.ErrInvalidFormat), errors.Is(err, challenge.ErrMissingField):\n\t\t\t\ts.respondWithError(w, r, cerr.PublicReason)\n\t\t\t}\n\t\t}\n\t}\n\n\t// generate JWT cookie\n\ttokenString, err := s.signJWT(jwt.MapClaims{\n\t\t\"challenge\": chall.ID,\n\t\t\"method\": rule.Challenge.Algorithm,\n\t\t\"policyRule\": rule.Hash(),\n\t\t\"action\": string(cr.Rule),\n\t})\n\tif err != nil {\n\t\tlg.Error(\"failed to sign JWT\", \"err\", err)\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.respondWithError(w, r, localizer.T(\"failed_to_sign_jwt\"))\n\t\treturn\n\t}\n\n\ts.SetCookie(w, CookieOpts{Path: cookiePath, Host: r.Host, Value: tokenString})\n\n\tchallengesValidated.WithLabelValues(rule.Challenge.Algorithm).Inc()\n\tlg.Debug(\"challenge passed, redirecting to app\")\n\thttp.Redirect(w, r, redir, http.StatusFound)\n}\n\nfunc cr(name string, rule config.Rule, weight int) policy.CheckResult {\n\treturn policy.CheckResult{\n\t\tName: name,\n\t\tRule: rule,\n\t\tWeight: weight,\n\t}\n}\n\n// Check evaluates the list of rules, and returns the result\nfunc (s *Server) check(r *http.Request) (policy.CheckResult, *policy.Bot, error) {\n\thost := r.Header.Get(\"X-Real-Ip\")\n\tif host == \"\" {\n\t\treturn decaymap.Zilch[policy.CheckResult](), nil, fmt.Errorf(\"[misconfiguration] X-Real-Ip header is not set\")\n\t}\n\n\taddr := net.ParseIP(host)\n\tif addr == nil {\n\t\treturn decaymap.Zilch[policy.CheckResult](), nil, fmt.Errorf(\"[misconfiguration] %q is not an IP address\", host)\n\t}\n\n\tweight := 0\n\n\tfor _, b := range s.policy.Bots {\n\t\tmatch, err := b.Rules.Check(r)\n\t\tif err != nil {\n\t\t\treturn decaymap.Zilch[policy.CheckResult](), nil, fmt.Errorf(\"can't run check %s: %w\", b.Name, err)\n\t\t}\n\n\t\tif match {\n\t\t\tswitch b.Action {\n\t\t\tcase config.RuleDeny, config.RuleAllow, config.RuleBenchmark, config.RuleChallenge:\n\t\t\t\treturn cr(\"bot/\"+b.Name, b.Action, weight), &b, nil\n\t\t\tcase config.RuleWeigh:\n\t\t\t\tslog.Debug(\"adjusting weight\", \"name\", b.Name, \"delta\", b.Weight.Adjust)\n\t\t\t\tweight += b.Weight.Adjust\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, t := range s.policy.Thresholds {\n\t\tresult, _, err := t.Program.ContextEval(r.Context(), &policy.ThresholdRequest{Weight: weight})\n\t\tif err != nil {\n\t\t\tslog.Error(\"error when evaluating threshold expression\", \"expression\", t.Expression.String(), \"err\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tvar matches bool\n\n\t\tif val, ok := result.(types.Bool); ok {\n\t\t\tmatches = bool(val)\n\t\t}\n\n\t\tif matches {\n\t\t\treturn cr(\"threshold/\"+t.Name, t.Action, weight), &policy.Bot{\n\t\t\t\tChallenge: t.Challenge,\n\t\t\t\tRules: &checker.List{},\n\t\t\t}, nil\n\t\t}\n\t}\n\n\treturn cr(\"default/allow\", config.RuleAllow, weight), &policy.Bot{\n\t\tChallenge: &config.ChallengeRules{\n\t\t\tDifficulty: s.policy.DefaultDifficulty,\n\t\t\tReportAs: s.policy.DefaultDifficulty,\n\t\t\tAlgorithm: config.DefaultAlgorithm,\n\t\t},\n\t\tRules: &checker.List{},\n\t}, nil\n}\n"], ["/anubis/cmd/robots2policy/main.go", "package main\n\nimport (\n\t\"bufio\"\n\t\"encoding/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\n\t\"sigs.k8s.io/yaml\"\n)\n\nvar (\n\tinputFile = flag.String(\"input\", \"\", \"path to robots.txt file (use - for stdin)\")\n\toutputFile = flag.String(\"output\", \"\", \"output file path (use - for stdout, defaults to stdout)\")\n\toutputFormat = flag.String(\"format\", \"yaml\", \"output format: yaml or json\")\n\tbaseAction = flag.String(\"action\", \"CHALLENGE\", \"default action for disallowed paths: ALLOW, DENY, CHALLENGE, WEIGH\")\n\tcrawlDelay = flag.Int(\"crawl-delay-weight\", 0, \"if > 0, add weight adjustment for crawl-delay (difficulty adjustment)\")\n\tpolicyName = flag.String(\"name\", \"robots-txt-policy\", \"name for the generated policy\")\n\tuserAgentDeny = flag.String(\"deny-user-agents\", \"DENY\", \"action for specifically blocked user agents: DENY, CHALLENGE\")\n\thelpFlag = flag.Bool(\"help\", false, \"show help\")\n)\n\ntype RobotsRule struct {\n\tUserAgent string\n\tDisallows []string\n\tAllows []string\n\tCrawlDelay int\n\tIsBlacklist bool // true if this is a specifically denied user agent\n}\n\ntype AnubisRule struct {\n\tExpression *config.ExpressionOrList `yaml:\"expression,omitempty\" json:\"expression,omitempty\"`\n\tChallenge *config.ChallengeRules `yaml:\"challenge,omitempty\" json:\"challenge,omitempty\"`\n\tWeight *config.Weight `yaml:\"weight,omitempty\" json:\"weight,omitempty\"`\n\tName string `yaml:\"name\" json:\"name\"`\n\tAction string `yaml:\"action\" json:\"action\"`\n}\n\nfunc init() {\n\tflag.Usage = func() {\n\t\tfmt.Fprintf(os.Stderr, \"Usage of %s:\\n\", os.Args[0])\n\t\tfmt.Fprintf(os.Stderr, \"%s [options] -input \\n\\n\", os.Args[0])\n\t\tflag.PrintDefaults()\n\t\tfmt.Fprintln(os.Stderr, \"\\nExamples:\")\n\t\tfmt.Fprintln(os.Stderr, \" # Convert local robots.txt file\")\n\t\tfmt.Fprintln(os.Stderr, \" robots2policy -input robots.txt -output policy.yaml\")\n\t\tfmt.Fprintln(os.Stderr, \"\")\n\t\tfmt.Fprintln(os.Stderr, \" # Convert from URL\")\n\t\tfmt.Fprintln(os.Stderr, \" robots2policy -input https://example.com/robots.txt -format json\")\n\t\tfmt.Fprintln(os.Stderr, \"\")\n\t\tfmt.Fprintln(os.Stderr, \" # Read from stdin, write to stdout\")\n\t\tfmt.Fprintln(os.Stderr, \" curl https://example.com/robots.txt | robots2policy -input -\")\n\t\tos.Exit(2)\n\t}\n}\n\nfunc main() {\n\tflag.Parse()\n\n\tif len(flag.Args()) > 0 || *helpFlag || *inputFile == \"\" {\n\t\tflag.Usage()\n\t}\n\n\t// Read robots.txt\n\tvar input io.Reader\n\tif *inputFile == \"-\" {\n\t\tinput = os.Stdin\n\t} else if strings.HasPrefix(*inputFile, \"http://\") || strings.HasPrefix(*inputFile, \"https://\") {\n\t\tresp, err := http.Get(*inputFile)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to fetch robots.txt from URL: %v\", err)\n\t\t}\n\t\tdefer resp.Body.Close()\n\t\tinput = resp.Body\n\t} else {\n\t\tfile, err := os.Open(*inputFile)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to open input file: %v\", err)\n\t\t}\n\t\tdefer file.Close()\n\t\tinput = file\n\t}\n\n\t// Parse robots.txt\n\trules, err := parseRobotsTxt(input)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to parse robots.txt: %v\", err)\n\t}\n\n\t// Convert to Anubis rules\n\tanubisRules := convertToAnubisRules(rules)\n\n\t// Check if any rules were generated\n\tif len(anubisRules) == 0 {\n\t\tlog.Fatal(\"no valid rules generated from robots.txt - file may be empty or contain no disallow directives\")\n\t}\n\n\t// Generate output\n\tvar output []byte\n\tswitch strings.ToLower(*outputFormat) {\n\tcase \"yaml\":\n\t\toutput, err = yaml.Marshal(anubisRules)\n\tcase \"json\":\n\t\toutput, err = json.MarshalIndent(anubisRules, \"\", \" \")\n\tdefault:\n\t\tlog.Fatalf(\"unsupported output format: %s (use yaml or json)\", *outputFormat)\n\t}\n\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to marshal output: %v\", err)\n\t}\n\n\t// Write output\n\tif *outputFile == \"\" || *outputFile == \"-\" {\n\t\tfmt.Print(string(output))\n\t} else {\n\t\terr = os.WriteFile(*outputFile, output, 0644)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to write output file: %v\", err)\n\t\t}\n\t\tfmt.Printf(\"Generated Anubis policy written to %s\\n\", *outputFile)\n\t}\n}\n\nfunc parseRobotsTxt(input io.Reader) ([]RobotsRule, error) {\n\tscanner := bufio.NewScanner(input)\n\tvar rules []RobotsRule\n\tvar currentRule *RobotsRule\n\n\tfor scanner.Scan() {\n\t\tline := strings.TrimSpace(scanner.Text())\n\n\t\t// Skip empty lines and comments\n\t\tif line == \"\" || strings.HasPrefix(line, \"#\") {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Split on first colon\n\t\tparts := strings.SplitN(line, \":\", 2)\n\t\tif len(parts) != 2 {\n\t\t\tcontinue\n\t\t}\n\n\t\tdirective := strings.TrimSpace(strings.ToLower(parts[0]))\n\t\tvalue := strings.TrimSpace(parts[1])\n\n\t\tswitch directive {\n\t\tcase \"user-agent\":\n\t\t\t// Start a new rule section\n\t\t\tif currentRule != nil {\n\t\t\t\trules = append(rules, *currentRule)\n\t\t\t}\n\t\t\tcurrentRule = &RobotsRule{\n\t\t\t\tUserAgent: value,\n\t\t\t\tDisallows: make([]string, 0),\n\t\t\t\tAllows: make([]string, 0),\n\t\t\t}\n\n\t\tcase \"disallow\":\n\t\t\tif currentRule != nil && value != \"\" {\n\t\t\t\tcurrentRule.Disallows = append(currentRule.Disallows, value)\n\t\t\t}\n\n\t\tcase \"allow\":\n\t\t\tif currentRule != nil && value != \"\" {\n\t\t\t\tcurrentRule.Allows = append(currentRule.Allows, value)\n\t\t\t}\n\n\t\tcase \"crawl-delay\":\n\t\t\tif currentRule != nil {\n\t\t\t\tif delay, err := parseIntSafe(value); err == nil {\n\t\t\t\t\tcurrentRule.CrawlDelay = delay\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Don't forget the last rule\n\tif currentRule != nil {\n\t\trules = append(rules, *currentRule)\n\t}\n\n\t// Mark blacklisted user agents (those with \"Disallow: /\")\n\tfor i := range rules {\n\t\tfor _, disallow := range rules[i].Disallows {\n\t\t\tif disallow == \"/\" {\n\t\t\t\trules[i].IsBlacklist = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn rules, scanner.Err()\n}\n\nfunc parseIntSafe(s string) (int, error) {\n\tvar result int\n\t_, err := fmt.Sscanf(s, \"%d\", &result)\n\treturn result, err\n}\n\nfunc convertToAnubisRules(robotsRules []RobotsRule) []AnubisRule {\n\tvar anubisRules []AnubisRule\n\truleCounter := 0\n\n\tfor _, robotsRule := range robotsRules {\n\t\tuserAgent := robotsRule.UserAgent\n\n\t\t// Handle crawl delay as weight adjustment (do this first before any continues)\n\t\tif robotsRule.CrawlDelay > 0 && *crawlDelay > 0 {\n\t\t\truleCounter++\n\t\t\trule := AnubisRule{\n\t\t\t\tName: fmt.Sprintf(\"%s-crawl-delay-%d\", *policyName, ruleCounter),\n\t\t\t\tAction: \"WEIGH\",\n\t\t\t\tWeight: &config.Weight{Adjust: *crawlDelay},\n\t\t\t}\n\n\t\t\tif userAgent == \"*\" {\n\t\t\t\trule.Expression = &config.ExpressionOrList{\n\t\t\t\t\tAll: []string{\"true\"}, // Always applies\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\trule.Expression = &config.ExpressionOrList{\n\t\t\t\t\tAll: []string{fmt.Sprintf(\"userAgent.contains(%q)\", userAgent)},\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tanubisRules = append(anubisRules, rule)\n\t\t}\n\n\t\t// Handle blacklisted user agents (complete deny/challenge)\n\t\tif robotsRule.IsBlacklist {\n\t\t\truleCounter++\n\t\t\trule := AnubisRule{\n\t\t\t\tName: fmt.Sprintf(\"%s-blacklist-%d\", *policyName, ruleCounter),\n\t\t\t\tAction: *userAgentDeny,\n\t\t\t}\n\n\t\t\tif userAgent == \"*\" {\n\t\t\t\t// This would block everything - convert to a weight adjustment instead\n\t\t\t\trule.Name = fmt.Sprintf(\"%s-global-restriction-%d\", *policyName, ruleCounter)\n\t\t\t\trule.Action = \"WEIGH\"\n\t\t\t\trule.Weight = &config.Weight{Adjust: 20} // Increase difficulty significantly\n\t\t\t\trule.Expression = &config.ExpressionOrList{\n\t\t\t\t\tAll: []string{\"true\"}, // Always applies\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\trule.Expression = &config.ExpressionOrList{\n\t\t\t\t\tAll: []string{fmt.Sprintf(\"userAgent.contains(%q)\", userAgent)},\n\t\t\t\t}\n\t\t\t}\n\t\t\tanubisRules = append(anubisRules, rule)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Handle specific disallow rules\n\t\tfor _, disallow := range robotsRule.Disallows {\n\t\t\tif disallow == \"/\" {\n\t\t\t\tcontinue // Already handled as blacklist above\n\t\t\t}\n\n\t\t\truleCounter++\n\t\t\trule := AnubisRule{\n\t\t\t\tName: fmt.Sprintf(\"%s-disallow-%d\", *policyName, ruleCounter),\n\t\t\t\tAction: *baseAction,\n\t\t\t}\n\n\t\t\t// Build CEL expression\n\t\t\tvar conditions []string\n\n\t\t\t// Add user agent condition if not wildcard\n\t\t\tif userAgent != \"*\" {\n\t\t\t\tconditions = append(conditions, fmt.Sprintf(\"userAgent.contains(%q)\", userAgent))\n\t\t\t}\n\n\t\t\t// Add path condition\n\t\t\tpathCondition := buildPathCondition(disallow)\n\t\t\tconditions = append(conditions, pathCondition)\n\n\t\t\trule.Expression = &config.ExpressionOrList{\n\t\t\t\tAll: conditions,\n\t\t\t}\n\n\t\t\tanubisRules = append(anubisRules, rule)\n\t\t}\n\n\t}\n\n\treturn anubisRules\n}\n\nfunc buildPathCondition(robotsPath string) string {\n\t// Handle wildcards in robots.txt paths\n\tif strings.Contains(robotsPath, \"*\") || strings.Contains(robotsPath, \"?\") {\n\t\t// Convert robots.txt wildcards to regex\n\t\tregex := regexp.QuoteMeta(robotsPath)\n\t\tregex = strings.ReplaceAll(regex, `\\*`, `.*`) // * becomes .*\n\t\tregex = strings.ReplaceAll(regex, `\\?`, `.`) // ? becomes .\n\t\tregex = \"^\" + regex\n\t\treturn fmt.Sprintf(\"path.matches(%q)\", regex)\n\t}\n\n\t// Simple prefix match for most cases\n\treturn fmt.Sprintf(\"path.startsWith(%q)\", robotsPath)\n}\n"], ["/anubis/lib/http.go", "package lib\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"net/http\"\n\t\"regexp\"\n\t\"slices\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/TecharoHQ/anubis/internal\"\n\t\"github.com/TecharoHQ/anubis/lib/challenge\"\n\t\"github.com/TecharoHQ/anubis/lib/localization\"\n\t\"github.com/TecharoHQ/anubis/lib/policy\"\n\t\"github.com/TecharoHQ/anubis/web\"\n\t\"github.com/a-h/templ\"\n\t\"github.com/golang-jwt/jwt/v5\"\n\t\"golang.org/x/net/publicsuffix\"\n)\n\nvar domainMatchRegexp = regexp.MustCompile(`^((xn--)?[a-z0-9]+(-[a-z0-9]+)*\\.)+[a-z]{2,}$`)\n\ntype CookieOpts struct {\n\tValue string\n\tHost string\n\tPath string\n\tName string\n\tExpiry time.Duration\n}\n\nfunc (s *Server) SetCookie(w http.ResponseWriter, cookieOpts CookieOpts) {\n\tvar domain = s.opts.CookieDomain\n\tvar name = anubis.CookieName\n\tvar path = \"/\"\n\tif cookieOpts.Name != \"\" {\n\t\tname = cookieOpts.Name\n\t}\n\tif cookieOpts.Path != \"\" {\n\t\tpath = cookieOpts.Path\n\t}\n\tif s.opts.CookieDynamicDomain && domainMatchRegexp.MatchString(cookieOpts.Host) {\n\t\tif etld, err := publicsuffix.EffectiveTLDPlusOne(cookieOpts.Host); err == nil {\n\t\t\tdomain = etld\n\t\t}\n\t}\n\n\tif cookieOpts.Expiry == 0 {\n\t\tcookieOpts.Expiry = s.opts.CookieExpiration\n\t}\n\n\thttp.SetCookie(w, &http.Cookie{\n\t\tName: name,\n\t\tValue: cookieOpts.Value,\n\t\tExpires: time.Now().Add(cookieOpts.Expiry),\n\t\tSameSite: http.SameSiteNoneMode,\n\t\tDomain: domain,\n\t\tSecure: s.opts.CookieSecure,\n\t\tPartitioned: s.opts.CookiePartitioned,\n\t\tPath: path,\n\t})\n}\n\nfunc (s *Server) ClearCookie(w http.ResponseWriter, cookieOpts CookieOpts) {\n\tvar domain = s.opts.CookieDomain\n\tvar name = anubis.CookieName\n\tvar path = \"/\"\n\tif cookieOpts.Name != \"\" {\n\t\tname = cookieOpts.Name\n\t}\n\tif cookieOpts.Path != \"\" {\n\t\tpath = cookieOpts.Path\n\t}\n\tif s.opts.CookieDynamicDomain && domainMatchRegexp.MatchString(cookieOpts.Host) {\n\t\tif etld, err := publicsuffix.EffectiveTLDPlusOne(cookieOpts.Host); err == nil {\n\t\t\tdomain = etld\n\t\t}\n\t}\n\n\thttp.SetCookie(w, &http.Cookie{\n\t\tName: name,\n\t\tValue: \"\",\n\t\tMaxAge: -1,\n\t\tExpires: time.Now().Add(-1 * time.Minute),\n\t\tSameSite: http.SameSiteNoneMode,\n\t\tPartitioned: s.opts.CookiePartitioned,\n\t\tDomain: domain,\n\t\tSecure: s.opts.CookieSecure,\n\t\tPath: path,\n\t})\n}\n\n// https://github.com/oauth2-proxy/oauth2-proxy/blob/master/pkg/upstream/http.go#L124\ntype UnixRoundTripper struct {\n\tTransport *http.Transport\n}\n\n// set bare minimum stuff\nfunc (t UnixRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {\n\treq = req.Clone(req.Context())\n\tif req.Host == \"\" {\n\t\treq.Host = \"localhost\"\n\t}\n\treq.URL.Host = req.Host // proxy error: no Host in request URL\n\treq.URL.Scheme = \"http\" // make http.Transport happy and avoid an infinite recursion\n\treturn t.Transport.RoundTrip(req)\n}\n\nfunc randomChance(n int) bool {\n\treturn rand.Intn(n) == 0\n}\n\nfunc (s *Server) RenderIndex(w http.ResponseWriter, r *http.Request, rule *policy.Bot, returnHTTPStatusOnly bool) {\n\tlocalizer := localization.GetLocalizer(r)\n\n\tif returnHTTPStatusOnly {\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\tw.Write([]byte(localizer.T(\"authorization_required\")))\n\t\treturn\n\t}\n\n\tlg := internal.GetRequestLogger(r)\n\n\tif !strings.Contains(r.Header.Get(\"Accept-Encoding\"), \"gzip\") && randomChance(64) {\n\t\tlg.Error(\"client was given a challenge but does not in fact support gzip compression\")\n\t\ts.respondWithError(w, r, localizer.T(\"client_error_browser\"))\n\t}\n\n\tchallengesIssued.WithLabelValues(\"embedded\").Add(1)\n\tchall, err := s.challengeFor(r)\n\tif err != nil {\n\t\tlg.Error(\"can't get challenge\", \"err\", \"err\")\n\t\ts.ClearCookie(w, CookieOpts{Name: anubis.TestCookieName, Host: r.Host})\n\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s: %s\", localizer.T(\"internal_server_error\"), rule.Challenge.Algorithm))\n\t\treturn\n\t}\n\n\tvar ogTags map[string]string = nil\n\tif s.opts.OpenGraph.Enabled {\n\t\tvar err error\n\t\togTags, err = s.OGTags.GetOGTags(r.Context(), r.URL, r.Host)\n\t\tif err != nil {\n\t\t\tlg.Error(\"failed to get OG tags\", \"err\", err)\n\t\t}\n\t}\n\n\ts.SetCookie(w, CookieOpts{\n\t\tValue: chall.ID,\n\t\tHost: r.Host,\n\t\tPath: \"/\",\n\t\tName: anubis.TestCookieName,\n\t\tExpiry: 30 * time.Minute,\n\t})\n\n\timpl, ok := challenge.Get(rule.Challenge.Algorithm)\n\tif !ok {\n\t\tlg.Error(\"check failed\", \"err\", \"can't get algorithm\", \"algorithm\", rule.Challenge.Algorithm)\n\t\ts.ClearCookie(w, CookieOpts{Name: anubis.TestCookieName, Host: r.Host})\n\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s: %s\", localizer.T(\"internal_server_error\"), rule.Challenge.Algorithm))\n\t\treturn\n\t}\n\n\tin := &challenge.IssueInput{\n\t\tImpressum: s.policy.Impressum,\n\t\tRule: rule,\n\t\tChallenge: chall,\n\t\tOGTags: ogTags,\n\t\tStore: s.store,\n\t}\n\n\tcomponent, err := impl.Issue(r, lg, in)\n\tif err != nil {\n\t\tlg.Error(\"[unexpected] render failed, please open an issue\", \"err\", err) // This is likely a bug in the template. Should never be triggered as CI tests for this.\n\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s \\\"RenderIndex\\\"\", localizer.T(\"internal_server_error\")))\n\t\treturn\n\t}\n\n\thandler := internal.GzipMiddleware(1, internal.NoStoreCache(templ.Handler(\n\t\tcomponent,\n\t\ttempl.WithStatus(s.opts.Policy.StatusCodes.Challenge),\n\t)))\n\thandler.ServeHTTP(w, r)\n}\n\nfunc (s *Server) RenderBench(w http.ResponseWriter, r *http.Request) {\n\tlocalizer := localization.GetLocalizer(r)\n\n\ttempl.Handler(\n\t\tweb.Base(localizer.T(\"benchmarking_anubis\"), web.Bench(localizer), s.policy.Impressum, localizer),\n\t).ServeHTTP(w, r)\n}\n\nfunc (s *Server) respondWithError(w http.ResponseWriter, r *http.Request, message string) {\n\ts.respondWithStatus(w, r, message, http.StatusInternalServerError)\n}\n\nfunc (s *Server) respondWithStatus(w http.ResponseWriter, r *http.Request, msg string, status int) {\n\tlocalizer := localization.GetLocalizer(r)\n\n\ttempl.Handler(web.Base(localizer.T(\"oh_noes\"), web.ErrorPage(msg, s.opts.WebmasterEmail, localizer), s.policy.Impressum, localizer), templ.WithStatus(status)).ServeHTTP(w, r)\n}\n\nfunc (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\ts.mux.ServeHTTP(w, r)\n}\n\nfunc (s *Server) stripBasePrefixFromRequest(r *http.Request) *http.Request {\n\tif !s.opts.StripBasePrefix || s.opts.BasePrefix == \"\" {\n\t\treturn r\n\t}\n\n\tbasePrefix := strings.TrimSuffix(s.opts.BasePrefix, \"/\")\n\tpath := r.URL.Path\n\n\tif !strings.HasPrefix(path, basePrefix) {\n\t\treturn r\n\t}\n\n\ttrimmedPath := strings.TrimPrefix(path, basePrefix)\n\tif trimmedPath == \"\" {\n\t\ttrimmedPath = \"/\"\n\t}\n\n\t// Clone the request and URL\n\treqCopy := r.Clone(r.Context())\n\turlCopy := *r.URL\n\turlCopy.Path = trimmedPath\n\treqCopy.URL = &urlCopy\n\n\treturn reqCopy\n}\n\nfunc (s *Server) ServeHTTPNext(w http.ResponseWriter, r *http.Request) {\n\tif s.next == nil {\n\t\tlocalizer := localization.GetLocalizer(r)\n\n\t\tredir := r.FormValue(\"redir\")\n\t\turlParsed, err := r.URL.Parse(redir)\n\t\tif err != nil {\n\t\t\ts.respondWithStatus(w, r, localizer.T(\"redirect_not_parseable\"), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tif (len(urlParsed.Host) > 0 && len(s.opts.RedirectDomains) != 0 && !slices.Contains(s.opts.RedirectDomains, urlParsed.Host)) || urlParsed.Host != r.URL.Host {\n\t\t\ts.respondWithStatus(w, r, localizer.T(\"redirect_domain_not_allowed\"), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tif redir != \"\" {\n\t\t\thttp.Redirect(w, r, redir, http.StatusFound)\n\t\t\treturn\n\t\t}\n\n\t\ttempl.Handler(\n\t\t\tweb.Base(localizer.T(\"you_are_not_a_bot\"), web.StaticHappy(localizer), s.policy.Impressum, localizer),\n\t\t).ServeHTTP(w, r)\n\t} else {\n\t\trequestsProxied.WithLabelValues(r.Host).Inc()\n\t\tr = s.stripBasePrefixFromRequest(r)\n\t\ts.next.ServeHTTP(w, r)\n\t}\n}\n\nfunc (s *Server) signJWT(claims jwt.MapClaims) (string, error) {\n\tclaims[\"iat\"] = time.Now().Unix()\n\tclaims[\"nbf\"] = time.Now().Add(-1 * time.Minute).Unix()\n\tclaims[\"exp\"] = time.Now().Add(s.opts.CookieExpiration).Unix()\n\n\tif len(s.hs512Secret) == 0 {\n\t\treturn jwt.NewWithClaims(jwt.SigningMethodEdDSA, claims).SignedString(s.ed25519Priv)\n\t} else {\n\t\treturn jwt.NewWithClaims(jwt.SigningMethodHS512, claims).SignedString(s.hs512Secret)\n\t}\n}\n"], ["/anubis/internal/ogtags/ogtags.go", "package ogtags\n\nimport (\n\t\"context\"\n\t\"log/slog\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n)\n\nconst (\n\tmaxContentLength = 8 << 20 // 8 MiB is enough for anyone\n\thttpTimeout = 5 * time.Second /*todo: make this configurable?*/\n\n\tschemeSeparatorLength = 3 // Length of \"://\"\n\tquerySeparatorLength = 1 // Length of \"?\" for query strings\n)\n\ntype OGTagCache struct {\n\tcache store.JSON[map[string]string]\n\ttargetURL *url.URL\n\tclient *http.Client\n\n\t// Pre-built strings for optimization\n\tunixPrefix string // \"http://unix\"\n\tapprovedTags []string\n\tapprovedPrefixes []string\n\togTimeToLive time.Duration\n\togCacheConsiderHost bool\n\togPassthrough bool\n\togOverride map[string]string\n}\n\nfunc NewOGTagCache(target string, conf config.OpenGraph, backend store.Interface) *OGTagCache {\n\t// Predefined approved tags and prefixes\n\tdefaultApprovedTags := []string{\"description\", \"keywords\", \"author\"}\n\tdefaultApprovedPrefixes := []string{\"og:\", \"twitter:\", \"fediverse:\"}\n\n\tvar parsedTargetURL *url.URL\n\tvar err error\n\n\tif target == \"\" {\n\t\t// Default to localhost if target is empty\n\t\tparsedTargetURL, _ = url.Parse(\"http://localhost\")\n\t} else {\n\t\tparsedTargetURL, err = url.Parse(target)\n\t\tif err != nil {\n\t\t\tslog.Debug(\"og: failed to parse target URL, treating as non-unix\", \"target\", target, \"error\", err)\n\t\t\t// If parsing fails, treat it as a non-unix target for backward compatibility or default behavior\n\t\t\t// For now, assume it's not a scheme issue but maybe an invalid char, etc.\n\t\t\t// A simple string target might be intended if it's not a full URL.\n\t\t\tparsedTargetURL = &url.URL{Scheme: \"http\", Host: target} // Assume http if scheme missing and host-like\n\t\t\tif !strings.Contains(target, \"://\") && !strings.HasPrefix(target, \"unix:\") {\n\t\t\t\t// If it looks like just a host/host:port (and not unix), prepend http:// (todo: is this bad...? Trace path to see if i can yell at user to do it right)\n\t\t\t\tparsedTargetURL, _ = url.Parse(\"http://\" + target) // fetch cares about scheme but anubis doesn't\n\t\t\t}\n\t\t}\n\t}\n\n\tclient := &http.Client{\n\t\tTimeout: httpTimeout,\n\t}\n\n\t// Configure custom transport for Unix sockets\n\tif parsedTargetURL.Scheme == \"unix\" {\n\t\tsocketPath := parsedTargetURL.Path // For unix scheme, path is the socket path\n\t\tclient.Transport = &http.Transport{\n\t\t\tDialContext: func(_ context.Context, _, _ string) (net.Conn, error) {\n\t\t\t\treturn net.Dial(\"unix\", socketPath)\n\t\t\t},\n\t\t}\n\t}\n\n\treturn &OGTagCache{\n\t\tcache: store.JSON[map[string]string]{\n\t\t\tUnderlying: backend,\n\t\t\tPrefix: \"ogtags:\",\n\t\t},\n\t\ttargetURL: parsedTargetURL,\n\t\togPassthrough: conf.Enabled,\n\t\togTimeToLive: conf.TimeToLive,\n\t\togCacheConsiderHost: conf.ConsiderHost,\n\t\togOverride: conf.Override,\n\t\tapprovedTags: defaultApprovedTags,\n\t\tapprovedPrefixes: defaultApprovedPrefixes,\n\t\tclient: client,\n\t\tunixPrefix: \"http://unix\",\n\t}\n}\n\n// getTarget constructs the target URL string for fetching OG tags.\n// Optimized to minimize allocations by building strings directly.\nfunc (c *OGTagCache) getTarget(u *url.URL) string {\n\tvar escapedPath = u.EscapedPath() // will cause an allocation if path contains special characters\n\tif c.targetURL.Scheme == \"unix\" {\n\t\t// Build URL string directly without creating intermediate URL object\n\t\tvar sb strings.Builder\n\t\tsb.Grow(len(c.unixPrefix) + len(escapedPath) + len(u.RawQuery) + querySeparatorLength) // Pre-allocate\n\t\tsb.WriteString(c.unixPrefix)\n\t\tsb.WriteString(escapedPath)\n\t\tif u.RawQuery != \"\" {\n\t\t\tsb.WriteByte('?')\n\t\t\tsb.WriteString(u.RawQuery)\n\t\t}\n\t\treturn sb.String()\n\t}\n\n\t// For regular http/https targets, build URL string directly\n\tvar sb strings.Builder\n\t// Pre-calculate size: scheme + \"://\" + host + path + \"?\" + query\n\testimatedSize := len(c.targetURL.Scheme) + schemeSeparatorLength + len(c.targetURL.Host) + len(escapedPath) + len(u.RawQuery) + querySeparatorLength\n\tsb.Grow(estimatedSize)\n\n\tsb.WriteString(c.targetURL.Scheme)\n\tsb.WriteString(\"://\")\n\tsb.WriteString(c.targetURL.Host)\n\tsb.WriteString(escapedPath)\n\tif u.RawQuery != \"\" {\n\t\tsb.WriteByte('?')\n\t\tsb.WriteString(u.RawQuery)\n\t}\n\n\treturn sb.String()\n}\n"], ["/anubis/internal/headers.go", "package internal\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/netip\"\n\t\"strings\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/sebest/xff\"\n)\n\n// TODO: move into config\ntype XFFComputePreferences struct {\n\tStripPrivate bool\n\tStripLoopback bool\n\tStripCGNAT bool\n\tStripLLU bool\n\tFlatten bool\n}\n\nvar CGNat = netip.MustParsePrefix(\"100.64.0.0/10\")\n\n// UnchangingCache sets the Cache-Control header to cache a response for 1 year if\n// and only if the application is compiled in \"release\" mode by Docker.\nfunc UnchangingCache(next http.Handler) http.Handler {\n\t//goland:noinspection GoBoolExpressions\n\tif anubis.Version == \"devel\" {\n\t\treturn next\n\t}\n\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Cache-Control\", \"public, max-age=31536000\")\n\t\tnext.ServeHTTP(w, r)\n\t})\n}\n\n// RemoteXRealIP sets the X-Real-Ip header to the request's real IP if\n// the setting is enabled by the user.\nfunc RemoteXRealIP(useRemoteAddress bool, bindNetwork string, next http.Handler) http.Handler {\n\tif !useRemoteAddress {\n\t\tslog.Debug(\"skipping middleware, useRemoteAddress is empty\")\n\t\treturn next\n\t}\n\n\tif bindNetwork == \"unix\" {\n\t\t// For local sockets there is no real remote address but the localhost\n\t\t// address should be sensible.\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tr.Header.Set(\"X-Real-Ip\", \"127.0.0.1\")\n\t\t\tnext.ServeHTTP(w, r)\n\t\t})\n\t}\n\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\thost, _, err := net.SplitHostPort(r.RemoteAddr)\n\t\tif err != nil {\n\t\t\tpanic(err) // this should never happen\n\t\t}\n\t\tr.Header.Set(\"X-Real-Ip\", host)\n\t\tnext.ServeHTTP(w, r)\n\t})\n}\n\n// XForwardedForToXRealIP sets the X-Real-Ip header based on the contents\n// of the X-Forwarded-For header.\nfunc XForwardedForToXRealIP(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif xffHeader := r.Header.Get(\"X-Forwarded-For\"); r.Header.Get(\"X-Real-Ip\") == \"\" && xffHeader != \"\" {\n\t\t\tip := xff.Parse(xffHeader)\n\t\t\tslog.Debug(\"setting x-real-ip\", \"val\", ip)\n\t\t\tr.Header.Set(\"X-Real-Ip\", ip)\n\t\t}\n\n\t\tnext.ServeHTTP(w, r)\n\t})\n}\n\n// XForwardedForUpdate sets or updates the X-Forwarded-For header, adding\n// the known remote address to an existing chain if present\nfunc XForwardedForUpdate(stripPrivate bool, next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tdefer next.ServeHTTP(w, r)\n\n\t\tpref := XFFComputePreferences{\n\t\t\tStripPrivate: stripPrivate,\n\t\t\tStripLoopback: true,\n\t\t\tStripCGNAT: true,\n\t\t\tFlatten: true,\n\t\t\tStripLLU: true,\n\t\t}\n\n\t\tremoteAddr := r.RemoteAddr\n\t\torigXFFHeader := r.Header.Get(\"X-Forwarded-For\")\n\n\t\tif remoteAddr == \"@\" {\n\t\t\t// remote is a unix socket\n\t\t\t// do not touch chain\n\t\t\treturn\n\t\t}\n\n\t\txffHeaderString, err := computeXFFHeader(remoteAddr, origXFFHeader, pref)\n\t\tif err != nil {\n\t\t\tslog.Debug(\"computing X-Forwarded-For header failed\", \"err\", err)\n\t\t\treturn\n\t\t}\n\n\t\tif len(xffHeaderString) == 0 {\n\t\t\tr.Header.Del(\"X-Forwarded-For\")\n\t\t} else {\n\t\t\tr.Header.Set(\"X-Forwarded-For\", xffHeaderString)\n\t\t}\n\t})\n}\n\nvar (\n\tErrCantSplitHostParse = errors.New(\"internal: unable to net.SplitHostParse\")\n\tErrCantParseRemoteIP = errors.New(\"internal: unable to parse remote IP\")\n)\n\nfunc computeXFFHeader(remoteAddr string, origXFFHeader string, pref XFFComputePreferences) (string, error) {\n\tremoteIP, _, err := net.SplitHostPort(remoteAddr)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"%w: %w\", ErrCantSplitHostParse, err)\n\t}\n\tparsedRemoteIP, err := netip.ParseAddr(remoteIP)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"%w: %w\", ErrCantParseRemoteIP, err)\n\t}\n\n\torigForwardedList := make([]string, 0, 4)\n\tif origXFFHeader != \"\" {\n\t\torigForwardedList = strings.Split(origXFFHeader, \",\")\n\t\tfor i := range origForwardedList {\n\t\t\torigForwardedList[i] = strings.TrimSpace(origForwardedList[i])\n\t\t}\n\t}\n\torigForwardedList = append(origForwardedList, parsedRemoteIP.String())\n\tforwardedList := make([]string, 0, len(origForwardedList))\n\t// this behavior is equivalent to\n\t// ingress-nginx \"compute-full-forwarded-for\"\n\t// https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/configmap/#compute-full-forwarded-for\n\t//\n\t// this would be the correct place to strip and/or flatten this list\n\t//\n\t// strip - iterate backwards and eliminate configured trusted IPs\n\t// flatten - only return the last element to avoid spoofing confusion\n\t//\n\t// many applications handle this in different ways, but\n\t// generally they'd be expected to do these two things on\n\t// their own end to find the first non-spoofed IP\n\tfor i := len(origForwardedList) - 1; i >= 0; i-- {\n\t\tsegmentIP, err := netip.ParseAddr(origForwardedList[i])\n\t\tif err != nil {\n\t\t\t// can't assess this element, so the remainder of the chain\n\t\t\t// can't be trusted. not a fatal error, since anyone can\n\t\t\t// spoof an XFF header\n\t\t\tslog.Debug(\"failed to parse XFF segment\", \"err\", err)\n\t\t\tbreak\n\t\t}\n\t\tif pref.StripPrivate && segmentIP.IsPrivate() {\n\t\t\tcontinue\n\t\t}\n\t\tif pref.StripLoopback && segmentIP.IsLoopback() {\n\t\t\tcontinue\n\t\t}\n\t\tif pref.StripLLU && segmentIP.IsLinkLocalUnicast() {\n\t\t\tcontinue\n\t\t}\n\t\tif pref.StripCGNAT && CGNat.Contains(segmentIP) {\n\t\t\tcontinue\n\t\t}\n\t\tforwardedList = append([]string{segmentIP.String()}, forwardedList...)\n\t}\n\tvar xffHeaderString string\n\tif len(forwardedList) == 0 {\n\t\txffHeaderString = \"\"\n\t\treturn xffHeaderString, nil\n\t}\n\tif pref.Flatten {\n\t\txffHeaderString = forwardedList[len(forwardedList)-1]\n\t} else {\n\t\txffHeaderString = strings.Join(forwardedList, \",\")\n\t}\n\treturn xffHeaderString, nil\n}\n\n// NoStoreCache sets the Cache-Control header to no-store for the response.\nfunc NoStoreCache(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Cache-Control\", \"no-store\")\n\t\tnext.ServeHTTP(w, r)\n\t})\n}\n\n// NoBrowsing prevents directory browsing by returning a 404 for any request that ends with a \"/\".\nfunc NoBrowsing(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif strings.HasSuffix(r.URL.Path, \"/\") {\n\t\t\thttp.NotFound(w, r)\n\t\t\treturn\n\t\t}\n\t\tnext.ServeHTTP(w, r)\n\t})\n}\n"], ["/anubis/lib/policy/policy.go", "package policy\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log/slog\"\n\t\"sync/atomic\"\n\n\t\"github.com/TecharoHQ/anubis/lib/policy/checker\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n\t\"github.com/TecharoHQ/anubis/lib/thoth\"\n\t\"github.com/prometheus/client_golang/prometheus\"\n\t\"github.com/prometheus/client_golang/prometheus/promauto\"\n\n\t_ \"github.com/TecharoHQ/anubis/lib/store/all\"\n)\n\nvar (\n\tApplications = promauto.NewCounterVec(prometheus.CounterOpts{\n\t\tName: \"anubis_policy_results\",\n\t\tHelp: \"The results of each policy rule\",\n\t}, []string{\"rule\", \"action\"})\n\n\tErrChallengeRuleHasWrongAlgorithm = errors.New(\"config.Bot.ChallengeRules: algorithm is invalid\")\n\twarnedAboutThresholds = &atomic.Bool{}\n)\n\ntype ParsedConfig struct {\n\torig *config.Config\n\n\tBots []Bot\n\tThresholds []*Threshold\n\tDNSBL bool\n\tImpressum *config.Impressum\n\tOpenGraph config.OpenGraph\n\tDefaultDifficulty int\n\tStatusCodes config.StatusCodes\n\tStore store.Interface\n}\n\nfunc newParsedConfig(orig *config.Config) *ParsedConfig {\n\treturn &ParsedConfig{\n\t\torig: orig,\n\t\tOpenGraph: orig.OpenGraph,\n\t\tStatusCodes: orig.StatusCodes,\n\t}\n}\n\nfunc ParseConfig(ctx context.Context, fin io.Reader, fname string, defaultDifficulty int) (*ParsedConfig, error) {\n\tc, err := config.Load(fin, fname)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar validationErrs []error\n\n\ttc, hasThothClient := thoth.FromContext(ctx)\n\n\tresult := newParsedConfig(c)\n\tresult.DefaultDifficulty = defaultDifficulty\n\n\tfor _, b := range c.Bots {\n\t\tif berr := b.Valid(); berr != nil {\n\t\t\tvalidationErrs = append(validationErrs, berr)\n\t\t\tcontinue\n\t\t}\n\n\t\tparsedBot := Bot{\n\t\t\tName: b.Name,\n\t\t\tAction: b.Action,\n\t\t}\n\n\t\tcl := checker.List{}\n\n\t\tif len(b.RemoteAddr) > 0 {\n\t\t\tc, err := NewRemoteAddrChecker(b.RemoteAddr)\n\t\t\tif err != nil {\n\t\t\t\tvalidationErrs = append(validationErrs, fmt.Errorf(\"while processing rule %s remote addr set: %w\", b.Name, err))\n\t\t\t} else {\n\t\t\t\tcl = append(cl, c)\n\t\t\t}\n\t\t}\n\n\t\tif b.UserAgentRegex != nil {\n\t\t\tc, err := NewUserAgentChecker(*b.UserAgentRegex)\n\t\t\tif err != nil {\n\t\t\t\tvalidationErrs = append(validationErrs, fmt.Errorf(\"while processing rule %s user agent regex: %w\", b.Name, err))\n\t\t\t} else {\n\t\t\t\tcl = append(cl, c)\n\t\t\t}\n\t\t}\n\n\t\tif b.PathRegex != nil {\n\t\t\tc, err := NewPathChecker(*b.PathRegex)\n\t\t\tif err != nil {\n\t\t\t\tvalidationErrs = append(validationErrs, fmt.Errorf(\"while processing rule %s path regex: %w\", b.Name, err))\n\t\t\t} else {\n\t\t\t\tcl = append(cl, c)\n\t\t\t}\n\t\t}\n\n\t\tif len(b.HeadersRegex) > 0 {\n\t\t\tc, err := NewHeadersChecker(b.HeadersRegex)\n\t\t\tif err != nil {\n\t\t\t\tvalidationErrs = append(validationErrs, fmt.Errorf(\"while processing rule %s headers regex map: %w\", b.Name, err))\n\t\t\t} else {\n\t\t\t\tcl = append(cl, c)\n\t\t\t}\n\t\t}\n\n\t\tif b.Expression != nil {\n\t\t\tc, err := NewCELChecker(b.Expression)\n\t\t\tif err != nil {\n\t\t\t\tvalidationErrs = append(validationErrs, fmt.Errorf(\"while processing rule %s expressions: %w\", b.Name, err))\n\t\t\t} else {\n\t\t\t\tcl = append(cl, c)\n\t\t\t}\n\t\t}\n\n\t\tif b.ASNs != nil {\n\t\t\tif !hasThothClient {\n\t\t\t\tslog.Warn(\"You have specified a Thoth specific check but you have no Thoth client configured. Please read https://anubis.techaro.lol/docs/admin/thoth for more information\", \"check\", \"asn\", \"settings\", b.ASNs)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tcl = append(cl, tc.ASNCheckerFor(b.ASNs.Match))\n\t\t}\n\n\t\tif b.GeoIP != nil {\n\t\t\tif !hasThothClient {\n\t\t\t\tslog.Warn(\"You have specified a Thoth specific check but you have no Thoth client configured. Please read https://anubis.techaro.lol/docs/admin/thoth for more information\", \"check\", \"geoip\", \"settings\", b.GeoIP)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tcl = append(cl, tc.GeoIPCheckerFor(b.GeoIP.Countries))\n\t\t}\n\n\t\tif b.Challenge == nil {\n\t\t\tparsedBot.Challenge = &config.ChallengeRules{\n\t\t\t\tDifficulty: defaultDifficulty,\n\t\t\t\tReportAs: defaultDifficulty,\n\t\t\t\tAlgorithm: \"fast\",\n\t\t\t}\n\t\t} else {\n\t\t\tparsedBot.Challenge = b.Challenge\n\t\t\tif parsedBot.Challenge.Algorithm == \"\" {\n\t\t\t\tparsedBot.Challenge.Algorithm = config.DefaultAlgorithm\n\t\t\t}\n\t\t}\n\n\t\tif b.Weight != nil {\n\t\t\tparsedBot.Weight = b.Weight\n\t\t}\n\n\t\tresult.Impressum = c.Impressum\n\n\t\tparsedBot.Rules = cl\n\n\t\tresult.Bots = append(result.Bots, parsedBot)\n\t}\n\n\tfor _, t := range c.Thresholds {\n\t\tif t.Name == \"legacy-anubis-behaviour\" && t.Expression.String() == \"true\" {\n\t\t\tif !warnedAboutThresholds.Load() {\n\t\t\t\tslog.Warn(\"configuration file does not contain thresholds, see docs for details on how to upgrade\", \"fname\", fname, \"docs_url\", \"https://anubis.techaro.lol/docs/admin/configuration/thresholds/\")\n\t\t\t\twarnedAboutThresholds.Store(true)\n\t\t\t}\n\n\t\t\tt.Challenge.Difficulty = defaultDifficulty\n\t\t\tt.Challenge.ReportAs = defaultDifficulty\n\t\t}\n\n\t\tthreshold, err := ParsedThresholdFromConfig(t)\n\t\tif err != nil {\n\t\t\tvalidationErrs = append(validationErrs, fmt.Errorf(\"can't compile threshold config for %s: %w\", t.Name, err))\n\t\t\tcontinue\n\t\t}\n\n\t\tresult.Thresholds = append(result.Thresholds, threshold)\n\t}\n\n\tstFac, ok := store.Get(c.Store.Backend)\n\tswitch ok {\n\tcase true:\n\t\tstore, err := stFac.Build(ctx, c.Store.Parameters)\n\t\tif err != nil {\n\t\t\tvalidationErrs = append(validationErrs, err)\n\t\t} else {\n\t\t\tresult.Store = store\n\t\t}\n\tcase false:\n\t\tvalidationErrs = append(validationErrs, config.ErrUnknownStoreBackend)\n\t}\n\n\tif len(validationErrs) > 0 {\n\t\treturn nil, fmt.Errorf(\"errors validating policy config JSON %s: %w\", fname, errors.Join(validationErrs...))\n\t}\n\n\tresult.DNSBL = c.DNSBL\n\n\treturn result, nil\n}\n"], ["/anubis/lib/policy/config/config.go", "package config\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/fs\"\n\t\"net\"\n\t\"net/http\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis/data\"\n\t\"k8s.io/apimachinery/pkg/util/yaml\"\n)\n\nvar (\n\tErrNoBotRulesDefined = errors.New(\"config: must define at least one (1) bot rule\")\n\tErrBotMustHaveName = errors.New(\"config.Bot: must set name\")\n\tErrBotMustHaveUserAgentOrPath = errors.New(\"config.Bot: must set either user_agent_regex, path_regex, headers_regex, or remote_addresses\")\n\tErrBotMustHaveUserAgentOrPathNotBoth = errors.New(\"config.Bot: must set either user_agent_regex, path_regex, and not both\")\n\tErrUnknownAction = errors.New(\"config.Bot: unknown action\")\n\tErrInvalidUserAgentRegex = errors.New(\"config.Bot: invalid user agent regex\")\n\tErrInvalidPathRegex = errors.New(\"config.Bot: invalid path regex\")\n\tErrInvalidHeadersRegex = errors.New(\"config.Bot: invalid headers regex\")\n\tErrInvalidCIDR = errors.New(\"config.Bot: invalid CIDR\")\n\tErrRegexEndsWithNewline = errors.New(\"config.Bot: regular expression ends with newline (try >- instead of > in yaml)\")\n\tErrInvalidImportStatement = errors.New(\"config.ImportStatement: invalid source file\")\n\tErrCantSetBotAndImportValuesAtOnce = errors.New(\"config.BotOrImport: can't set bot rules and import values at the same time\")\n\tErrMustSetBotOrImportRules = errors.New(\"config.BotOrImport: rule definition is invalid, you must set either bot rules or an import statement, not both\")\n\tErrStatusCodeNotValid = errors.New(\"config.StatusCode: status code not valid, must be between 100 and 599\")\n)\n\ntype Rule string\n\nconst (\n\tRuleUnknown Rule = \"\"\n\tRuleAllow Rule = \"ALLOW\"\n\tRuleDeny Rule = \"DENY\"\n\tRuleChallenge Rule = \"CHALLENGE\"\n\tRuleWeigh Rule = \"WEIGH\"\n\tRuleBenchmark Rule = \"DEBUG_BENCHMARK\"\n)\n\nfunc (r Rule) Valid() error {\n\tswitch r {\n\tcase RuleAllow, RuleDeny, RuleChallenge, RuleWeigh, RuleBenchmark:\n\t\treturn nil\n\tdefault:\n\t\treturn ErrUnknownAction\n\t}\n}\n\nconst DefaultAlgorithm = \"fast\"\n\ntype BotConfig struct {\n\tUserAgentRegex *string `json:\"user_agent_regex,omitempty\" yaml:\"user_agent_regex,omitempty\"`\n\tPathRegex *string `json:\"path_regex,omitempty\" yaml:\"path_regex,omitempty\"`\n\tHeadersRegex map[string]string `json:\"headers_regex,omitempty\" yaml:\"headers_regex,omitempty\"`\n\tExpression *ExpressionOrList `json:\"expression,omitempty\" yaml:\"expression,omitempty\"`\n\tChallenge *ChallengeRules `json:\"challenge,omitempty\" yaml:\"challenge,omitempty\"`\n\tWeight *Weight `json:\"weight,omitempty\" yaml:\"weight,omitempty\"`\n\tName string `json:\"name\" yaml:\"name\"`\n\tAction Rule `json:\"action\" yaml:\"action\"`\n\tRemoteAddr []string `json:\"remote_addresses,omitempty\" yaml:\"remote_addresses,omitempty\"`\n\n\t// Thoth features\n\tGeoIP *GeoIP `json:\"geoip,omitempty\"`\n\tASNs *ASNs `json:\"asns,omitempty\"`\n}\n\nfunc (b BotConfig) Zero() bool {\n\tfor _, cond := range []bool{\n\t\tb.Name != \"\",\n\t\tb.UserAgentRegex != nil,\n\t\tb.PathRegex != nil,\n\t\tlen(b.HeadersRegex) != 0,\n\t\tb.Action != \"\",\n\t\tlen(b.RemoteAddr) != 0,\n\t\tb.Challenge != nil,\n\t\tb.GeoIP != nil,\n\t\tb.ASNs != nil,\n\t} {\n\t\tif cond {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc (b *BotConfig) Valid() error {\n\tvar errs []error\n\n\tif b.Name == \"\" {\n\t\terrs = append(errs, ErrBotMustHaveName)\n\t}\n\n\tallFieldsEmpty := b.UserAgentRegex == nil &&\n\t\tb.PathRegex == nil &&\n\t\tlen(b.RemoteAddr) == 0 &&\n\t\tlen(b.HeadersRegex) == 0 &&\n\t\tb.ASNs == nil &&\n\t\tb.GeoIP == nil\n\n\tif allFieldsEmpty && b.Expression == nil {\n\t\terrs = append(errs, ErrBotMustHaveUserAgentOrPath)\n\t}\n\n\tif b.UserAgentRegex != nil && b.PathRegex != nil {\n\t\terrs = append(errs, ErrBotMustHaveUserAgentOrPathNotBoth)\n\t}\n\n\tif b.UserAgentRegex != nil {\n\t\tif strings.HasSuffix(*b.UserAgentRegex, \"\\n\") {\n\t\t\terrs = append(errs, fmt.Errorf(\"%w: user agent regex: %q\", ErrRegexEndsWithNewline, *b.UserAgentRegex))\n\t\t}\n\n\t\tif _, err := regexp.Compile(*b.UserAgentRegex); err != nil {\n\t\t\terrs = append(errs, ErrInvalidUserAgentRegex, err)\n\t\t}\n\t}\n\n\tif b.PathRegex != nil {\n\t\tif strings.HasSuffix(*b.PathRegex, \"\\n\") {\n\t\t\terrs = append(errs, fmt.Errorf(\"%w: path regex: %q\", ErrRegexEndsWithNewline, *b.PathRegex))\n\t\t}\n\n\t\tif _, err := regexp.Compile(*b.PathRegex); err != nil {\n\t\t\terrs = append(errs, ErrInvalidPathRegex, err)\n\t\t}\n\t}\n\n\tif len(b.HeadersRegex) > 0 {\n\t\tfor name, expr := range b.HeadersRegex {\n\t\t\tif name == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif strings.HasSuffix(expr, \"\\n\") {\n\t\t\t\terrs = append(errs, fmt.Errorf(\"%w: header %s regex: %q\", ErrRegexEndsWithNewline, name, expr))\n\t\t\t}\n\n\t\t\tif _, err := regexp.Compile(expr); err != nil {\n\t\t\t\terrs = append(errs, ErrInvalidHeadersRegex, err)\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(b.RemoteAddr) > 0 {\n\t\tfor _, cidr := range b.RemoteAddr {\n\t\t\tif _, _, err := net.ParseCIDR(cidr); err != nil {\n\t\t\t\terrs = append(errs, ErrInvalidCIDR, err)\n\t\t\t}\n\t\t}\n\t}\n\n\tif b.Expression != nil {\n\t\tif err := b.Expression.Valid(); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\tswitch b.Action {\n\tcase RuleAllow, RuleBenchmark, RuleChallenge, RuleDeny, RuleWeigh:\n\t\t// okay\n\tdefault:\n\t\terrs = append(errs, fmt.Errorf(\"%w: %q\", ErrUnknownAction, b.Action))\n\t}\n\n\tif b.Action == RuleChallenge && b.Challenge != nil {\n\t\tif err := b.Challenge.Valid(); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\tif b.Action == RuleWeigh && b.Weight == nil {\n\t\tb.Weight = &Weight{Adjust: 5}\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"config: bot entry for %q is not valid:\\n%w\", b.Name, errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n\ntype ChallengeRules struct {\n\tAlgorithm string `json:\"algorithm,omitempty\" yaml:\"algorithm,omitempty\"`\n\tDifficulty int `json:\"difficulty,omitempty\" yaml:\"difficulty,omitempty\"`\n\tReportAs int `json:\"report_as,omitempty\" yaml:\"report_as,omitempty\"`\n}\n\nvar (\n\tErrChallengeDifficultyTooLow = errors.New(\"config.ChallengeRules: difficulty is too low (must be >= 1)\")\n\tErrChallengeDifficultyTooHigh = errors.New(\"config.ChallengeRules: difficulty is too high (must be <= 64)\")\n\tErrChallengeMustHaveAlgorithm = errors.New(\"config.ChallengeRules: must have algorithm name set\")\n)\n\nfunc (cr ChallengeRules) Valid() error {\n\tvar errs []error\n\n\tif cr.Algorithm == \"\" {\n\t\terrs = append(errs, ErrChallengeMustHaveAlgorithm)\n\t}\n\n\tif cr.Difficulty < 1 {\n\t\terrs = append(errs, fmt.Errorf(\"%w, got: %d\", ErrChallengeDifficultyTooLow, cr.Difficulty))\n\t}\n\n\tif cr.Difficulty > 64 {\n\t\terrs = append(errs, fmt.Errorf(\"%w, got: %d\", ErrChallengeDifficultyTooHigh, cr.Difficulty))\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"config: challenge rules entry is not valid:\\n%w\", errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n\ntype ImportStatement struct {\n\tImport string `json:\"import\"`\n\tBots []BotConfig\n}\n\nfunc (is *ImportStatement) open() (fs.File, error) {\n\tif strings.HasPrefix(is.Import, \"(data)/\") {\n\t\tfname := strings.TrimPrefix(is.Import, \"(data)/\")\n\t\tfin, err := data.BotPolicies.Open(fname)\n\t\treturn fin, err\n\t}\n\n\treturn os.Open(is.Import)\n}\n\nfunc (is *ImportStatement) load() error {\n\tfin, err := is.open()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%w: %s: %w\", ErrInvalidImportStatement, is.Import, err)\n\t}\n\tdefer fin.Close()\n\n\tvar imported []BotOrImport\n\tvar result []BotConfig\n\n\tif err := yaml.NewYAMLToJSONDecoder(fin).Decode(&imported); err != nil {\n\t\treturn fmt.Errorf(\"can't parse %s: %w\", is.Import, err)\n\t}\n\n\tvar errs []error\n\n\tfor _, b := range imported {\n\t\tif err := b.Valid(); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\n\t\tif b.ImportStatement != nil {\n\t\t\tresult = append(result, b.ImportStatement.Bots...)\n\t\t}\n\n\t\tif b.BotConfig != nil {\n\t\t\tresult = append(result, *b.BotConfig)\n\t\t}\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"config %s is not valid:\\n%w\", is.Import, errors.Join(errs...))\n\t}\n\n\tis.Bots = result\n\n\treturn nil\n}\n\nfunc (is *ImportStatement) Valid() error {\n\treturn is.load()\n}\n\ntype BotOrImport struct {\n\t*BotConfig `json:\",inline\"`\n\t*ImportStatement `json:\",inline\"`\n}\n\nfunc (boi *BotOrImport) Valid() error {\n\tif boi.BotConfig != nil && boi.ImportStatement != nil {\n\t\treturn ErrCantSetBotAndImportValuesAtOnce\n\t}\n\n\tif boi.BotConfig != nil {\n\t\treturn boi.BotConfig.Valid()\n\t}\n\n\tif boi.ImportStatement != nil {\n\t\treturn boi.ImportStatement.Valid()\n\t}\n\n\treturn ErrMustSetBotOrImportRules\n}\n\ntype StatusCodes struct {\n\tChallenge int `json:\"CHALLENGE\"`\n\tDeny int `json:\"DENY\"`\n}\n\nfunc (sc StatusCodes) Valid() error {\n\tvar errs []error\n\n\tif sc.Challenge == 0 || (sc.Challenge < 100 && sc.Challenge >= 599) {\n\t\terrs = append(errs, fmt.Errorf(\"%w: challenge is %d\", ErrStatusCodeNotValid, sc.Challenge))\n\t}\n\n\tif sc.Deny == 0 || (sc.Deny < 100 && sc.Deny >= 599) {\n\t\terrs = append(errs, fmt.Errorf(\"%w: deny is %d\", ErrStatusCodeNotValid, sc.Deny))\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"status codes not valid:\\n%w\", errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n\ntype fileConfig struct {\n\tBots []BotOrImport `json:\"bots\"`\n\tDNSBL bool `json:\"dnsbl\"`\n\tOpenGraph openGraphFileConfig `json:\"openGraph,omitempty\"`\n\tImpressum *Impressum `json:\"impressum,omitempty\"`\n\tStatusCodes StatusCodes `json:\"status_codes\"`\n\tStore *Store `json:\"store\"`\n\tThresholds []Threshold `json:\"thresholds\"`\n}\n\nfunc (c *fileConfig) Valid() error {\n\tvar errs []error\n\n\tif len(c.Bots) == 0 {\n\t\terrs = append(errs, ErrNoBotRulesDefined)\n\t}\n\n\tfor i, b := range c.Bots {\n\t\tif err := b.Valid(); err != nil {\n\t\t\terrs = append(errs, fmt.Errorf(\"bot %d: %w\", i, err))\n\t\t}\n\t}\n\n\tif c.OpenGraph.Enabled {\n\t\tif err := c.OpenGraph.Valid(); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\tif err := c.StatusCodes.Valid(); err != nil {\n\t\terrs = append(errs, err)\n\t}\n\n\tfor i, t := range c.Thresholds {\n\t\tif err := t.Valid(); err != nil {\n\t\t\terrs = append(errs, fmt.Errorf(\"threshold %d: %w\", i, err))\n\t\t}\n\t}\n\n\tif c.Store != nil {\n\t\tif err := c.Store.Valid(); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"config is not valid:\\n%w\", errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n\nfunc Load(fin io.Reader, fname string) (*Config, error) {\n\tc := &fileConfig{\n\t\tStatusCodes: StatusCodes{\n\t\t\tChallenge: http.StatusOK,\n\t\t\tDeny: http.StatusOK,\n\t\t},\n\t\tStore: &Store{\n\t\t\tBackend: \"memory\",\n\t\t},\n\t}\n\n\tif err := yaml.NewYAMLToJSONDecoder(fin).Decode(&c); err != nil {\n\t\treturn nil, fmt.Errorf(\"can't parse policy config YAML %s: %w\", fname, err)\n\t}\n\n\tif err := c.Valid(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult := &Config{\n\t\tDNSBL: c.DNSBL,\n\t\tOpenGraph: OpenGraph{\n\t\t\tEnabled: c.OpenGraph.Enabled,\n\t\t\tConsiderHost: c.OpenGraph.ConsiderHost,\n\t\t\tOverride: c.OpenGraph.Override,\n\t\t},\n\t\tStatusCodes: c.StatusCodes,\n\t\tStore: c.Store,\n\t}\n\n\tif c.OpenGraph.TimeToLive != \"\" {\n\t\t// XXX(Xe): already validated in Valid()\n\t\togTTL, _ := time.ParseDuration(c.OpenGraph.TimeToLive)\n\t\tresult.OpenGraph.TimeToLive = ogTTL\n\t}\n\n\tvar validationErrs []error\n\n\tfor _, boi := range c.Bots {\n\t\tif boi.ImportStatement != nil {\n\t\t\tif err := boi.load(); err != nil {\n\t\t\t\tvalidationErrs = append(validationErrs, err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tresult.Bots = append(result.Bots, boi.ImportStatement.Bots...)\n\t\t}\n\n\t\tif boi.BotConfig != nil {\n\t\t\tif err := boi.BotConfig.Valid(); err != nil {\n\t\t\t\tvalidationErrs = append(validationErrs, err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tresult.Bots = append(result.Bots, *boi.BotConfig)\n\t\t}\n\t}\n\n\tif c.Impressum != nil {\n\t\tif err := c.Impressum.Valid(); err != nil {\n\t\t\tvalidationErrs = append(validationErrs, err)\n\t\t}\n\n\t\tresult.Impressum = c.Impressum\n\t}\n\n\tif len(c.Thresholds) == 0 {\n\t\tc.Thresholds = DefaultThresholds\n\t}\n\n\tfor _, t := range c.Thresholds {\n\t\tif err := t.Valid(); err != nil {\n\t\t\tvalidationErrs = append(validationErrs, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tresult.Thresholds = append(result.Thresholds, t)\n\t}\n\n\tif len(validationErrs) > 0 {\n\t\treturn nil, fmt.Errorf(\"errors validating policy config %s: %w\", fname, errors.Join(validationErrs...))\n\t}\n\n\treturn result, nil\n}\n\ntype Config struct {\n\tBots []BotConfig\n\tThresholds []Threshold\n\tDNSBL bool\n\tImpressum *Impressum\n\tOpenGraph OpenGraph\n\tStatusCodes StatusCodes\n\tStore *Store\n}\n\nfunc (c Config) Valid() error {\n\tvar errs []error\n\n\tif len(c.Bots) == 0 {\n\t\terrs = append(errs, ErrNoBotRulesDefined)\n\t}\n\n\tfor _, b := range c.Bots {\n\t\tif err := b.Valid(); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"config is not valid:\\n%w\", errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n"], ["/anubis/internal/ogtags/fetch.go", "package ogtags\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log/slog\"\n\t\"mime\"\n\t\"net\"\n\t\"net/http\"\n\n\t\"golang.org/x/net/html\"\n)\n\nvar (\n\tErrOgHandled = errors.New(\"og: handled error\") // used to indicate that the error was handled and should not be logged\n\temptyMap = map[string]string{} // used to indicate an empty result in the cache. Can't use nil as it would be a cache miss.\n)\n\n// fetchHTMLDocumentWithCache fetches the HTML document from the given URL string,\n// preserving the original host header.\nfunc (c *OGTagCache) fetchHTMLDocumentWithCache(ctx context.Context, urlStr string, originalHost string, cacheKey string) (*html.Node, error) {\n\treq, err := http.NewRequestWithContext(ctx, \"GET\", urlStr, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create http request: %w\", err)\n\t}\n\n\t// Set the Host header to the original host\n\tif originalHost != \"\" {\n\t\treq.Host = originalHost\n\t}\n\n\t// Add proxy headers\n\treq.Header.Set(\"X-Forwarded-Proto\", \"https\")\n\treq.Header.Set(\"User-Agent\", \"Anubis-OGTag-Fetcher/1.0\") // For tracking purposes\n\n\t// Send the request\n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\tvar netErr net.Error\n\t\tif errors.As(err, &netErr) && netErr.Timeout() {\n\t\t\tslog.Debug(\"og: request timed out\", \"url\", urlStr)\n\t\t\tc.cache.Set(ctx, cacheKey, emptyMap, c.ogTimeToLive/2) // Cache empty result for half the TTL to not spam the server\n\t\t}\n\t\treturn nil, fmt.Errorf(\"http get failed: %w\", err)\n\t}\n\n\t// Ensure the response body is closed\n\tdefer func(Body io.ReadCloser) {\n\t\terr := Body.Close()\n\t\tif err != nil {\n\t\t\tslog.Debug(\"og: error closing response body\", \"url\", urlStr, \"error\", err)\n\t\t}\n\t}(resp.Body)\n\n\tif resp.StatusCode != http.StatusOK {\n\t\tslog.Debug(\"og: received non-OK status code\", \"url\", urlStr, \"status\", resp.StatusCode)\n\t\tc.cache.Set(ctx, cacheKey, emptyMap, c.ogTimeToLive) // Cache empty result for non-successful status codes\n\t\treturn nil, fmt.Errorf(\"%w: page not found\", ErrOgHandled)\n\t}\n\n\t// Check content type\n\tct := resp.Header.Get(\"Content-Type\")\n\tif ct == \"\" {\n\t\treturn nil, fmt.Errorf(\"missing Content-Type header\")\n\t} else {\n\t\tmediaType, _, err := mime.ParseMediaType(ct)\n\t\tif err != nil {\n\t\t\tslog.Debug(\"og: malformed Content-Type header\", \"url\", urlStr, \"contentType\", ct)\n\t\t\treturn nil, fmt.Errorf(\"%w malformed Content-Type header: %w\", ErrOgHandled, err)\n\t\t}\n\n\t\tif mediaType != \"text/html\" && mediaType != \"application/xhtml+xml\" {\n\t\t\tslog.Debug(\"og: unsupported Content-Type\", \"url\", urlStr, \"contentType\", mediaType)\n\t\t\treturn nil, fmt.Errorf(\"%w unsupported Content-Type: %s\", ErrOgHandled, mediaType)\n\t\t}\n\t}\n\n\tresp.Body = http.MaxBytesReader(nil, resp.Body, maxContentLength)\n\n\tdoc, err := html.Parse(resp.Body)\n\tif err != nil {\n\t\t// Check if the error is specifically because the limit was exceeded\n\t\tvar maxBytesErr *http.MaxBytesError\n\t\tif errors.As(err, &maxBytesErr) {\n\t\t\tslog.Debug(\"og: content exceeded max length\", \"url\", urlStr, \"limit\", maxContentLength)\n\t\t\treturn nil, fmt.Errorf(\"content too large: exceeded %d bytes\", maxContentLength)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"failed to parse HTML: %w\", err)\n\t}\n\n\treturn doc, nil\n}\n"], ["/anubis/cmd/robots2policy/batch/batch_process.go", "/*\nBatch process robots.txt files from archives like https://github.com/nrjones8/robots-dot-txt-archive-bot/tree/master/data/cleaned\ninto Anubis CEL policies. Usage: go run batch_process.go \n*/\npackage main\n\nimport (\n\t\"fmt\"\n\t\"io/fs\"\n\t\"log\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\nfunc main() {\n\tif len(os.Args) < 2 {\n\t\tfmt.Println(\"Usage: go run batch_process.go \")\n\t\tfmt.Println(\"Example: go run batch_process.go ./cleaned\")\n\t\tos.Exit(1)\n\t}\n\n\tcleanedDir := os.Args[1]\n\toutputDir := \"generated_policies\"\n\n\t// Create output directory\n\tif err := os.MkdirAll(outputDir, 0755); err != nil {\n\t\tlog.Fatalf(\"Failed to create output directory: %v\", err)\n\t}\n\n\tcount := 0\n\terr := filepath.WalkDir(cleanedDir, func(path string, d fs.DirEntry, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Skip directories\n\t\tif d.IsDir() {\n\t\t\treturn nil\n\t\t}\n\n\t\t// Generate policy name from file path\n\t\trelPath, _ := filepath.Rel(cleanedDir, path)\n\t\tpolicyName := strings.ReplaceAll(relPath, \"/\", \"-\")\n\t\tpolicyName = strings.TrimSuffix(policyName, \"-robots.txt\")\n\t\tpolicyName = strings.ReplaceAll(policyName, \".\", \"-\")\n\n\t\toutputFile := filepath.Join(outputDir, policyName+\".yaml\")\n\n\t\tcmd := exec.Command(\"go\", \"run\", \"main.go\",\n\t\t\t\"-input\", path,\n\t\t\t\"-output\", outputFile,\n\t\t\t\"-name\", policyName,\n\t\t\t\"-format\", \"yaml\")\n\n\t\tif err := cmd.Run(); err != nil {\n\t\t\tfmt.Printf(\"Warning: Failed to process %s: %v\\n\", path, err)\n\t\t\treturn nil // Continue processing other files\n\t\t}\n\n\t\tcount++\n\t\tif count%100 == 0 {\n\t\t\tfmt.Printf(\"Processed %d files...\\n\", count)\n\t\t} else if count%10 == 0 {\n\t\t\tfmt.Print(\".\")\n\t\t}\n\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\tlog.Fatalf(\"Error walking directory: %v\", err)\n\t}\n\n\tfmt.Printf(\"Successfully processed %d robots.txt files\\n\", count)\n\tfmt.Printf(\"Generated policies saved to: %s/\\n\", outputDir)\n}\n"], ["/anubis/lib/store/bbolt/bbolt.go", "package bbolt\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n\t\"go.etcd.io/bbolt\"\n)\n\n// Sentinel error values used for testing and in admin-visible error messages.\nvar (\n\tErrBucketDoesNotExist = errors.New(\"bbolt: bucket does not exist\")\n\tErrNotExists = errors.New(\"bbolt: value does not exist in store\")\n)\n\n// Store implements store.Interface backed by bbolt[1].\n//\n// In essence, bbolt is a hierarchical key/value store with a twist: every value\n// needs to belong to a bucket. Buckets can contain an infinite number of\n// buckets. As such, Anubis nests values in buckets. Each value in the store\n// is given its own bucket with two keys:\n//\n// 1. data - The raw data, usually in JSON\n// 2. expiry - The expiry time formatted as a time.RFC3339Nano timestamp string\n//\n// When Anubis stores a new bit of data, it creates a new bucket for that value.\n// This allows the cleanup phase to iterate over every bucket in the database and\n// only scan the expiry times without having to decode the entire record.\n//\n// bbolt is not suitable for environments where multiple instance of Anubis need\n// to read from and write to the same backend store. For that, use the valkey\n// storage backend.\n//\n// [1]: https://github.com/etcd-io/bbolt\ntype Store struct {\n\tbdb *bbolt.DB\n}\n\n// Delete a key from the datastore. If the key does not exist, return an error.\nfunc (s *Store) Delete(ctx context.Context, key string) error {\n\treturn s.bdb.Update(func(tx *bbolt.Tx) error {\n\t\tif tx.Bucket([]byte(key)) == nil {\n\t\t\treturn fmt.Errorf(\"%w: %q\", ErrNotExists, key)\n\t\t}\n\n\t\treturn tx.DeleteBucket([]byte(key))\n\t})\n}\n\n// Get a value from the datastore.\n//\n// Because each value is stored in its own bucket with data and expiry keys,\n// two get operations are required:\n//\n// 1. Get the expiry key, parse as time.RFC3339Nano. If the key has expired, run deletion in the background and return a \"key not found\" error.\n// 2. Get the data key, copy into the result byteslice, return it.\nfunc (s *Store) Get(ctx context.Context, key string) ([]byte, error) {\n\tvar result []byte\n\n\tif err := s.bdb.View(func(tx *bbolt.Tx) error {\n\t\titemBucket := tx.Bucket([]byte(key))\n\t\tif itemBucket == nil {\n\t\t\treturn fmt.Errorf(\"%w: %q\", store.ErrNotFound, key)\n\t\t}\n\n\t\texpiryStr := itemBucket.Get([]byte(\"expiry\"))\n\t\tif expiryStr == nil {\n\t\t\treturn fmt.Errorf(\"[unexpected] %w: %q (expiry is nil)\", store.ErrNotFound, key)\n\t\t}\n\n\t\texpiry, err := time.Parse(time.RFC3339Nano, string(expiryStr))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"[unexpected] %w: %w\", store.ErrCantDecode, err)\n\t\t}\n\n\t\tif time.Now().After(expiry) {\n\t\t\tgo s.Delete(context.Background(), key)\n\t\t\treturn fmt.Errorf(\"%w: %q\", store.ErrNotFound, key)\n\t\t}\n\n\t\tdataStr := itemBucket.Get([]byte(\"data\"))\n\t\tif dataStr == nil {\n\t\t\treturn fmt.Errorf(\"[unexpected] %w: %q (data is nil)\", store.ErrNotFound, key)\n\t\t}\n\n\t\tresult = make([]byte, len(dataStr))\n\t\tif n := copy(result, dataStr); n != len(dataStr) {\n\t\t\treturn fmt.Errorf(\"[unexpected] %w: %d bytes copied of %d\", store.ErrCantDecode, n, len(dataStr))\n\t\t}\n\n\t\treturn nil\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn result, nil\n}\n\n// Set a value into the store with a given expiry.\nfunc (s *Store) Set(ctx context.Context, key string, value []byte, expiry time.Duration) error {\n\texpires := time.Now().Add(expiry)\n\n\treturn s.bdb.Update(func(tx *bbolt.Tx) error {\n\t\tvalueBkt, err := tx.CreateBucketIfNotExists([]byte(key))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"%w: %w: %q (create bucket)\", store.ErrCantEncode, err, key)\n\t\t}\n\n\t\tif err := valueBkt.Put([]byte(\"expiry\"), []byte(expires.Format(time.RFC3339Nano))); err != nil {\n\t\t\treturn fmt.Errorf(\"%w: %q (expiry)\", store.ErrCantEncode, key)\n\t\t}\n\n\t\tif err := valueBkt.Put([]byte(\"data\"), value); err != nil {\n\t\t\treturn fmt.Errorf(\"%w: %q (data)\", store.ErrCantEncode, key)\n\t\t}\n\n\t\treturn nil\n\t})\n}\n\nfunc (s *Store) cleanup(ctx context.Context) error {\n\tnow := time.Now()\n\n\treturn s.bdb.Update(func(tx *bbolt.Tx) error {\n\t\treturn tx.ForEach(func(key []byte, valueBkt *bbolt.Bucket) error {\n\t\t\tvar expiry time.Time\n\t\t\tvar err error\n\n\t\t\texpiryStr := valueBkt.Get([]byte(\"expiry\"))\n\t\t\tif expiryStr == nil {\n\t\t\t\tslog.Warn(\"while running cleanup, expiry is not set somehow, file a bug?\", \"key\", string(key))\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\texpiry, err = time.Parse(time.RFC3339Nano, string(expiryStr))\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"[unexpected] %w in bucket %q: %w\", store.ErrCantDecode, string(key), err)\n\t\t\t}\n\n\t\t\tif now.After(expiry) {\n\t\t\t\treturn tx.DeleteBucket(key)\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\t})\n}\n\nfunc (s *Store) cleanupThread(ctx context.Context) {\n\tt := time.NewTicker(time.Hour)\n\tdefer t.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase <-t.C:\n\t\t\tif err := s.cleanup(ctx); err != nil {\n\t\t\t\tslog.Error(\"error during bbolt cleanup\", \"err\", err)\n\t\t\t}\n\t\t}\n\t}\n}\n"], ["/anubis/lib/thoth/thoth.go", "package thoth\n\nimport (\n\t\"context\"\n\t\"crypto/tls\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\tiptoasnv1 \"github.com/TecharoHQ/thoth-proto/gen/techaro/thoth/iptoasn/v1\"\n\tgrpcprom \"github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus\"\n\t\"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/timeout\"\n\t\"github.com/prometheus/client_golang/prometheus\"\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/credentials\"\n\t\"google.golang.org/grpc/credentials/insecure\"\n\thealthv1 \"google.golang.org/grpc/health/grpc_health_v1\"\n)\n\ntype Client struct {\n\tconn *grpc.ClientConn\n\thealth healthv1.HealthClient\n\tIPToASN iptoasnv1.IpToASNServiceClient\n}\n\nfunc New(ctx context.Context, thothURL, apiToken string, plaintext bool) (*Client, error) {\n\tclMetrics := grpcprom.NewClientMetrics(\n\t\tgrpcprom.WithClientHandlingTimeHistogram(\n\t\t\tgrpcprom.WithHistogramBuckets([]float64{0.001, 0.01, 0.1, 0.3, 0.6, 1, 3, 6, 9, 20, 30, 60, 90, 120}),\n\t\t),\n\t)\n\tprometheus.DefaultRegisterer.Register(clMetrics)\n\n\tdo := []grpc.DialOption{\n\t\tgrpc.WithChainUnaryInterceptor(\n\t\t\ttimeout.UnaryClientInterceptor(500*time.Millisecond),\n\t\t\tclMetrics.UnaryClientInterceptor(),\n\t\t\tauthUnaryClientInterceptor(apiToken),\n\t\t),\n\t\tgrpc.WithChainStreamInterceptor(\n\t\t\tclMetrics.StreamClientInterceptor(),\n\t\t\tauthStreamClientInterceptor(apiToken),\n\t\t),\n\t\tgrpc.WithUserAgent(fmt.Sprint(\"Techaro/anubis:\", anubis.Version)),\n\t}\n\n\tif plaintext {\n\t\tdo = append(do, grpc.WithTransportCredentials(insecure.NewCredentials()))\n\t} else {\n\t\tdo = append(do, grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{})))\n\t}\n\n\tconn, err := grpc.NewClient(\n\t\tthothURL,\n\t\tdo...,\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't dial thoth at %s: %w\", thothURL, err)\n\t}\n\n\thc := healthv1.NewHealthClient(conn)\n\n\treturn &Client{\n\t\tconn: conn,\n\t\thealth: hc,\n\t\tIPToASN: NewIpToASNWithCache(iptoasnv1.NewIpToASNServiceClient(conn)),\n\t}, nil\n}\n\nfunc (c *Client) Close() error {\n\tif c.conn != nil {\n\t\treturn c.conn.Close()\n\t}\n\treturn nil\n}\n\nfunc (c *Client) WithIPToASNService(impl iptoasnv1.IpToASNServiceClient) {\n\tc.IPToASN = impl\n}\n"], ["/anubis/lib/thoth/cachediptoasn.go", "package thoth\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net/netip\"\n\n\tiptoasnv1 \"github.com/TecharoHQ/thoth-proto/gen/techaro/thoth/iptoasn/v1\"\n\t\"github.com/gaissmai/bart\"\n\t\"google.golang.org/grpc\"\n)\n\ntype IPToASNWithCache struct {\n\tnext iptoasnv1.IpToASNServiceClient\n\ttable *bart.Table[*iptoasnv1.LookupResponse]\n}\n\nfunc NewIpToASNWithCache(next iptoasnv1.IpToASNServiceClient) *IPToASNWithCache {\n\tresult := &IPToASNWithCache{\n\t\tnext: next,\n\t\ttable: &bart.Table[*iptoasnv1.LookupResponse]{},\n\t}\n\n\tfor _, pfx := range []netip.Prefix{\n\t\tnetip.MustParsePrefix(\"10.0.0.0/8\"), // RFC 1918\n\t\tnetip.MustParsePrefix(\"172.16.0.0/12\"), // RFC 1918\n\t\tnetip.MustParsePrefix(\"192.168.0.0/16\"), // RFC 1918\n\t\tnetip.MustParsePrefix(\"127.0.0.0/8\"), // Loopback\n\t\tnetip.MustParsePrefix(\"169.254.0.0/16\"), // Link-local\n\t\tnetip.MustParsePrefix(\"100.64.0.0/10\"), // CGNAT\n\t\tnetip.MustParsePrefix(\"192.0.0.0/24\"), // Protocol assignments\n\t\tnetip.MustParsePrefix(\"192.0.2.0/24\"), // TEST-NET-1\n\t\tnetip.MustParsePrefix(\"198.18.0.0/15\"), // Benchmarking\n\t\tnetip.MustParsePrefix(\"198.51.100.0/24\"), // TEST-NET-2\n\t\tnetip.MustParsePrefix(\"203.0.113.0/24\"), // TEST-NET-3\n\t\tnetip.MustParsePrefix(\"240.0.0.0/4\"), // Reserved\n\t\tnetip.MustParsePrefix(\"255.255.255.255/32\"), // Broadcast\n\t\tnetip.MustParsePrefix(\"fc00::/7\"), // Unique local address\n\t\tnetip.MustParsePrefix(\"fe80::/10\"), // Link-local\n\t\tnetip.MustParsePrefix(\"::1/128\"), // Loopback\n\t\tnetip.MustParsePrefix(\"::/128\"), // Unspecified\n\t\tnetip.MustParsePrefix(\"100::/64\"), // Discard-only\n\t\tnetip.MustParsePrefix(\"2001:db8::/32\"), // Documentation\n\t} {\n\t\tresult.table.Insert(pfx, &iptoasnv1.LookupResponse{Announced: false})\n\t}\n\n\treturn result\n}\n\nfunc (ip2asn *IPToASNWithCache) Lookup(ctx context.Context, lr *iptoasnv1.LookupRequest, opts ...grpc.CallOption) (*iptoasnv1.LookupResponse, error) {\n\taddr, err := netip.ParseAddr(lr.GetIpAddress())\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"input is not an IP address: %w\", err)\n\t}\n\n\tcachedResponse, ok := ip2asn.table.Lookup(addr)\n\tif ok {\n\t\treturn cachedResponse, nil\n\t}\n\n\tresp, err := ip2asn.next.Lookup(ctx, lr, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar errs []error\n\tfor _, cidr := range resp.GetCidr() {\n\t\tpfx, err := netip.ParsePrefix(cidr)\n\t\tif err != nil {\n\t\t\terrs = append(errs, err)\n\t\t\tcontinue\n\t\t}\n\t\tip2asn.table.Insert(pfx, resp)\n\t}\n\n\tif len(errs) != 0 {\n\t\tslog.Error(\"errors parsing IP prefixes\", \"err\", errors.Join(errs...))\n\t}\n\n\treturn resp, nil\n}\n"], ["/anubis/lib/thoth/asnchecker.go", "package thoth\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net/http\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis/internal\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/checker\"\n\tiptoasnv1 \"github.com/TecharoHQ/thoth-proto/gen/techaro/thoth/iptoasn/v1\"\n)\n\nfunc (c *Client) ASNCheckerFor(asns []uint32) checker.Impl {\n\tasnMap := map[uint32]struct{}{}\n\tvar sb strings.Builder\n\tfmt.Fprintln(&sb, \"ASNChecker\")\n\tfor _, asn := range asns {\n\t\tasnMap[asn] = struct{}{}\n\t\tfmt.Fprintln(&sb, \"AS\", asn)\n\t}\n\n\treturn &ASNChecker{\n\t\tiptoasn: c.IPToASN,\n\t\tasns: asnMap,\n\t\thash: internal.FastHash(sb.String()),\n\t}\n}\n\ntype ASNChecker struct {\n\tiptoasn iptoasnv1.IpToASNServiceClient\n\tasns map[uint32]struct{}\n\thash string\n}\n\nfunc (asnc *ASNChecker) Check(r *http.Request) (bool, error) {\n\tctx, cancel := context.WithTimeout(r.Context(), 500*time.Millisecond)\n\tdefer cancel()\n\n\tipInfo, err := asnc.iptoasn.Lookup(ctx, &iptoasnv1.LookupRequest{\n\t\tIpAddress: r.Header.Get(\"X-Real-Ip\"),\n\t})\n\tif err != nil {\n\t\tswitch {\n\t\tcase errors.Is(err, context.DeadlineExceeded):\n\t\t\tslog.Debug(\"error contacting thoth\", \"err\", err, \"actionable\", false)\n\t\t\treturn false, nil\n\t\tdefault:\n\t\t\tslog.Error(\"error contacting thoth, please contact support\", \"err\", err, \"actionable\", true)\n\t\t\treturn false, nil\n\t\t}\n\t}\n\n\t// If IP is not publicly announced, return false\n\tif !ipInfo.GetAnnounced() {\n\t\treturn false, nil\n\t}\n\n\t_, ok := asnc.asns[uint32(ipInfo.GetAsNumber())]\n\n\treturn ok, nil\n}\n\nfunc (asnc *ASNChecker) Hash() string {\n\treturn asnc.hash\n}\n"], ["/anubis/lib/thoth/geoipchecker.go", "package thoth\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net/http\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis/lib/policy/checker\"\n\tiptoasnv1 \"github.com/TecharoHQ/thoth-proto/gen/techaro/thoth/iptoasn/v1\"\n)\n\nfunc (c *Client) GeoIPCheckerFor(countries []string) checker.Impl {\n\tcountryMap := map[string]struct{}{}\n\tvar sb strings.Builder\n\tfmt.Fprintln(&sb, \"GeoIPChecker\")\n\tfor _, cc := range countries {\n\t\tcountryMap[cc] = struct{}{}\n\t\tfmt.Fprintln(&sb, cc)\n\t}\n\n\treturn &GeoIPChecker{\n\t\tIPToASN: c.IPToASN,\n\t\tCountries: countryMap,\n\t\thash: sb.String(),\n\t}\n}\n\ntype GeoIPChecker struct {\n\tIPToASN iptoasnv1.IpToASNServiceClient\n\tCountries map[string]struct{}\n\thash string\n}\n\nfunc (gipc *GeoIPChecker) Check(r *http.Request) (bool, error) {\n\tctx, cancel := context.WithTimeout(r.Context(), 500*time.Millisecond)\n\tdefer cancel()\n\n\tipInfo, err := gipc.IPToASN.Lookup(ctx, &iptoasnv1.LookupRequest{\n\t\tIpAddress: r.Header.Get(\"X-Real-Ip\"),\n\t})\n\tif err != nil {\n\t\tswitch {\n\t\tcase errors.Is(err, context.DeadlineExceeded):\n\t\t\tslog.Debug(\"error contacting thoth\", \"err\", err, \"actionable\", false)\n\t\t\treturn false, nil\n\t\tdefault:\n\t\t\tslog.Error(\"error contacting thoth, please contact support\", \"err\", err, \"actionable\", true)\n\t\t\treturn false, nil\n\t\t}\n\t}\n\n\t// If IP is not publicly announced, return false\n\tif !ipInfo.GetAnnounced() {\n\t\treturn false, nil\n\t}\n\n\t_, ok := gipc.Countries[strings.ToLower(ipInfo.GetCountryCode())]\n\n\treturn ok, nil\n}\n\nfunc (gipc *GeoIPChecker) Hash() string {\n\treturn gipc.hash\n}\n"], ["/anubis/lib/localization/localization.go", "package localization\n\nimport (\n\t\"embed\"\n\t\"encoding/json\"\n\t\"net/http\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/nicksnyder/go-i18n/v2/i18n\"\n\t\"golang.org/x/text/language\"\n)\n\n//go:embed locales/*.json\nvar localeFS embed.FS\n\ntype LocalizationService struct {\n\tbundle *i18n.Bundle\n}\n\nvar (\n\tglobalService *LocalizationService\n\tonce sync.Once\n)\n\nfunc NewLocalizationService() *LocalizationService {\n\tonce.Do(func() {\n\t\tbundle := i18n.NewBundle(language.English)\n\t\tbundle.RegisterUnmarshalFunc(\"json\", json.Unmarshal)\n\n\t\t// Read all JSON files from the locales directory\n\t\tentries, err := localeFS.ReadDir(\"locales\")\n\t\tif err != nil {\n\t\t\t// Try fallback - create a minimal service with default messages\n\t\t\tglobalService = &LocalizationService{bundle: bundle}\n\t\t\treturn\n\t\t}\n\n\t\tloadedAny := false\n\t\tfor _, entry := range entries {\n\t\t\tif !entry.IsDir() && strings.HasSuffix(entry.Name(), \".json\") {\n\t\t\t\tfilePath := \"locales/\" + entry.Name()\n\t\t\t\t_, err := bundle.LoadMessageFileFS(localeFS, filePath)\n\t\t\t\tif err != nil {\n\t\t\t\t\t// Log error but continue with other files\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tloadedAny = true\n\t\t\t}\n\t\t}\n\n\t\tif !loadedAny {\n\t\t\t// If no files were loaded successfully, create minimal service\n\t\t\tglobalService = &LocalizationService{bundle: bundle}\n\t\t\treturn\n\t\t}\n\n\t\tglobalService = &LocalizationService{bundle: bundle}\n\t})\n\n\t// Safety check - if globalService is still nil, create a minimal one\n\tif globalService == nil {\n\t\tbundle := i18n.NewBundle(language.English)\n\t\tbundle.RegisterUnmarshalFunc(\"json\", json.Unmarshal)\n\t\tglobalService = &LocalizationService{bundle: bundle}\n\t}\n\n\treturn globalService\n}\n\nfunc (ls *LocalizationService) GetLocalizer(lang string) *i18n.Localizer {\n\treturn i18n.NewLocalizer(ls.bundle, lang)\n}\n\nfunc (ls *LocalizationService) GetLocalizerFromRequest(r *http.Request) *i18n.Localizer {\n\tif ls == nil || ls.bundle == nil {\n\t\t// Fallback to a basic bundle if service is not properly initialized\n\t\tbundle := i18n.NewBundle(language.English)\n\t\tbundle.RegisterUnmarshalFunc(\"json\", json.Unmarshal)\n\t\treturn i18n.NewLocalizer(bundle, \"en\")\n\t}\n\tacceptLanguage := r.Header.Get(\"Accept-Language\")\n\treturn i18n.NewLocalizer(ls.bundle, acceptLanguage, \"en\")\n}\n\n// SimpleLocalizer wraps i18n.Localizer with a more convenient API\ntype SimpleLocalizer struct {\n\tLocalizer *i18n.Localizer\n}\n\n// T provides a concise way to localize messages\nfunc (sl *SimpleLocalizer) T(messageID string) string {\n\treturn sl.Localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: messageID})\n}\n\n// Get the language that is used by the localizer by retrieving a well-known string that is required to be present\nfunc (sl *SimpleLocalizer) GetLang() string {\n\t_, tag, err := sl.Localizer.LocalizeWithTag(&i18n.LocalizeConfig{MessageID: \"loading\"})\n\tif err != nil {\n\t\treturn \"en\"\n\t}\n\treturn tag.String()\n}\n\n// GetLocalizer creates a localizer based on the request's Accept-Language header or forcedLanguage option\nfunc GetLocalizer(r *http.Request) *SimpleLocalizer {\n\tvar localizer *i18n.Localizer\n\tif anubis.ForcedLanguage == \"\" {\n\t\tlocalizer = NewLocalizationService().GetLocalizerFromRequest(r)\n\t} else {\n\t\tlocalizer = NewLocalizationService().GetLocalizer(anubis.ForcedLanguage)\n\t}\n\treturn &SimpleLocalizer{Localizer: localizer}\n}\n"], ["/anubis/lib/policy/checker.go", "package policy\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/netip\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com/TecharoHQ/anubis/internal\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/checker\"\n\t\"github.com/gaissmai/bart\"\n)\n\nvar (\n\tErrMisconfiguration = errors.New(\"[unexpected] policy: administrator misconfiguration\")\n)\n\ntype RemoteAddrChecker struct {\n\tprefixTable *bart.Lite\n\thash string\n}\n\nfunc NewRemoteAddrChecker(cidrs []string) (checker.Impl, error) {\n\ttable := new(bart.Lite)\n\n\tfor _, cidr := range cidrs {\n\t\tprefix, err := netip.ParsePrefix(cidr)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"%w: range %s not parsing: %w\", ErrMisconfiguration, cidr, err)\n\t\t}\n\n\t\ttable.Insert(prefix)\n\t}\n\n\treturn &RemoteAddrChecker{\n\t\tprefixTable: table,\n\t\thash: internal.FastHash(strings.Join(cidrs, \",\")),\n\t}, nil\n}\n\nfunc (rac *RemoteAddrChecker) Check(r *http.Request) (bool, error) {\n\thost := r.Header.Get(\"X-Real-Ip\")\n\tif host == \"\" {\n\t\treturn false, fmt.Errorf(\"%w: header X-Real-Ip is not set\", ErrMisconfiguration)\n\t}\n\n\taddr, err := netip.ParseAddr(host)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"%w: %s is not an IP address: %w\", ErrMisconfiguration, host, err)\n\t}\n\n\treturn rac.prefixTable.Contains(addr), nil\n}\n\nfunc (rac *RemoteAddrChecker) Hash() string {\n\treturn rac.hash\n}\n\ntype HeaderMatchesChecker struct {\n\theader string\n\tregexp *regexp.Regexp\n\thash string\n}\n\nfunc NewUserAgentChecker(rexStr string) (checker.Impl, error) {\n\treturn NewHeaderMatchesChecker(\"User-Agent\", rexStr)\n}\n\nfunc NewHeaderMatchesChecker(header, rexStr string) (checker.Impl, error) {\n\trex, err := regexp.Compile(strings.TrimSpace(rexStr))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: regex %s failed parse: %w\", ErrMisconfiguration, rexStr, err)\n\t}\n\treturn &HeaderMatchesChecker{strings.TrimSpace(header), rex, internal.FastHash(header + \": \" + rexStr)}, nil\n}\n\nfunc (hmc *HeaderMatchesChecker) Check(r *http.Request) (bool, error) {\n\tif hmc.regexp.MatchString(r.Header.Get(hmc.header)) {\n\t\treturn true, nil\n\t}\n\n\treturn false, nil\n}\n\nfunc (hmc *HeaderMatchesChecker) Hash() string {\n\treturn hmc.hash\n}\n\ntype PathChecker struct {\n\tregexp *regexp.Regexp\n\thash string\n}\n\nfunc NewPathChecker(rexStr string) (checker.Impl, error) {\n\trex, err := regexp.Compile(strings.TrimSpace(rexStr))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: regex %s failed parse: %w\", ErrMisconfiguration, rexStr, err)\n\t}\n\treturn &PathChecker{rex, internal.FastHash(rexStr)}, nil\n}\n\nfunc (pc *PathChecker) Check(r *http.Request) (bool, error) {\n\tif pc.regexp.MatchString(r.URL.Path) {\n\t\treturn true, nil\n\t}\n\n\treturn false, nil\n}\n\nfunc (pc *PathChecker) Hash() string {\n\treturn pc.hash\n}\n\nfunc NewHeaderExistsChecker(key string) checker.Impl {\n\treturn headerExistsChecker{strings.TrimSpace(key)}\n}\n\ntype headerExistsChecker struct {\n\theader string\n}\n\nfunc (hec headerExistsChecker) Check(r *http.Request) (bool, error) {\n\tif r.Header.Get(hec.header) != \"\" {\n\t\treturn true, nil\n\t}\n\n\treturn false, nil\n}\n\nfunc (hec headerExistsChecker) Hash() string {\n\treturn internal.FastHash(hec.header)\n}\n\nfunc NewHeadersChecker(headermap map[string]string) (checker.Impl, error) {\n\tvar result checker.List\n\tvar errs []error\n\n\tfor key, rexStr := range headermap {\n\t\tif rexStr == \".*\" {\n\t\t\tresult = append(result, headerExistsChecker{strings.TrimSpace(key)})\n\t\t\tcontinue\n\t\t}\n\n\t\trex, err := regexp.Compile(strings.TrimSpace(rexStr))\n\t\tif err != nil {\n\t\t\terrs = append(errs, fmt.Errorf(\"while compiling header %s regex %s: %w\", key, rexStr, err))\n\t\t\tcontinue\n\t\t}\n\n\t\tresult = append(result, &HeaderMatchesChecker{key, rex, internal.FastHash(key + \": \" + rexStr)})\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn nil, errors.Join(errs...)\n\t}\n\n\treturn result, nil\n}\n"], ["/anubis/internal/log.go", "package internal\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"log/slog\"\n\t\"net/http\"\n\t\"os\"\n\t\"strings\"\n)\n\nfunc InitSlog(level string) {\n\tvar programLevel slog.Level\n\tif err := (&programLevel).UnmarshalText([]byte(level)); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"invalid log level %s: %v, using info\\n\", level, err)\n\t\tprogramLevel = slog.LevelInfo\n\t}\n\n\tleveler := &slog.LevelVar{}\n\tleveler.Set(programLevel)\n\n\th := slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{\n\t\tAddSource: true,\n\t\tLevel: leveler,\n\t})\n\tslog.SetDefault(slog.New(h))\n}\n\nfunc GetRequestLogger(r *http.Request) *slog.Logger {\n\treturn slog.With(\n\t\t\"user_agent\", r.UserAgent(),\n\t\t\"accept_language\", r.Header.Get(\"Accept-Language\"),\n\t\t\"priority\", r.Header.Get(\"Priority\"),\n\t\t\"x-forwarded-for\",\n\t\tr.Header.Get(\"X-Forwarded-For\"),\n\t\t\"x-real-ip\", r.Header.Get(\"X-Real-Ip\"),\n\t)\n}\n\n// ErrorLogFilter is used to suppress \"context canceled\" logs from the http server when a request is canceled (e.g., when a client disconnects).\ntype ErrorLogFilter struct {\n\tUnwrap *log.Logger\n}\n\nfunc (elf *ErrorLogFilter) Write(p []byte) (n int, err error) {\n\tlogMessage := string(p)\n\tif strings.Contains(logMessage, \"context canceled\") {\n\t\treturn len(p), nil // Suppress the log by doing nothing\n\t}\n\tif elf.Unwrap != nil {\n\t\treturn elf.Unwrap.Writer().Write(p)\n\t}\n\treturn len(p), nil\n}\n\nfunc GetFilteredHTTPLogger() *log.Logger {\n\tstdErrLogger := log.New(os.Stderr, \"\", log.LstdFlags) // essentially what the default logger is.\n\treturn log.New(&ErrorLogFilter{Unwrap: stdErrLogger}, \"\", 0)\n}\n"], ["/anubis/internal/dnsbl/dnsbl.go", "package dnsbl\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net\"\n\t\"strings\"\n)\n\n//go:generate go tool golang.org/x/tools/cmd/stringer -type=DroneBLResponse\n\ntype DroneBLResponse byte\n\nconst (\n\tAllGood DroneBLResponse = 0\n\tIRCDrone DroneBLResponse = 3\n\tBottler DroneBLResponse = 5\n\tUnknownSpambotOrDrone DroneBLResponse = 6\n\tDDOSDrone DroneBLResponse = 7\n\tSOCKSProxy DroneBLResponse = 8\n\tHTTPProxy DroneBLResponse = 9\n\tProxyChain DroneBLResponse = 10\n\tOpenProxy DroneBLResponse = 11\n\tOpenDNSResolver DroneBLResponse = 12\n\tBruteForceAttackers DroneBLResponse = 13\n\tOpenWingateProxy DroneBLResponse = 14\n\tCompromisedRouter DroneBLResponse = 15\n\tAutoRootingWorms DroneBLResponse = 16\n\tAutoDetectedBotIP DroneBLResponse = 17\n\tUnknown DroneBLResponse = 255\n)\n\nfunc Reverse(ip net.IP) string {\n\tif ip.To4() != nil {\n\t\treturn reverse4(ip)\n\t}\n\n\treturn reverse6(ip)\n}\n\nfunc reverse4(ip net.IP) string {\n\tsplitAddress := strings.Split(ip.String(), \".\")\n\n\t// swap first and last octet\n\tsplitAddress[0], splitAddress[3] = splitAddress[3], splitAddress[0]\n\t// swap middle octets\n\tsplitAddress[1], splitAddress[2] = splitAddress[2], splitAddress[1]\n\n\treturn strings.Join(splitAddress, \".\")\n}\n\nfunc reverse6(ip net.IP) string {\n\tipBytes := []byte(ip)\n\tvar sb strings.Builder\n\n\tfor i := len(ipBytes) - 1; i >= 0; i-- {\n\t\t// Split the byte into two nibbles\n\t\thighNibble := ipBytes[i] >> 4\n\t\tlowNibble := ipBytes[i] & 0x0F\n\n\t\t// Append the nibbles in reversed order\n\t\tsb.WriteString(fmt.Sprintf(\"%x.%x.\", lowNibble, highNibble))\n\t}\n\n\treturn sb.String()[:len(sb.String())-1]\n}\n\nfunc Lookup(ipStr string) (DroneBLResponse, error) {\n\tip := net.ParseIP(ipStr)\n\tif ip == nil {\n\t\treturn Unknown, errors.New(\"dnsbl: input is not an IP address\")\n\t}\n\n\trevIP := Reverse(ip) + \".dnsbl.dronebl.org\"\n\n\tips, err := net.LookupIP(revIP)\n\tif err != nil {\n\t\tvar dnserr *net.DNSError\n\t\tif errors.As(err, &dnserr) {\n\t\t\tif dnserr.IsNotFound {\n\t\t\t\treturn AllGood, nil\n\t\t\t}\n\t\t}\n\n\t\treturn Unknown, err\n\t}\n\n\tif len(ips) != 0 {\n\t\tfor _, ip := range ips {\n\t\t\treturn DroneBLResponse(ip.To4()[3]), nil\n\t\t}\n\t}\n\n\treturn UnknownSpambotOrDrone, nil\n}\n"], ["/anubis/lib/policy/expressions/environment.go", "package expressions\n\nimport (\n\t\"math/rand/v2\"\n\t\"strings\"\n\n\t\"github.com/google/cel-go/cel\"\n\t\"github.com/google/cel-go/common/types\"\n\t\"github.com/google/cel-go/common/types/ref\"\n\t\"github.com/google/cel-go/common/types/traits\"\n\t\"github.com/google/cel-go/ext\"\n)\n\n// BotEnvironment creates a new CEL environment, this is the set of\n// variables and functions that are passed into the CEL scope so that\n// Anubis can fail loudly and early when something is invalid instead\n// of blowing up at runtime.\nfunc BotEnvironment() (*cel.Env, error) {\n\treturn New(\n\t\t// Variables exposed to CEL programs:\n\t\tcel.Variable(\"remoteAddress\", cel.StringType),\n\t\tcel.Variable(\"host\", cel.StringType),\n\t\tcel.Variable(\"method\", cel.StringType),\n\t\tcel.Variable(\"userAgent\", cel.StringType),\n\t\tcel.Variable(\"path\", cel.StringType),\n\t\tcel.Variable(\"query\", cel.MapType(cel.StringType, cel.StringType)),\n\t\tcel.Variable(\"headers\", cel.MapType(cel.StringType, cel.StringType)),\n\t\tcel.Variable(\"load_1m\", cel.DoubleType),\n\t\tcel.Variable(\"load_5m\", cel.DoubleType),\n\t\tcel.Variable(\"load_15m\", cel.DoubleType),\n\n\t\t// Bot-specific functions:\n\t\tcel.Function(\"missingHeader\",\n\t\t\tcel.Overload(\"missingHeader_map_string_string_string\",\n\t\t\t\t[]*cel.Type{cel.MapType(cel.StringType, cel.StringType), cel.StringType},\n\t\t\t\tcel.BoolType,\n\t\t\t\tcel.BinaryBinding(func(headers, key ref.Val) ref.Val {\n\t\t\t\t\t// Convert headers to a trait that supports Find\n\t\t\t\t\theadersMap, ok := headers.(traits.Indexer)\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn types.ValOrErr(headers, \"headers is not a map, but is %T\", headers)\n\t\t\t\t\t}\n\n\t\t\t\t\tkeyStr, ok := key.(types.String)\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn types.ValOrErr(key, \"key is not a string, but is %T\", key)\n\t\t\t\t\t}\n\n\t\t\t\t\tval := headersMap.Get(keyStr)\n\t\t\t\t\t// Check if the key is missing by testing for an error\n\t\t\t\t\tif types.IsError(val) {\n\t\t\t\t\t\treturn types.Bool(true) // header is missing\n\t\t\t\t\t}\n\t\t\t\t\treturn types.Bool(false) // header is present\n\t\t\t\t}),\n\t\t\t),\n\t\t),\n\n\t\tcel.Function(\"segments\",\n\t\t\tcel.Overload(\"segments_string_list_string\",\n\t\t\t\t[]*cel.Type{cel.StringType},\n\t\t\t\tcel.ListType(cel.StringType),\n\t\t\t\tcel.UnaryBinding(func(path ref.Val) ref.Val {\n\t\t\t\t\tpathStrType, ok := path.(types.String)\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn types.ValOrErr(path, \"path is not a string, but is %T\", path)\n\t\t\t\t\t}\n\n\t\t\t\t\tpathStr := string(pathStrType)\n\t\t\t\t\tif !strings.HasPrefix(pathStr, \"/\") {\n\t\t\t\t\t\treturn types.ValOrErr(path, \"path does not start with /\")\n\t\t\t\t\t}\n\n\t\t\t\t\tpathList := strings.Split(string(pathStr), \"/\")[1:]\n\n\t\t\t\t\treturn types.NewStringList(types.DefaultTypeAdapter, pathList)\n\t\t\t\t}),\n\t\t\t),\n\t\t),\n\t)\n}\n\n// NewThreshold creates a new CEL environment for threshold checking.\nfunc ThresholdEnvironment() (*cel.Env, error) {\n\treturn New(\n\t\tcel.Variable(\"weight\", cel.IntType),\n\t)\n}\n\nfunc New(opts ...cel.EnvOption) (*cel.Env, error) {\n\targs := []cel.EnvOption{\n\t\text.Strings(\n\t\t\text.StringsLocale(\"en_US\"),\n\t\t\text.StringsValidateFormatCalls(true),\n\t\t),\n\n\t\t// default all timestamps to UTC\n\t\tcel.DefaultUTCTimeZone(true),\n\n\t\t// Functions exposed to all CEL programs:\n\t\tcel.Function(\"randInt\",\n\t\t\tcel.Overload(\"randInt_int\",\n\t\t\t\t[]*cel.Type{cel.IntType},\n\t\t\t\tcel.IntType,\n\t\t\t\tcel.UnaryBinding(func(val ref.Val) ref.Val {\n\t\t\t\t\tn, ok := val.(types.Int)\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn types.ValOrErr(val, \"value is not an integer, but is %T\", val)\n\t\t\t\t\t}\n\n\t\t\t\t\treturn types.Int(rand.IntN(int(n)))\n\t\t\t\t}),\n\t\t\t),\n\t\t),\n\t}\n\n\targs = append(args, opts...)\n\treturn cel.NewEnv(args...)\n}\n\n// Compile takes CEL environment and syntax tree then emits an optimized\n// Program for execution.\nfunc Compile(env *cel.Env, src string) (cel.Program, error) {\n\tintermediate, iss := env.Compile(src)\n\tif iss != nil {\n\t\treturn nil, iss.Err()\n\t}\n\n\tast, iss := env.Check(intermediate)\n\tif iss != nil {\n\t\treturn nil, iss.Err()\n\t}\n\n\treturn env.Program(\n\t\tast,\n\t\tcel.EvalOptions(\n\t\t\t// optimize regular expressions right now instead of on the fly\n\t\t\tcel.OptOptimize,\n\t\t),\n\t)\n}\n"], ["/anubis/lib/challenge/proofofwork/proofofwork.go", "package proofofwork\n\nimport (\n\t\"crypto/subtle\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net/http\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com/TecharoHQ/anubis/internal\"\n\tchall \"github.com/TecharoHQ/anubis/lib/challenge\"\n\t\"github.com/TecharoHQ/anubis/lib/localization\"\n\t\"github.com/TecharoHQ/anubis/web\"\n\t\"github.com/a-h/templ\"\n)\n\nfunc init() {\n\tchall.Register(\"fast\", &Impl{Algorithm: \"fast\"})\n\tchall.Register(\"slow\", &Impl{Algorithm: \"slow\"})\n}\n\ntype Impl struct {\n\tAlgorithm string\n}\n\nfunc (i *Impl) Setup(mux *http.ServeMux) {\n\t/* no implementation required */\n}\n\nfunc (i *Impl) Issue(r *http.Request, lg *slog.Logger, in *chall.IssueInput) (templ.Component, error) {\n\tloc := localization.GetLocalizer(r)\n\tcomponent, err := web.BaseWithChallengeAndOGTags(loc.T(\"making_sure_not_bot\"), web.Index(loc), in.Impressum, in.Challenge.RandomData, in.Rule.Challenge, in.OGTags, loc)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't render page: %w\", err)\n\t}\n\n\treturn component, nil\n}\n\nfunc (i *Impl) Validate(r *http.Request, lg *slog.Logger, in *chall.ValidateInput) error {\n\trule := in.Rule\n\tchallenge := in.Challenge.RandomData\n\n\tnonceStr := r.FormValue(\"nonce\")\n\tif nonceStr == \"\" {\n\t\treturn chall.NewError(\"validate\", \"invalid response\", fmt.Errorf(\"%w nonce\", chall.ErrMissingField))\n\t}\n\n\tnonce, err := strconv.Atoi(nonceStr)\n\tif err != nil {\n\t\treturn chall.NewError(\"validate\", \"invalid response\", fmt.Errorf(\"%w: nonce: %w\", chall.ErrInvalidFormat, err))\n\n\t}\n\n\telapsedTimeStr := r.FormValue(\"elapsedTime\")\n\tif elapsedTimeStr == \"\" {\n\t\treturn chall.NewError(\"validate\", \"invalid response\", fmt.Errorf(\"%w elapsedTime\", chall.ErrMissingField))\n\t}\n\n\telapsedTime, err := strconv.ParseFloat(elapsedTimeStr, 64)\n\tif err != nil {\n\t\treturn chall.NewError(\"validate\", \"invalid response\", fmt.Errorf(\"%w: elapsedTime: %w\", chall.ErrInvalidFormat, err))\n\t}\n\n\tresponse := r.FormValue(\"response\")\n\tif response == \"\" {\n\t\treturn chall.NewError(\"validate\", \"invalid response\", fmt.Errorf(\"%w response\", chall.ErrMissingField))\n\t}\n\n\tcalcString := fmt.Sprintf(\"%s%d\", challenge, nonce)\n\tcalculated := internal.SHA256sum(calcString)\n\n\tif subtle.ConstantTimeCompare([]byte(response), []byte(calculated)) != 1 {\n\t\treturn chall.NewError(\"validate\", \"invalid response\", fmt.Errorf(\"%w: wanted response %s but got %s\", chall.ErrFailed, calculated, response))\n\t}\n\n\t// compare the leading zeroes\n\tif !strings.HasPrefix(response, strings.Repeat(\"0\", rule.Challenge.Difficulty)) {\n\t\treturn chall.NewError(\"validate\", \"invalid response\", fmt.Errorf(\"%w: wanted %d leading zeros but got %s\", chall.ErrFailed, rule.Challenge.Difficulty, response))\n\t}\n\n\tlg.Debug(\"challenge took\", \"elapsedTime\", elapsedTime)\n\tchall.TimeTaken.WithLabelValues(i.Algorithm).Observe(elapsedTime)\n\n\treturn nil\n}\n"], ["/anubis/utils/cmd/backoff-retry/main.go", "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"os\"\n\t\"os/exec\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar (\n\tstartWait = flag.Duration(\"start-wait\", 250*time.Millisecond, \"amount of time to start with exponential backoff\")\n\ttryCount = flag.Int(\"try-count\", 5, \"number of retries\")\n)\n\nfunc main() {\n\tflag.Parse()\n\n\tcmdStr := strings.Join(flag.Args(), \" \")\n\twait := *startWait\n\n\tfor i := range make([]struct{}, *tryCount) {\n\t\tslog.Info(\"executing\", \"try\", i+1, \"wait\", wait, \"cmd\", cmdStr)\n\n\t\tcmd := exec.Command(\"sh\", \"-c\", cmdStr)\n\t\tcmd.Stdin = nil\n\t\tcmd.Stdout = os.Stdout\n\t\tcmd.Stderr = os.Stderr\n\n\t\tif err := cmd.Run(); err != nil {\n\t\t\ttime.Sleep(wait)\n\t\t\twait = wait * 2\n\t\t} else {\n\t\t\tos.Exit(0)\n\t\t}\n\t}\n\n\tfmt.Printf(\"giving up after %d tries\\n\", *tryCount)\n\tos.Exit(1)\n}\n"], ["/anubis/lib/store/bbolt/factory.go", "package bbolt\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n\t\"go.etcd.io/bbolt\"\n)\n\nvar (\n\tErrMissingPath = errors.New(\"bbolt: path is missing from config\")\n\tErrCantWriteToPath = errors.New(\"bbolt: can't write to path\")\n)\n\nfunc init() {\n\tstore.Register(\"bbolt\", Factory{})\n}\n\n// Factory builds new instances of the bbolt storage backend according to\n// configuration passed via a json.RawMessage.\ntype Factory struct{}\n\n// Build parses and validates the bbolt storage backend Config and creates\n// a new instance of it.\nfunc (Factory) Build(ctx context.Context, data json.RawMessage) (store.Interface, error) {\n\tvar config Config\n\tif err := json.Unmarshal([]byte(data), &config); err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\tif err := config.Valid(); err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\tbdb, err := bbolt.Open(config.Path, 0600, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't open bbolt database %s: %w\", config.Path, err)\n\t}\n\n\tresult := &Store{\n\t\tbdb: bdb,\n\t}\n\n\tgo result.cleanupThread(ctx)\n\n\treturn result, nil\n}\n\n// Valid parses and validates the bbolt store Config or returns\n// an error.\nfunc (Factory) Valid(data json.RawMessage) error {\n\tvar config Config\n\tif err := json.Unmarshal([]byte(data), &config); err != nil {\n\t\treturn fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\tif err := config.Valid(); err != nil {\n\t\treturn fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\treturn nil\n}\n\n// Config is the bbolt storage backend configuration.\ntype Config struct {\n\t// Path is the filesystem path of the database. The folder must be writable to Anubis.\n\tPath string `json:\"path\"`\n}\n\n// Valid validates the configuration including checking if its containing folder is writable.\nfunc (c Config) Valid() error {\n\tvar errs []error\n\n\tif c.Path == \"\" {\n\t\terrs = append(errs, ErrMissingPath)\n\t} else {\n\t\tdir := filepath.Dir(c.Path)\n\t\tif err := os.WriteFile(filepath.Join(dir, \".test-file\"), []byte(\"\"), 0600); err != nil {\n\t\t\terrs = append(errs, ErrCantWriteToPath)\n\t\t}\n\t\tos.Remove(filepath.Join(dir, \".test-file\"))\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn errors.Join(errs...)\n\t}\n\n\treturn nil\n}\n"], ["/anubis/lib/policy/config/opengraph.go", "package config\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"time\"\n)\n\nvar (\n\tErrInvalidOpenGraphConfig = errors.New(\"config.OpenGraph: invalid OpenGraph configuration\")\n\tErrOpenGraphTTLDoesNotParse = errors.New(\"config.OpenGraph: ttl does not parse as a Duration, see https://pkg.go.dev/time#ParseDuration (formatted like 5m -> 5 minutes, 2h -> 2 hours, etc)\")\n\tErrOpenGraphMissingProperty = errors.New(\"config.OpenGraph: default opengraph tags missing a property\")\n)\n\ntype openGraphFileConfig struct {\n\tEnabled bool `json:\"enabled\" yaml:\"enabled\"`\n\tConsiderHost bool `json:\"considerHost\" yaml:\"enabled\"`\n\tTimeToLive string `json:\"ttl\" yaml:\"ttl\"`\n\tOverride map[string]string `json:\"override,omitempty\" yaml:\"override,omitempty\"`\n}\n\ntype OpenGraph struct {\n\tEnabled bool `json:\"enabled\" yaml:\"enabled\"`\n\tConsiderHost bool `json:\"considerHost\" yaml:\"enabled\"`\n\tOverride map[string]string `json:\"override,omitempty\" yaml:\"override,omitempty\"`\n\tTimeToLive time.Duration `json:\"ttl\" yaml:\"ttl\"`\n}\n\nfunc (og *openGraphFileConfig) Valid() error {\n\tvar errs []error\n\n\tif _, err := time.ParseDuration(og.TimeToLive); err != nil {\n\t\terrs = append(errs, fmt.Errorf(\"%w: ParseDuration(%q) returned: %w\", ErrOpenGraphTTLDoesNotParse, og.TimeToLive, err))\n\t}\n\n\tif len(og.Override) != 0 {\n\t\tfor _, tag := range []string{\n\t\t\t\"og:title\",\n\t\t} {\n\t\t\tif _, ok := og.Override[tag]; !ok {\n\t\t\t\terrs = append(errs, fmt.Errorf(\"%w: %s\", ErrOpenGraphMissingProperty, tag))\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn errors.Join(ErrInvalidOpenGraphConfig, errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n"], ["/anubis/lib/policy/celchecker.go", "package policy\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/TecharoHQ/anubis/internal\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/expressions\"\n\t\"github.com/google/cel-go/cel\"\n\t\"github.com/google/cel-go/common/types\"\n)\n\ntype CELChecker struct {\n\tprogram cel.Program\n\tsrc string\n}\n\nfunc NewCELChecker(cfg *config.ExpressionOrList) (*CELChecker, error) {\n\tenv, err := expressions.BotEnvironment()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tprogram, err := expressions.Compile(env, cfg.String())\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't compile CEL program: %w\", err)\n\t}\n\n\treturn &CELChecker{\n\t\tsrc: cfg.String(),\n\t\tprogram: program,\n\t}, nil\n}\n\nfunc (cc *CELChecker) Hash() string {\n\treturn internal.FastHash(cc.src)\n}\n\nfunc (cc *CELChecker) Check(r *http.Request) (bool, error) {\n\tresult, _, err := cc.program.ContextEval(r.Context(), &CELRequest{r})\n\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tif val, ok := result.(types.Bool); ok {\n\t\treturn bool(val), nil\n\t}\n\n\treturn false, nil\n}\n\ntype CELRequest struct {\n\t*http.Request\n}\n\nfunc (cr *CELRequest) Parent() cel.Activation { return nil }\n\nfunc (cr *CELRequest) ResolveName(name string) (any, bool) {\n\tswitch name {\n\tcase \"remoteAddress\":\n\t\treturn cr.Header.Get(\"X-Real-Ip\"), true\n\tcase \"host\":\n\t\treturn cr.Host, true\n\tcase \"method\":\n\t\treturn cr.Method, true\n\tcase \"userAgent\":\n\t\treturn cr.UserAgent(), true\n\tcase \"path\":\n\t\treturn cr.URL.Path, true\n\tcase \"query\":\n\t\treturn expressions.URLValues{Values: cr.URL.Query()}, true\n\tcase \"headers\":\n\t\treturn expressions.HTTPHeaders{Header: cr.Header}, true\n\tcase \"load_1m\":\n\t\treturn expressions.Load1(), true\n\tcase \"load_5m\":\n\t\treturn expressions.Load5(), true\n\tcase \"load_15m\":\n\t\treturn expressions.Load15(), true\n\tdefault:\n\t\treturn nil, false\n\t}\n}\n"], ["/anubis/lib/policy/config/threshold.go", "package config\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com/TecharoHQ/anubis\"\n)\n\nvar (\n\tErrNoThresholdRulesDefined = errors.New(\"config: no thresholds defined\")\n\tErrThresholdMustHaveName = errors.New(\"config.Threshold: must set name\")\n\tErrThresholdMustHaveExpression = errors.New(\"config.Threshold: must set expression\")\n\tErrThresholdChallengeMustHaveChallenge = errors.New(\"config.Threshold: a threshold with the CHALLENGE action must have challenge set\")\n\tErrThresholdCannotHaveWeighAction = errors.New(\"config.Threshold: a threshold cannot have the WEIGH action\")\n\n\tDefaultThresholds = []Threshold{\n\t\t{\n\t\t\tName: \"legacy-anubis-behaviour\",\n\t\t\tExpression: &ExpressionOrList{\n\t\t\t\tExpression: \"weight > 0\",\n\t\t\t},\n\t\t\tAction: RuleChallenge,\n\t\t\tChallenge: &ChallengeRules{\n\t\t\t\tAlgorithm: \"fast\",\n\t\t\t\tDifficulty: anubis.DefaultDifficulty,\n\t\t\t\tReportAs: anubis.DefaultDifficulty,\n\t\t\t},\n\t\t},\n\t}\n)\n\ntype Threshold struct {\n\tName string `json:\"name\" yaml:\"name\"`\n\tExpression *ExpressionOrList `json:\"expression\" yaml:\"expression\"`\n\tAction Rule `json:\"action\" yaml:\"action\"`\n\tChallenge *ChallengeRules `json:\"challenge\" yaml:\"challenge\"`\n}\n\nfunc (t Threshold) Valid() error {\n\tvar errs []error\n\n\tif len(t.Name) == 0 {\n\t\terrs = append(errs, ErrThresholdMustHaveName)\n\t}\n\n\tif t.Expression == nil {\n\t\terrs = append(errs, ErrThresholdMustHaveExpression)\n\t}\n\n\tif t.Expression != nil {\n\t\tif err := t.Expression.Valid(); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\tif err := t.Action.Valid(); err != nil {\n\t\terrs = append(errs, err)\n\t}\n\n\tif t.Action == RuleWeigh {\n\t\terrs = append(errs, ErrThresholdCannotHaveWeighAction)\n\t}\n\n\tif t.Action == RuleChallenge && t.Challenge == nil {\n\t\terrs = append(errs, ErrThresholdChallengeMustHaveChallenge)\n\t}\n\n\tif t.Challenge != nil {\n\t\tif err := t.Challenge.Valid(); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"config: threshold entry for %q is not valid:\\n%w\", t.Name, errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n"], ["/anubis/web/index_templ.go", "// Code generated by templ - DO NOT EDIT.\n\n// templ: version: v0.3.906\npackage web\n\n//lint:file-ignore SA4006 This context is only used if a nested component is present.\n\nimport \"github.com/a-h/templ\"\nimport templruntime \"github.com/a-h/templ/runtime\"\n\nimport (\n\t\"fmt\"\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/TecharoHQ/anubis/lib/localization\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/xess\"\n)\n\nfunc base(title string, body templ.Component, impressum *config.Impressum, challenge any, ogTags map[string]string, localizer *localization.SimpleLocalizer) templ.Component {\n\treturn templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {\n\t\ttempl_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context\n\t\tif templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {\n\t\t\treturn templ_7745c5c3_CtxErr\n\t\t}\n\t\ttempl_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)\n\t\tif !templ_7745c5c3_IsBuffer {\n\t\t\tdefer func() {\n\t\t\t\ttempl_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)\n\t\t\t\tif templ_7745c5c3_Err == nil {\n\t\t\t\t\ttempl_7745c5c3_Err = templ_7745c5c3_BufErr\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\tctx = templ.InitializeContext(ctx)\n\t\ttempl_7745c5c3_Var1 := templ.GetChildren(ctx)\n\t\tif templ_7745c5c3_Var1 == nil {\n\t\t\ttempl_7745c5c3_Var1 = templ.NopComponent\n\t\t}\n\t\tctx = templ.ClearChildren(ctx)\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, \"\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var3 string\n\t\ttempl_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(title)\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 15, Col: 17}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 3, \"\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tfor key, value := range ogTags {\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, \"\")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, \"\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templ.JSONScript(\"anubis_version\", anubis.Version).Render(ctx, templ_7745c5c3_Buffer)\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tif challenge != nil {\n\t\t\ttempl_7745c5c3_Err = templ.JSONScript(\"anubis_challenge\", challenge).Render(ctx, templ_7745c5c3_Buffer)\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t}\n\t\ttempl_7745c5c3_Err = templ.JSONScript(\"anubis_base_prefix\", anubis.BasePrefix).Render(ctx, templ_7745c5c3_Buffer)\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var7 string\n\t\ttempl_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(title)\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 68, Col: 47}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 10, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = body.Render(ctx, templ_7745c5c3_Buffer)\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var8 string\n\t\ttempl_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"protected_by\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 73, Col: 36}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, \" Anubis \")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var9 string\n\t\ttempl_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"protected_from\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 73, Col: 127}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, \" Techaro. \")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var10 string\n\t\ttempl_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"made_with\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 75, Col: 40}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 14, \".

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var11 string\n\t\ttempl_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"mascot_design\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 77, Col: 39}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, \" \")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var12 string\n\t\ttempl_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"celphase\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 77, Col: 123}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, \".

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tif impressum != nil {\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, \"

\")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\ttempl_7745c5c3_Err = templ.Raw(impressum.Footer).Render(ctx, templ_7745c5c3_Buffer)\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 18, \"-- Imprint

\")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 20, \"
\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\treturn nil\n\t})\n}\n\nfunc index(localizer *localization.SimpleLocalizer) templ.Component {\n\treturn templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {\n\t\ttempl_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context\n\t\tif templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {\n\t\t\treturn templ_7745c5c3_CtxErr\n\t\t}\n\t\ttempl_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)\n\t\tif !templ_7745c5c3_IsBuffer {\n\t\t\tdefer func() {\n\t\t\t\ttempl_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)\n\t\t\t\tif templ_7745c5c3_Err == nil {\n\t\t\t\t\ttempl_7745c5c3_Err = templ_7745c5c3_BufErr\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\tctx = templ.InitializeContext(ctx)\n\t\ttempl_7745c5c3_Var14 := templ.GetChildren(ctx)\n\t\tif templ_7745c5c3_Var14 == nil {\n\t\t\ttempl_7745c5c3_Var14 = templ.NopComponent\n\t\t}\n\t\tctx = templ.ClearChildren(ctx)\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 21, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var17 string\n\t\ttempl_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"loading\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 95, Col: 41}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var17))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 24, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var19 string\n\t\ttempl_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"why_am_i_seeing\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 101, Col: 44}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var19))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 26, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var20 string\n\t\ttempl_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"ai_companies_explanation\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 103, Col: 45}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var20))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 27, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var21 string\n\t\ttempl_7745c5c3_Var21, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"anubis_compromise\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 106, Col: 38}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var21))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var22 string\n\t\ttempl_7745c5c3_Var22, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"hack_purpose\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 109, Col: 33}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var22))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var23 string\n\t\ttempl_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"jshelter_note\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 112, Col: 34}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var23))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 30, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var24 string\n\t\ttempl_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"version_info\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 114, Col: 35}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var24))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 31, \" \")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var25 string\n\t\ttempl_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinStringErrs(anubis.Version)\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 114, Col: 60}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var25))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 32, \".

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\treturn nil\n\t})\n}\n\nfunc errorPage(message, mail string, localizer *localization.SimpleLocalizer) templ.Component {\n\treturn templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {\n\t\ttempl_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context\n\t\tif templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {\n\t\t\treturn templ_7745c5c3_CtxErr\n\t\t}\n\t\ttempl_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)\n\t\tif !templ_7745c5c3_IsBuffer {\n\t\t\tdefer func() {\n\t\t\t\ttempl_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)\n\t\t\t\tif templ_7745c5c3_Err == nil {\n\t\t\t\t\ttempl_7745c5c3_Err = templ_7745c5c3_BufErr\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\tctx = templ.InitializeContext(ctx)\n\t\ttempl_7745c5c3_Var27 := templ.GetChildren(ctx)\n\t\tif templ_7745c5c3_Var27 == nil {\n\t\t\ttempl_7745c5c3_Var27 = templ.NopComponent\n\t\t}\n\t\tctx = templ.ClearChildren(ctx)\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 34, \"
\\\"Sad

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var29 string\n\t\ttempl_7745c5c3_Var29, templ_7745c5c3_Err = templ.JoinStringErrs(message)\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 128, Col: 14}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var29))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 36, \".

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tif mail != \"\" {\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 37, \"

\")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\tvar templ_7745c5c3_Var30 string\n\t\t\ttempl_7745c5c3_Var30, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"go_home\"))\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 131, Col: 40}\n\t\t\t}\n\t\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var30))\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 38, \" \")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\tvar templ_7745c5c3_Var31 string\n\t\t\ttempl_7745c5c3_Var31, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"contact_webmaster\"))\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 131, Col: 81}\n\t\t\t}\n\t\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var31))\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 39, \" \")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\tvar templ_7745c5c3_Var33 string\n\t\t\ttempl_7745c5c3_Var33, templ_7745c5c3_Err = templ.JoinStringErrs(mail)\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 133, Col: 11}\n\t\t\t}\n\t\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var33))\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 41, \"

\")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t} else {\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 42, \"

\")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\tvar templ_7745c5c3_Var34 string\n\t\t\ttempl_7745c5c3_Var34, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"go_home\"))\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 137, Col: 42}\n\t\t\t}\n\t\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var34))\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 43, \"

\")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 44, \"
\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\treturn nil\n\t})\n}\n\nfunc StaticHappy(localizer *localization.SimpleLocalizer) templ.Component {\n\treturn templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {\n\t\ttempl_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context\n\t\tif templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {\n\t\t\treturn templ_7745c5c3_CtxErr\n\t\t}\n\t\ttempl_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)\n\t\tif !templ_7745c5c3_IsBuffer {\n\t\t\tdefer func() {\n\t\t\t\ttempl_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)\n\t\t\t\tif templ_7745c5c3_Err == nil {\n\t\t\t\t\ttempl_7745c5c3_Err = templ_7745c5c3_BufErr\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\tctx = templ.InitializeContext(ctx)\n\t\ttempl_7745c5c3_Var35 := templ.GetChildren(ctx)\n\t\tif templ_7745c5c3_Var35 == nil {\n\t\t\ttempl_7745c5c3_Var35 = templ.NopComponent\n\t\t}\n\t\tctx = templ.ClearChildren(ctx)\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 45, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var37 string\n\t\ttempl_7745c5c3_Var37, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"static_check_endpoint\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 150, Col: 43}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var37))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 47, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\treturn nil\n\t})\n}\n\nfunc bench(localizer *localization.SimpleLocalizer) templ.Component {\n\treturn templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {\n\t\ttempl_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context\n\t\tif templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {\n\t\t\treturn templ_7745c5c3_CtxErr\n\t\t}\n\t\ttempl_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)\n\t\tif !templ_7745c5c3_IsBuffer {\n\t\t\tdefer func() {\n\t\t\t\ttempl_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)\n\t\t\t\tif templ_7745c5c3_Err == nil {\n\t\t\t\t\ttempl_7745c5c3_Err = templ_7745c5c3_BufErr\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\tctx = templ.InitializeContext(ctx)\n\t\ttempl_7745c5c3_Var38 := templ.GetChildren(ctx)\n\t\tif templ_7745c5c3_Var38 == nil {\n\t\t\ttempl_7745c5c3_Var38 = templ.NopComponent\n\t\t}\n\t\tctx = templ.ClearChildren(ctx)\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 48, \"
\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var39 string\n\t\ttempl_7745c5c3_Var39, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"time\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 161, Col: 51}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var39))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 49, \"\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var40 string\n\t\ttempl_7745c5c3_Var40, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"iters\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 162, Col: 50}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var40))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 50, \"
\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var41 string\n\t\ttempl_7745c5c3_Var41, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"time_a\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 165, Col: 53}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var41))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 51, \"\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var42 string\n\t\ttempl_7745c5c3_Var42, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"iters_a\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 166, Col: 52}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var42))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 52, \"\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var43 string\n\t\ttempl_7745c5c3_Var43, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"time_b\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 167, Col: 53}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var43))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 53, \"\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var44 string\n\t\ttempl_7745c5c3_Var44, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"iters_b\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 168, Col: 52}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var44))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 54, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var46 string\n\t\ttempl_7745c5c3_Var46, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"loading\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 178, Col: 66}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var46))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 56, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\treturn nil\n\t})\n}\n\nvar _ = templruntime.GeneratedTemplate\n"], ["/anubis/lib/policy/config/asn.go", "package config\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\nvar (\n\tErrPrivateASN = errors.New(\"bot.ASNs: you have specified a private use ASN\")\n)\n\ntype ASNs struct {\n\tMatch []uint32 `json:\"match\"`\n}\n\nfunc (a *ASNs) Valid() error {\n\tvar errs []error\n\n\tfor _, asn := range a.Match {\n\t\tif isPrivateASN(asn) {\n\t\t\terrs = append(errs, fmt.Errorf(\"%w: %d is private (see RFC 6996)\", ErrPrivateASN, asn))\n\t\t}\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"bot.ASNs: invalid ASN settings: %w\", errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n\n// isPrivateASN checks if an ASN is in the private use area.\n//\n// Based on RFC 6996 and IANA allocations.\nfunc isPrivateASN(asn uint32) bool {\n\tswitch {\n\tcase asn >= 64512 && asn <= 65534:\n\t\treturn true\n\tcase asn >= 4200000000 && asn <= 4294967294:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n"], ["/anubis/lib/thoth/thothmock/iptoasn.go", "package thothmock\n\nimport (\n\t\"context\"\n\t\"net/netip\"\n\n\tiptoasnv1 \"github.com/TecharoHQ/thoth-proto/gen/techaro/thoth/iptoasn/v1\"\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/status\"\n)\n\nfunc MockIpToASNService() *IpToASNService {\n\tresponses := map[string]*iptoasnv1.LookupResponse{\n\t\t\"127.0.0.1\": {Announced: false},\n\t\t\"::1\": {Announced: false},\n\t\t\"10.10.10.10\": {\n\t\t\tAnnounced: true,\n\t\t\tAsNumber: 13335,\n\t\t\tCidr: []string{\"1.1.1.0/24\"},\n\t\t\tCountryCode: \"US\",\n\t\t\tDescription: \"Cloudflare\",\n\t\t},\n\t\t\"2.2.2.2\": {\n\t\t\tAnnounced: true,\n\t\t\tAsNumber: 420,\n\t\t\tCidr: []string{\"2.2.2.0/24\"},\n\t\t\tCountryCode: \"CA\",\n\t\t\tDescription: \"test canada\",\n\t\t},\n\t\t\"1.1.1.1\": {\n\t\t\tAnnounced: true,\n\t\t\tAsNumber: 13335,\n\t\t\tCidr: []string{\"1.1.1.0/24\"},\n\t\t\tCountryCode: \"US\",\n\t\t\tDescription: \"Cloudflare\",\n\t\t},\n\t}\n\n\treturn &IpToASNService{Responses: responses}\n}\n\ntype IpToASNService struct {\n\tiptoasnv1.UnimplementedIpToASNServiceServer\n\tResponses map[string]*iptoasnv1.LookupResponse\n}\n\nfunc (ip2asn *IpToASNService) Lookup(ctx context.Context, lr *iptoasnv1.LookupRequest, opts ...grpc.CallOption) (*iptoasnv1.LookupResponse, error) {\n\tif _, err := netip.ParseAddr(lr.GetIpAddress()); err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, ok := ip2asn.Responses[lr.GetIpAddress()]\n\tif !ok {\n\t\treturn nil, status.Error(codes.NotFound, \"IP address not found in mock\")\n\t}\n\n\treturn resp, nil\n}\n"], ["/anubis/internal/ogtags/cache.go", "package ogtags\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"log/slog\"\n\t\"net/url\"\n\t\"syscall\"\n)\n\n// GetOGTags is the main function that retrieves Open Graph tags for a URL\nfunc (c *OGTagCache) GetOGTags(ctx context.Context, url *url.URL, originalHost string) (map[string]string, error) {\n\tif url == nil {\n\t\treturn nil, errors.New(\"nil URL provided, cannot fetch OG tags\")\n\t}\n\n\tif len(c.ogOverride) != 0 {\n\t\treturn c.ogOverride, nil\n\t}\n\n\ttarget := c.getTarget(url)\n\tcacheKey := c.generateCacheKey(target, originalHost)\n\n\t// Check cache first\n\tif cachedTags := c.checkCache(ctx, cacheKey); cachedTags != nil {\n\t\treturn cachedTags, nil\n\t}\n\n\t// Fetch HTML content, passing the original host\n\tdoc, err := c.fetchHTMLDocumentWithCache(ctx, target, originalHost, cacheKey)\n\tif errors.Is(err, syscall.ECONNREFUSED) {\n\t\tslog.Debug(\"Connection refused, returning empty tags\")\n\t\treturn nil, nil\n\t} else if errors.Is(err, ErrOgHandled) {\n\t\t// Error was handled in fetchHTMLDocument, return empty tags\n\t\treturn nil, nil\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Extract OG tags\n\togTags := c.extractOGTags(doc)\n\n\t// Store in cache\n\tc.cache.Set(ctx, cacheKey, ogTags, c.ogTimeToLive)\n\n\treturn ogTags, nil\n}\n\nfunc (c *OGTagCache) generateCacheKey(target string, originalHost string) string {\n\tvar cacheKey string\n\n\tif c.ogCacheConsiderHost {\n\t\tcacheKey = target + \"|\" + originalHost\n\t} else {\n\t\tcacheKey = target\n\t}\n\treturn cacheKey\n}\n\n// checkCache checks if we have the tags cached and returns them if so\nfunc (c *OGTagCache) checkCache(ctx context.Context, cacheKey string) map[string]string {\n\tif cachedTags, err := c.cache.Get(ctx, cacheKey); err == nil {\n\t\tslog.Debug(\"cache hit\", \"tags\", cachedTags)\n\t\treturn cachedTags\n\t}\n\tslog.Debug(\"cache miss\", \"url\", cacheKey)\n\treturn nil\n}\n"], ["/anubis/anubis.go", "// Package anubis contains the version number of Anubis.\npackage anubis\n\nimport \"time\"\n\n// Version is the current version of Anubis.\n//\n// This variable is set at build time using the -X linker flag. If not set,\n// it defaults to \"devel\".\nvar Version = \"devel\"\n\n// CookieName is the name of the cookie that Anubis uses in order to validate\n// access.\nvar CookieName = \"techaro.lol-anubis-auth\"\n\n// TestCookieName is the name of the cookie that Anubis uses in order to check\n// if cookies are enabled on the client's browser.\nvar TestCookieName = \"techaro.lol-anubis-cookie-verification\"\n\n// CookieDefaultExpirationTime is the amount of time before the cookie/JWT expires.\nconst CookieDefaultExpirationTime = 7 * 24 * time.Hour\n\n// BasePrefix is a global prefix for all Anubis endpoints. Can be emptied to remove the prefix entirely.\nvar BasePrefix = \"\"\n\n// StaticPath is the location where all static Anubis assets are located.\nconst StaticPath = \"/.within.website/x/cmd/anubis/\"\n\n// APIPrefix is the location where all Anubis API endpoints are located.\nconst APIPrefix = \"/.within.website/x/cmd/anubis/api/\"\n\n// DefaultDifficulty is the default \"difficulty\" (number of leading zeroes)\n// that must be met by the client in order to pass the challenge.\nconst DefaultDifficulty = 4\n\n// ForcedLanguage is the language being used instead of the one of the request's Accept-Language header\n// if being set.\nvar ForcedLanguage = \"\"\n"], ["/anubis/lib/challenge/metarefresh/metarefresh_templ.go", "// Code generated by templ - DO NOT EDIT.\n\n// templ: version: v0.3.906\npackage metarefresh\n\n//lint:file-ignore SA4006 This context is only used if a nested component is present.\n\nimport \"github.com/a-h/templ\"\nimport templruntime \"github.com/a-h/templ/runtime\"\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/TecharoHQ/anubis/lib/localization\"\n)\n\nfunc page(redir string, difficulty int, loc *localization.SimpleLocalizer) templ.Component {\n\treturn templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {\n\t\ttempl_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context\n\t\tif templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {\n\t\t\treturn templ_7745c5c3_CtxErr\n\t\t}\n\t\ttempl_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)\n\t\tif !templ_7745c5c3_IsBuffer {\n\t\t\tdefer func() {\n\t\t\t\ttempl_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)\n\t\t\t\tif templ_7745c5c3_Err == nil {\n\t\t\t\t\ttempl_7745c5c3_Err = templ_7745c5c3_BufErr\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\tctx = templ.InitializeContext(ctx)\n\t\ttempl_7745c5c3_Var1 := templ.GetChildren(ctx)\n\t\tif templ_7745c5c3_Var1 == nil {\n\t\t\ttempl_7745c5c3_Var1 = templ.NopComponent\n\t\t}\n\t\tctx = templ.ClearChildren(ctx)\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var4 string\n\t\ttempl_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(loc.T(\"loading\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `metarefresh.templ`, Line: 14, Col: 35}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var5 string\n\t\ttempl_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(loc.T(\"connection_security\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `metarefresh.templ`, Line: 15, Col: 35}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\treturn nil\n\t})\n}\n\nvar _ = templruntime.GeneratedTemplate\n"], ["/anubis/lib/challenge/metarefresh/metarefresh.go", "package metarefresh\n\nimport (\n\t\"crypto/subtle\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net/http\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/TecharoHQ/anubis/lib/challenge\"\n\t\"github.com/TecharoHQ/anubis/lib/localization\"\n\t\"github.com/TecharoHQ/anubis/web\"\n\t\"github.com/a-h/templ\"\n)\n\n//go:generate go tool github.com/a-h/templ/cmd/templ generate\n\nfunc init() {\n\tchallenge.Register(\"metarefresh\", &Impl{})\n}\n\ntype Impl struct{}\n\nfunc (i *Impl) Setup(mux *http.ServeMux) {}\n\nfunc (i *Impl) Issue(r *http.Request, lg *slog.Logger, in *challenge.IssueInput) (templ.Component, error) {\n\tu, err := r.URL.Parse(anubis.BasePrefix + \"/.within.website/x/cmd/anubis/api/pass-challenge\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't render page: %w\", err)\n\t}\n\n\tq := u.Query()\n\tq.Set(\"redir\", r.URL.String())\n\tq.Set(\"challenge\", in.Challenge.RandomData)\n\tu.RawQuery = q.Encode()\n\n\tloc := localization.GetLocalizer(r)\n\tcomponent, err := web.BaseWithChallengeAndOGTags(loc.T(\"making_sure_not_bot\"), page(u.String(), in.Rule.Challenge.Difficulty, loc), in.Impressum, in.Challenge.RandomData, in.Rule.Challenge, in.OGTags, loc)\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't render page: %w\", err)\n\t}\n\n\treturn component, nil\n}\n\nfunc (i *Impl) Validate(r *http.Request, lg *slog.Logger, in *challenge.ValidateInput) error {\n\tgotChallenge := r.FormValue(\"challenge\")\n\n\tif subtle.ConstantTimeCompare([]byte(in.Challenge.RandomData), []byte(gotChallenge)) != 1 {\n\t\treturn challenge.NewError(\"validate\", \"invalid response\", fmt.Errorf(\"%w: wanted response %s but got %s\", challenge.ErrFailed, in.Challenge.RandomData, gotChallenge))\n\t}\n\n\treturn nil\n}\n"], ["/anubis/lib/store/interface.go", "package store\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"time\"\n)\n\nvar (\n\t// ErrNotFound is returned when the store implementation cannot find the value\n\t// for a given key.\n\tErrNotFound = errors.New(\"store: key not found\")\n\n\t// ErrCantDecode is returned when a store adaptor cannot decode the store format\n\t// to a value used by the code.\n\tErrCantDecode = errors.New(\"store: can't decode value\")\n\n\t// ErrCantEncode is returned when a store adaptor cannot encode the value into\n\t// the format that the store uses.\n\tErrCantEncode = errors.New(\"store: can't encode value\")\n\n\t// ErrBadConfig is returned when a store adaptor's configuration is invalid.\n\tErrBadConfig = errors.New(\"store: configuration is invalid\")\n)\n\n// Interface defines the calls that Anubis uses for storage in a local or remote\n// datastore. This can be implemented with an in-memory, on-disk, or in-database\n// storage backend.\ntype Interface interface {\n\t// Delete removes a value from the store by key.\n\tDelete(ctx context.Context, key string) error\n\n\t// Get returns the value of a key assuming that value exists and has not expired.\n\tGet(ctx context.Context, key string) ([]byte, error)\n\n\t// Set puts a value into the store that expires according to its expiry.\n\tSet(ctx context.Context, key string, value []byte, expiry time.Duration) error\n}\n\nfunc z[T any]() T { return *new(T) }\n\ntype JSON[T any] struct {\n\tUnderlying Interface\n\tPrefix string\n}\n\nfunc (j *JSON[T]) Delete(ctx context.Context, key string) error {\n\tif j.Prefix != \"\" {\n\t\tkey = j.Prefix + key\n\t}\n\n\treturn j.Underlying.Delete(ctx, key)\n}\n\nfunc (j *JSON[T]) Get(ctx context.Context, key string) (T, error) {\n\tif j.Prefix != \"\" {\n\t\tkey = j.Prefix + key\n\t}\n\n\tdata, err := j.Underlying.Get(ctx, key)\n\tif err != nil {\n\t\treturn z[T](), err\n\t}\n\n\tvar result T\n\tif err := json.Unmarshal(data, &result); err != nil {\n\t\treturn z[T](), fmt.Errorf(\"%w: %w\", ErrCantDecode, err)\n\t}\n\n\treturn result, nil\n}\n\nfunc (j *JSON[T]) Set(ctx context.Context, key string, value T, expiry time.Duration) error {\n\tif j.Prefix != \"\" {\n\t\tkey = j.Prefix + key\n\t}\n\n\tdata, err := json.Marshal(value)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%w: %w\", ErrCantEncode, err)\n\t}\n\n\tif err := j.Underlying.Set(ctx, key, data, expiry); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n"], ["/anubis/lib/store/valkey/valkey.go", "package valkey\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n\tvalkey \"github.com/redis/go-redis/v9\"\n)\n\ntype Store struct {\n\trdb *valkey.Client\n}\n\nfunc (s *Store) Delete(ctx context.Context, key string) error {\n\tn, err := s.rdb.Del(ctx, key).Result()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"can't delete from valkey: %w\", err)\n\t}\n\n\tswitch n {\n\tcase 0:\n\t\treturn fmt.Errorf(\"%w: %d key(s) deleted\", store.ErrNotFound, n)\n\tdefault:\n\t\treturn nil\n\t}\n}\n\nfunc (s *Store) Get(ctx context.Context, key string) ([]byte, error) {\n\tresult, err := s.rdb.Get(ctx, key).Result()\n\tif err != nil {\n\t\tif valkey.HasErrorPrefix(err, \"redis: nil\") {\n\t\t\treturn nil, fmt.Errorf(\"%w: %w\", store.ErrNotFound, err)\n\t\t}\n\n\t\treturn nil, fmt.Errorf(\"can't fetch from valkey: %w\", err)\n\t}\n\n\treturn []byte(result), nil\n}\n\nfunc (s *Store) Set(ctx context.Context, key string, value []byte, expiry time.Duration) error {\n\tif _, err := s.rdb.Set(ctx, key, string(value), expiry).Result(); err != nil {\n\t\treturn fmt.Errorf(\"can't set %q in valkey: %w\", key, err)\n\t}\n\n\treturn nil\n}\n"], ["/anubis/lib/policy/config/expressionorlist.go", "package config\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"slices\"\n\t\"strings\"\n)\n\nvar (\n\tErrExpressionOrListMustBeStringOrObject = errors.New(\"config: this must be a string or an object\")\n\tErrExpressionEmpty = errors.New(\"config: this expression is empty\")\n\tErrExpressionCantHaveBoth = errors.New(\"config: expression block can't contain multiple expression types\")\n)\n\ntype ExpressionOrList struct {\n\tExpression string `json:\"-\" yaml:\"-\"`\n\tAll []string `json:\"all,omitempty\" yaml:\"all,omitempty\"`\n\tAny []string `json:\"any,omitempty\" yaml:\"any,omitempty\"`\n}\n\nfunc (eol ExpressionOrList) String() string {\n\tswitch {\n\tcase len(eol.Expression) != 0:\n\t\treturn eol.Expression\n\tcase len(eol.All) != 0:\n\t\tvar sb strings.Builder\n\t\tfor i, pred := range eol.All {\n\t\t\tif i != 0 {\n\t\t\t\tfmt.Fprintf(&sb, \" && \")\n\t\t\t}\n\t\t\tfmt.Fprintf(&sb, \"( %s )\", pred)\n\t\t}\n\t\treturn sb.String()\n\tcase len(eol.Any) != 0:\n\t\tvar sb strings.Builder\n\t\tfor i, pred := range eol.Any {\n\t\t\tif i != 0 {\n\t\t\t\tfmt.Fprintf(&sb, \" || \")\n\t\t\t}\n\t\t\tfmt.Fprintf(&sb, \"( %s )\", pred)\n\t\t}\n\t\treturn sb.String()\n\t}\n\tpanic(\"this should not happen\")\n}\n\nfunc (eol ExpressionOrList) Equal(rhs *ExpressionOrList) bool {\n\tif eol.Expression != rhs.Expression {\n\t\treturn false\n\t}\n\n\tif !slices.Equal(eol.All, rhs.All) {\n\t\treturn false\n\t}\n\n\tif !slices.Equal(eol.Any, rhs.Any) {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\nfunc (eol *ExpressionOrList) MarshalYAML() (any, error) {\n\tswitch {\n\tcase len(eol.All) == 1 && len(eol.Any) == 0:\n\t\teol.Expression = eol.All[0]\n\t\teol.All = nil\n\tcase len(eol.Any) == 1 && len(eol.All) == 0:\n\t\teol.Expression = eol.Any[0]\n\t\teol.Any = nil\n\t}\n\n\tif eol.Expression != \"\" {\n\t\treturn eol.Expression, nil\n\t}\n\n\ttype RawExpressionOrList ExpressionOrList\n\treturn RawExpressionOrList(*eol), nil\n}\n\nfunc (eol *ExpressionOrList) MarshalJSON() ([]byte, error) {\n\tswitch {\n\tcase len(eol.All) == 1 && len(eol.Any) == 0:\n\t\teol.Expression = eol.All[0]\n\t\teol.All = nil\n\tcase len(eol.Any) == 1 && len(eol.All) == 0:\n\t\teol.Expression = eol.Any[0]\n\t\teol.Any = nil\n\t}\n\n\tif eol.Expression != \"\" {\n\t\treturn json.Marshal(string(eol.Expression))\n\t}\n\n\ttype RawExpressionOrList ExpressionOrList\n\tval := RawExpressionOrList(*eol)\n\treturn json.Marshal(val)\n}\n\nfunc (eol *ExpressionOrList) UnmarshalJSON(data []byte) error {\n\tswitch string(data[0]) {\n\tcase `\"`: // string\n\t\treturn json.Unmarshal(data, &eol.Expression)\n\tcase \"{\": // object\n\t\ttype RawExpressionOrList ExpressionOrList\n\t\tvar val RawExpressionOrList\n\t\tif err := json.Unmarshal(data, &val); err != nil {\n\t\t\treturn err\n\t\t}\n\t\teol.All = val.All\n\t\teol.Any = val.Any\n\n\t\treturn nil\n\t}\n\n\treturn ErrExpressionOrListMustBeStringOrObject\n}\n\nfunc (eol *ExpressionOrList) Valid() error {\n\tif eol.Expression == \"\" && len(eol.All) == 0 && len(eol.Any) == 0 {\n\t\treturn ErrExpressionEmpty\n\t}\n\tif len(eol.All) != 0 && len(eol.Any) != 0 {\n\t\treturn ErrExpressionCantHaveBoth\n\t}\n\n\treturn nil\n}\n"], ["/anubis/lib/store/valkey/factory.go", "package valkey\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n\tvalkey \"github.com/redis/go-redis/v9\"\n)\n\nvar (\n\tErrNoURL = errors.New(\"valkey.Config: no URL defined\")\n\tErrBadURL = errors.New(\"valkey.Config: URL is invalid\")\n)\n\nfunc init() {\n\tstore.Register(\"valkey\", Factory{})\n}\n\ntype Factory struct{}\n\nfunc (Factory) Build(ctx context.Context, data json.RawMessage) (store.Interface, error) {\n\tvar config Config\n\n\tif err := json.Unmarshal([]byte(data), &config); err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\tif err := config.Valid(); err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\topts, err := valkey.ParseURL(config.URL)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\trdb := valkey.NewClient(opts)\n\n\tif _, err := rdb.Ping(ctx).Result(); err != nil {\n\t\treturn nil, fmt.Errorf(\"can't ping valkey instance: %w\", err)\n\t}\n\n\treturn &Store{\n\t\trdb: rdb,\n\t}, nil\n}\n\nfunc (Factory) Valid(data json.RawMessage) error {\n\tvar config Config\n\tif err := json.Unmarshal([]byte(data), &config); err != nil {\n\t\treturn fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\tif err := config.Valid(); err != nil {\n\t\treturn fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\treturn nil\n}\n\ntype Config struct {\n\tURL string `json:\"url\"`\n}\n\nfunc (c Config) Valid() error {\n\tvar errs []error\n\n\tif c.URL == \"\" {\n\t\terrs = append(errs, ErrNoURL)\n\t}\n\n\tif _, err := valkey.ParseURL(c.URL); err != nil {\n\t\terrs = append(errs, ErrBadURL)\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"valkey.Config: invalid config: %w\", errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n"], ["/anubis/internal/dnsbl/droneblresponse_string.go", "// Code generated by \"stringer -type=DroneBLResponse\"; DO NOT EDIT.\n\npackage dnsbl\n\nimport \"strconv\"\n\nfunc _() {\n\t// An \"invalid array index\" compiler error signifies that the constant values have changed.\n\t// Re-run the stringer command to generate them again.\n\tvar x [1]struct{}\n\t_ = x[AllGood-0]\n\t_ = x[IRCDrone-3]\n\t_ = x[Bottler-5]\n\t_ = x[UnknownSpambotOrDrone-6]\n\t_ = x[DDOSDrone-7]\n\t_ = x[SOCKSProxy-8]\n\t_ = x[HTTPProxy-9]\n\t_ = x[ProxyChain-10]\n\t_ = x[OpenProxy-11]\n\t_ = x[OpenDNSResolver-12]\n\t_ = x[BruteForceAttackers-13]\n\t_ = x[OpenWingateProxy-14]\n\t_ = x[CompromisedRouter-15]\n\t_ = x[AutoRootingWorms-16]\n\t_ = x[AutoDetectedBotIP-17]\n\t_ = x[Unknown-255]\n}\n\nconst (\n\t_DroneBLResponse_name_0 = \"AllGood\"\n\t_DroneBLResponse_name_1 = \"IRCDrone\"\n\t_DroneBLResponse_name_2 = \"BottlerUnknownSpambotOrDroneDDOSDroneSOCKSProxyHTTPProxyProxyChainOpenProxyOpenDNSResolverBruteForceAttackersOpenWingateProxyCompromisedRouterAutoRootingWormsAutoDetectedBotIP\"\n\t_DroneBLResponse_name_3 = \"Unknown\"\n)\n\nvar (\n\t_DroneBLResponse_index_2 = [...]uint8{0, 7, 28, 37, 47, 56, 66, 75, 90, 109, 125, 142, 158, 175}\n)\n\nfunc (i DroneBLResponse) String() string {\n\tswitch {\n\tcase i == 0:\n\t\treturn _DroneBLResponse_name_0\n\tcase i == 3:\n\t\treturn _DroneBLResponse_name_1\n\tcase 5 <= i && i <= 17:\n\t\ti -= 5\n\t\treturn _DroneBLResponse_name_2[_DroneBLResponse_index_2[i]:_DroneBLResponse_index_2[i+1]]\n\tcase i == 255:\n\t\treturn _DroneBLResponse_name_3\n\tdefault:\n\t\treturn \"DroneBLResponse(\" + strconv.FormatInt(int64(i), 10) + \")\"\n\t}\n}\n"], ["/anubis/lib/store/memory/memory.go", "package memory\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis/decaymap\"\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n)\n\ntype factory struct{}\n\nfunc (factory) Build(ctx context.Context, _ json.RawMessage) (store.Interface, error) {\n\treturn New(ctx), nil\n}\n\nfunc (factory) Valid(json.RawMessage) error { return nil }\n\nfunc init() {\n\tstore.Register(\"memory\", factory{})\n}\n\ntype impl struct {\n\tstore *decaymap.Impl[string, []byte]\n}\n\nfunc (i *impl) Delete(_ context.Context, key string) error {\n\tif !i.store.Delete(key) {\n\t\treturn fmt.Errorf(\"%w: %q\", store.ErrNotFound, key)\n\t}\n\n\treturn nil\n}\n\nfunc (i *impl) Get(_ context.Context, key string) ([]byte, error) {\n\tresult, ok := i.store.Get(key)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"%w: %q\", store.ErrNotFound, key)\n\t}\n\n\treturn result, nil\n}\n\nfunc (i *impl) Set(_ context.Context, key string, value []byte, expiry time.Duration) error {\n\ti.store.Set(key, value, expiry)\n\treturn nil\n}\n\nfunc (i *impl) cleanupThread(ctx context.Context) {\n\tt := time.NewTicker(5 * time.Minute)\n\tdefer t.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase <-t.C:\n\t\t\ti.store.Cleanup()\n\t\t}\n\t}\n}\n\n// New creates a simple in-memory store. This will not scale to multiple Anubis instances.\nfunc New(ctx context.Context) store.Interface {\n\tresult := &impl{\n\t\tstore: decaymap.New[string, []byte](),\n\t}\n\n\tgo result.cleanupThread(ctx)\n\n\treturn result\n}\n"], ["/anubis/internal/ogtags/parse.go", "package ogtags\n\nimport (\n\t\"strings\"\n\n\t\"golang.org/x/net/html\"\n)\n\n// extractOGTags traverses the HTML document and extracts approved Open Graph tags\nfunc (c *OGTagCache) extractOGTags(doc *html.Node) map[string]string {\n\togTags := make(map[string]string)\n\n\tvar traverseNodes func(*html.Node)\n\ttraverseNodes = func(n *html.Node) {\n\t\tif isOGMetaTag(n) {\n\t\t\tproperty, content := c.extractMetaTagInfo(n)\n\t\t\tif property != \"\" {\n\t\t\t\togTags[property] = content\n\t\t\t}\n\t\t}\n\t\tfor child := n.FirstChild; child != nil; child = child.NextSibling {\n\t\t\ttraverseNodes(child)\n\t\t}\n\t}\n\n\ttraverseNodes(doc)\n\treturn ogTags\n}\n\n// isOGMetaTag checks if a node is *any* meta tag\nfunc isOGMetaTag(n *html.Node) bool {\n\tif n == nil {\n\t\treturn false\n\t}\n\treturn n.Type == html.ElementNode && n.Data == \"meta\"\n}\n\n// extractMetaTagInfo extracts property and content from a meta tag\nfunc (c *OGTagCache) extractMetaTagInfo(n *html.Node) (property, content string) {\n\tvar propertyKey string\n\n\t// Single pass through attributes, using range to avoid bounds checking\n\tfor _, attr := range n.Attr {\n\t\tswitch attr.Key {\n\t\tcase \"property\", \"name\":\n\t\t\tpropertyKey = attr.Val\n\t\tcase \"content\":\n\t\t\tcontent = attr.Val\n\t\t}\n\t\t// Early exit if we have both\n\t\tif propertyKey != \"\" && content != \"\" {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif propertyKey == \"\" {\n\t\treturn \"\", content\n\t}\n\n\t// Check prefixes first (more common case)\n\tfor _, prefix := range c.approvedPrefixes {\n\t\tif strings.HasPrefix(propertyKey, prefix) {\n\t\t\treturn propertyKey, content\n\t\t}\n\t}\n\n\t// Check exact matches\n\tfor _, tag := range c.approvedTags {\n\t\tif propertyKey == tag {\n\t\t\treturn propertyKey, content\n\t\t}\n\t}\n\n\treturn \"\", content\n}\n"], ["/anubis/xess/xess.go", "// Package xess vendors a copy of Xess and makes it available at /.xess/xess.css\n//\n// This is intended to be used as a vendored package in other projects.\npackage xess\n\nimport (\n\t\"embed\"\n\t\"net/http\"\n\t\"path/filepath\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/TecharoHQ/anubis/internal\"\n)\n\nvar (\n\t//go:embed *.css static\n\tStatic embed.FS\n\n\tURL = \"/.within.website/x/xess/xess.css\"\n)\n\nfunc init() {\n\tMount(http.DefaultServeMux)\n\n\t//goland:noinspection GoBoolExpressions\n\tif anubis.Version != \"devel\" {\n\t\tURL = filepath.Join(filepath.Dir(URL), \"xess.min.css\")\n\t}\n\n\tURL = URL + \"?cachebuster=\" + anubis.Version\n}\n\n// Mount registers the xess static file handlers on the given mux\nfunc Mount(mux *http.ServeMux) {\n\tprefix := anubis.BasePrefix + \"/.within.website/x/xess/\"\n\n\tmux.Handle(prefix, internal.UnchangingCache(http.StripPrefix(prefix, http.FileServerFS(Static))))\n}\n"], ["/anubis/lib/policy/config/store.go", "package config\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n\t_ \"github.com/TecharoHQ/anubis/lib/store/all\"\n)\n\nvar (\n\tErrNoStoreBackend = errors.New(\"config.Store: no backend defined\")\n\tErrUnknownStoreBackend = errors.New(\"config.Store: unknown backend\")\n)\n\ntype Store struct {\n\tBackend string `json:\"backend\"`\n\tParameters json.RawMessage `json:\"parameters\"`\n}\n\nfunc (s *Store) Valid() error {\n\tvar errs []error\n\n\tif len(s.Backend) == 0 {\n\t\terrs = append(errs, ErrNoStoreBackend)\n\t}\n\n\tfac, ok := store.Get(s.Backend)\n\tswitch ok {\n\tcase true:\n\t\tif err := fac.Valid(s.Parameters); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\tcase false:\n\t\terrs = append(errs, fmt.Errorf(\"%w: %q\", ErrUnknownStoreBackend, s.Backend))\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn errors.Join(errs...)\n\t}\n\n\treturn nil\n}\n"], ["/anubis/lib/policy/expressions/loadavg.go", "package expressions\n\nimport (\n\t\"context\"\n\t\"log/slog\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/shirou/gopsutil/v4/load\"\n)\n\ntype loadAvg struct {\n\tlock sync.RWMutex\n\tdata *load.AvgStat\n}\n\nfunc (l *loadAvg) updateThread(ctx context.Context) {\n\tticker := time.NewTicker(15 * time.Second)\n\tdefer ticker.Stop()\n\n\tl.update()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tl.update()\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (l *loadAvg) update() {\n\tl.lock.Lock()\n\tdefer l.lock.Unlock()\n\n\tvar err error\n\tl.data, err = load.Avg()\n\tif err != nil {\n\t\tslog.Debug(\"can't get load average\", \"err\", err)\n\t}\n}\n\nvar (\n\tglobalLoadAvg *loadAvg\n)\n\nfunc init() {\n\tglobalLoadAvg = &loadAvg{}\n\tgo globalLoadAvg.updateThread(context.Background())\n}\n\nfunc Load1() float64 {\n\tglobalLoadAvg.lock.RLock()\n\tdefer globalLoadAvg.lock.RUnlock()\n\treturn globalLoadAvg.data.Load1\n}\n\nfunc Load5() float64 {\n\tglobalLoadAvg.lock.RLock()\n\tdefer globalLoadAvg.lock.RUnlock()\n\treturn globalLoadAvg.data.Load5\n}\n\nfunc Load15() float64 {\n\tglobalLoadAvg.lock.RLock()\n\tdefer globalLoadAvg.lock.RUnlock()\n\treturn globalLoadAvg.data.Load15\n}\n"], ["/anubis/decaymap/decaymap.go", "package decaymap\n\nimport (\n\t\"sync\"\n\t\"time\"\n)\n\nfunc Zilch[T any]() T {\n\tvar zero T\n\treturn zero\n}\n\n// Impl is a lazy key->value map. It's a wrapper around a map and a mutex. If values exceed their time-to-live, they are pruned at Get time.\ntype Impl[K comparable, V any] struct {\n\tdata map[K]decayMapEntry[V]\n\tlock sync.RWMutex\n}\n\ntype decayMapEntry[V any] struct {\n\tValue V\n\texpiry time.Time\n}\n\n// New creates a new DecayMap of key type K and value type V.\n//\n// Key types must be comparable to work with maps.\nfunc New[K comparable, V any]() *Impl[K, V] {\n\treturn &Impl[K, V]{\n\t\tdata: make(map[K]decayMapEntry[V]),\n\t}\n}\n\n// expire forcibly expires a key by setting its time-to-live one second in the past.\nfunc (m *Impl[K, V]) expire(key K) bool {\n\tm.lock.RLock()\n\tval, ok := m.data[key]\n\tm.lock.RUnlock()\n\n\tif !ok {\n\t\treturn false\n\t}\n\n\tm.lock.Lock()\n\tval.expiry = time.Now().Add(-1 * time.Second)\n\tm.data[key] = val\n\tm.lock.Unlock()\n\n\treturn true\n}\n\n// Delete a value from the DecayMap by key.\n//\n// If the value does not exist, return false. Return true after\n// deletion.\nfunc (m *Impl[K, V]) Delete(key K) bool {\n\tm.lock.RLock()\n\t_, ok := m.data[key]\n\tm.lock.RUnlock()\n\n\tif !ok {\n\t\treturn false\n\t}\n\n\tm.lock.Lock()\n\tdelete(m.data, key)\n\tm.lock.Unlock()\n\n\treturn true\n}\n\n// Get gets a value from the DecayMap by key.\n//\n// If a value has expired, forcibly delete it if it was not updated.\nfunc (m *Impl[K, V]) Get(key K) (V, bool) {\n\tm.lock.RLock()\n\tvalue, ok := m.data[key]\n\tm.lock.RUnlock()\n\n\tif !ok {\n\t\treturn Zilch[V](), false\n\t}\n\n\tif time.Now().After(value.expiry) {\n\t\tm.lock.Lock()\n\t\t// Since previously reading m.data[key], the value may have been updated.\n\t\t// Delete the entry only if the expiry time is still the same.\n\t\tif m.data[key].expiry.Equal(value.expiry) {\n\t\t\tdelete(m.data, key)\n\t\t}\n\t\tm.lock.Unlock()\n\n\t\treturn Zilch[V](), false\n\t}\n\n\treturn value.Value, true\n}\n\n// Set sets a key value pair in the map.\nfunc (m *Impl[K, V]) Set(key K, value V, ttl time.Duration) {\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\n\tm.data[key] = decayMapEntry[V]{\n\t\tValue: value,\n\t\texpiry: time.Now().Add(ttl),\n\t}\n}\n\n// Cleanup removes all expired entries from the DecayMap.\nfunc (m *Impl[K, V]) Cleanup() {\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\n\tnow := time.Now()\n\tfor key, entry := range m.data {\n\t\tif now.After(entry.expiry) {\n\t\t\tdelete(m.data, key)\n\t\t}\n\t}\n}\n\n// Len returns the number of entries in the DecayMap.\nfunc (m *Impl[K, V]) Len() int {\n\tm.lock.RLock()\n\tdefer m.lock.RUnlock()\n\treturn len(m.data)\n}\n"], ["/anubis/internal/health.go", "package internal\n\nimport (\n\t\"context\"\n\n\t\"google.golang.org/grpc/health\"\n\thealthv1 \"google.golang.org/grpc/health/grpc_health_v1\"\n)\n\nvar HealthSrv = health.NewServer()\n\nfunc SetHealth(svc string, status healthv1.HealthCheckResponse_ServingStatus) {\n\tHealthSrv.SetServingStatus(svc, status)\n}\n\nfunc GetHealth(svc string) (healthv1.HealthCheckResponse_ServingStatus, bool) {\n\tst, err := HealthSrv.Check(context.Background(), &healthv1.HealthCheckRequest{\n\t\tService: svc,\n\t})\n\tif err != nil {\n\t\treturn healthv1.HealthCheckResponse_UNKNOWN, false\n\t}\n\n\treturn st.GetStatus(), true\n}\n"], ["/anubis/lib/challenge/interface.go", "package challenge\n\nimport (\n\t\"log/slog\"\n\t\"net/http\"\n\t\"sort\"\n\t\"sync\"\n\n\t\"github.com/TecharoHQ/anubis/lib/policy\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n\t\"github.com/a-h/templ\"\n)\n\nvar (\n\tregistry map[string]Impl = map[string]Impl{}\n\tregLock sync.RWMutex\n)\n\nfunc Register(name string, impl Impl) {\n\tregLock.Lock()\n\tdefer regLock.Unlock()\n\n\tregistry[name] = impl\n}\n\nfunc Get(name string) (Impl, bool) {\n\tregLock.RLock()\n\tdefer regLock.RUnlock()\n\tresult, ok := registry[name]\n\treturn result, ok\n}\n\nfunc Methods() []string {\n\tregLock.RLock()\n\tdefer regLock.RUnlock()\n\tvar result []string\n\tfor method := range registry {\n\t\tresult = append(result, method)\n\t}\n\tsort.Strings(result)\n\treturn result\n}\n\ntype IssueInput struct {\n\tImpressum *config.Impressum\n\tRule *policy.Bot\n\tChallenge *Challenge\n\tOGTags map[string]string\n\tStore store.Interface\n}\n\ntype ValidateInput struct {\n\tRule *policy.Bot\n\tChallenge *Challenge\n\tStore store.Interface\n}\n\ntype Impl interface {\n\t// Setup registers any additional routes with the Impl for assets or API routes.\n\tSetup(mux *http.ServeMux)\n\n\t// Issue a new challenge to the user, called by the Anubis.\n\tIssue(r *http.Request, lg *slog.Logger, in *IssueInput) (templ.Component, error)\n\n\t// Validate a challenge, making sure that it passes muster.\n\tValidate(r *http.Request, lg *slog.Logger, in *ValidateInput) error\n}\n"], ["/anubis/lib/policy/expressions/url_values.go", "package expressions\n\nimport (\n\t\"errors\"\n\t\"net/url\"\n\t\"reflect\"\n\t\"strings\"\n\n\t\"github.com/google/cel-go/common/types\"\n\t\"github.com/google/cel-go/common/types/ref\"\n\t\"github.com/google/cel-go/common/types/traits\"\n)\n\nvar ErrNotImplemented = errors.New(\"expressions: not implemented\")\n\n// URLValues is a type wrapper to expose url.Values into CEL programs.\ntype URLValues struct {\n\turl.Values\n}\n\nfunc (u URLValues) ConvertToNative(typeDesc reflect.Type) (any, error) {\n\treturn nil, ErrNotImplemented\n}\n\nfunc (u URLValues) ConvertToType(typeVal ref.Type) ref.Val {\n\tswitch typeVal {\n\tcase types.MapType:\n\t\treturn u\n\tcase types.TypeType:\n\t\treturn types.MapType\n\t}\n\n\treturn types.NewErr(\"can't convert from %q to %q\", types.MapType, typeVal)\n}\n\nfunc (u URLValues) Equal(other ref.Val) ref.Val {\n\treturn types.Bool(false) // We don't want to compare header maps\n}\n\nfunc (u URLValues) Type() ref.Type {\n\treturn types.MapType\n}\n\nfunc (u URLValues) Value() any { return u }\n\nfunc (u URLValues) Find(key ref.Val) (ref.Val, bool) {\n\tk, ok := key.(types.String)\n\tif !ok {\n\t\treturn nil, false\n\t}\n\n\tif _, ok := u.Values[string(k)]; !ok {\n\t\treturn nil, false\n\t}\n\n\treturn types.String(strings.Join(u.Values[string(k)], \",\")), true\n}\n\nfunc (u URLValues) Contains(key ref.Val) ref.Val {\n\t_, ok := u.Find(key)\n\treturn types.Bool(ok)\n}\n\nfunc (u URLValues) Get(key ref.Val) ref.Val {\n\tresult, ok := u.Find(key)\n\tif !ok {\n\t\treturn types.ValOrErr(result, \"no such key: %v\", key)\n\t}\n\treturn result\n}\n\nfunc (u URLValues) Iterator() traits.Iterator { panic(\"TODO(Xe): implement me\") }\n\nfunc (u URLValues) IsZeroValue() bool {\n\treturn len(u.Values) == 0\n}\n\nfunc (u URLValues) Size() ref.Val { return types.Int(len(u.Values)) }\n"], ["/anubis/lib/policy/expressions/http_headers.go", "package expressions\n\nimport (\n\t\"net/http\"\n\t\"reflect\"\n\t\"strings\"\n\n\t\"github.com/google/cel-go/common/types\"\n\t\"github.com/google/cel-go/common/types/ref\"\n\t\"github.com/google/cel-go/common/types/traits\"\n)\n\n// HTTPHeaders is a type wrapper to expose HTTP headers into CEL programs.\ntype HTTPHeaders struct {\n\thttp.Header\n}\n\nfunc (h HTTPHeaders) ConvertToNative(typeDesc reflect.Type) (any, error) {\n\treturn nil, ErrNotImplemented\n}\n\nfunc (h HTTPHeaders) ConvertToType(typeVal ref.Type) ref.Val {\n\tswitch typeVal {\n\tcase types.MapType:\n\t\treturn h\n\tcase types.TypeType:\n\t\treturn types.MapType\n\t}\n\n\treturn types.NewErr(\"can't convert from %q to %q\", types.MapType, typeVal)\n}\n\nfunc (h HTTPHeaders) Equal(other ref.Val) ref.Val {\n\treturn types.Bool(false) // We don't want to compare header maps\n}\n\nfunc (h HTTPHeaders) Type() ref.Type {\n\treturn types.MapType\n}\n\nfunc (h HTTPHeaders) Value() any { return h }\n\nfunc (h HTTPHeaders) Find(key ref.Val) (ref.Val, bool) {\n\tk, ok := key.(types.String)\n\tif !ok {\n\t\treturn nil, false\n\t}\n\n\tif _, ok := h.Header[string(k)]; !ok {\n\t\treturn nil, false\n\t}\n\n\treturn types.String(strings.Join(h.Header.Values(string(k)), \",\")), true\n}\n\nfunc (h HTTPHeaders) Contains(key ref.Val) ref.Val {\n\t_, ok := h.Find(key)\n\treturn types.Bool(ok)\n}\n\nfunc (h HTTPHeaders) Get(key ref.Val) ref.Val {\n\tresult, ok := h.Find(key)\n\tif !ok {\n\t\treturn types.ValOrErr(result, \"no such key: %v\", key)\n\t}\n\treturn result\n}\n\nfunc (h HTTPHeaders) Iterator() traits.Iterator { panic(\"TODO(Xe): implement me\") }\n\nfunc (h HTTPHeaders) IsZeroValue() bool {\n\treturn len(h.Header) == 0\n}\n\nfunc (h HTTPHeaders) Size() ref.Val { return types.Int(len(h.Header)) }\n"], ["/anubis/internal/gzip.go", "package internal\n\nimport (\n\t\"compress/gzip\"\n\t\"net/http\"\n\t\"strings\"\n)\n\nfunc GzipMiddleware(level int, next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif !strings.Contains(r.Header.Get(\"Accept-Encoding\"), \"gzip\") {\n\t\t\tnext.ServeHTTP(w, r)\n\t\t\treturn\n\t\t}\n\n\t\tw.Header().Set(\"Content-Encoding\", \"gzip\")\n\t\tgz, err := gzip.NewWriterLevel(w, level)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tdefer gz.Close()\n\n\t\tgrw := gzipResponseWriter{ResponseWriter: w, sink: gz}\n\t\tnext.ServeHTTP(grw, r)\n\t})\n}\n\ntype gzipResponseWriter struct {\n\thttp.ResponseWriter\n\tsink *gzip.Writer\n}\n\nfunc (w gzipResponseWriter) Write(b []byte) (int, error) {\n\treturn w.sink.Write(b)\n}\n"], ["/anubis/lib/policy/thresholds.go", "package policy\n\nimport (\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/expressions\"\n\t\"github.com/google/cel-go/cel\"\n)\n\ntype Threshold struct {\n\tconfig.Threshold\n\tProgram cel.Program\n}\n\nfunc ParsedThresholdFromConfig(t config.Threshold) (*Threshold, error) {\n\tresult := &Threshold{\n\t\tThreshold: t,\n\t}\n\n\tenv, err := expressions.ThresholdEnvironment()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tprogram, err := expressions.Compile(env, t.Expression.String())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult.Program = program\n\n\treturn result, nil\n}\n\ntype ThresholdRequest struct {\n\tWeight int\n}\n\nfunc (tr *ThresholdRequest) Parent() cel.Activation { return nil }\n\nfunc (tr *ThresholdRequest) ResolveName(name string) (any, bool) {\n\tswitch name {\n\tcase \"weight\":\n\t\treturn tr.Weight, true\n\tdefault:\n\t\treturn nil, false\n\t}\n}\n"], ["/anubis/lib/policy/checker/checker.go", "// Package checker defines the Checker interface and a helper utility to avoid import cycles.\npackage checker\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"strings\"\n\n\t\"github.com/TecharoHQ/anubis/internal\"\n)\n\ntype Impl interface {\n\tCheck(*http.Request) (bool, error)\n\tHash() string\n}\n\ntype List []Impl\n\nfunc (l List) Check(r *http.Request) (bool, error) {\n\tfor _, c := range l {\n\t\tok, err := c.Check(r)\n\t\tif err != nil {\n\t\t\treturn ok, err\n\t\t}\n\t\tif ok {\n\t\t\treturn ok, nil\n\t\t}\n\t}\n\n\treturn false, nil\n}\n\nfunc (l List) Hash() string {\n\tvar sb strings.Builder\n\n\tfor _, c := range l {\n\t\tfmt.Fprintln(&sb, c.Hash())\n\t}\n\n\treturn internal.FastHash(sb.String())\n}\n"], ["/anubis/internal/unbreakdocker.go", "package internal\n\nimport (\n\t\"os\"\n\t\"os/exec\"\n)\n\nfunc UnbreakDocker() {\n\t// XXX(Xe): This is bad code. Do not do this.\n\t//\n\t// I have to do this because I'm running from inside the context of a dev\n\t// container. This dev container runs in a different docker network than\n\t// the valkey test container runs in. In order to let my dev container\n\t// connect to the test container, they need to share a network in common.\n\t// The easiest network to use for this is the default \"bridge\" network.\n\t//\n\t// This is a horrifying monstrosity, but the part that scares me the most\n\t// is the fact that it works.\n\tif hostname, err := os.Hostname(); err == nil {\n\t\texec.Command(\"docker\", \"network\", \"connect\", \"bridge\", hostname).Run()\n\t}\n}\n"], ["/anubis/internal/hash.go", "package internal\n\nimport (\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"strconv\"\n\n\t\"github.com/cespare/xxhash/v2\"\n)\n\n// SHA256sum computes a cryptographic hash. Still used for proof-of-work challenges\n// where we need the security properties of a cryptographic hash function.\nfunc SHA256sum(text string) string {\n\thash := sha256.New()\n\thash.Write([]byte(text))\n\treturn hex.EncodeToString(hash.Sum(nil))\n}\n\n// FastHash is a high-performance non-cryptographic hash function suitable for\n// internal caching, policy rule identification, and other performance-critical\n// use cases where cryptographic security is not required.\nfunc FastHash(text string) string {\n\th := xxhash.Sum64String(text)\n\treturn strconv.FormatUint(h, 16)\n}\n"], ["/anubis/lib/policy/config/geoip.go", "package config\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"regexp\"\n\t\"strings\"\n)\n\nvar (\n\tcountryCodeRegexp = regexp.MustCompile(`^[a-zA-Z]{2}$`)\n\n\tErrNotCountryCode = errors.New(\"config.Bot: invalid country code\")\n)\n\ntype GeoIP struct {\n\tCountries []string `json:\"countries\"`\n}\n\nfunc (g *GeoIP) Valid() error {\n\tvar errs []error\n\n\tfor i, cc := range g.Countries {\n\t\tif !countryCodeRegexp.MatchString(cc) {\n\t\t\terrs = append(errs, fmt.Errorf(\"%w: %s\", ErrNotCountryCode, cc))\n\t\t}\n\n\t\tg.Countries[i] = strings.ToLower(cc)\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"bot.GeoIP: invalid GeoIP settings: %w\", errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n"], ["/anubis/lib/policy/config/impressum.go", "package config\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n)\n\nvar ErrMissingValue = errors.New(\"config: missing value\")\n\ntype Impressum struct {\n\tFooter string `json:\"footer\" yaml:\"footer\"`\n\tPage ImpressumPage `json:\"page\" yaml:\"page\"`\n}\n\nfunc (i Impressum) Render(_ context.Context, w io.Writer) error {\n\tif _, err := fmt.Fprint(w, i.Footer); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (i Impressum) Valid() error {\n\tvar errs []error\n\n\tif len(i.Footer) == 0 {\n\t\terrs = append(errs, fmt.Errorf(\"%w: impressum footer must be defined\", ErrMissingValue))\n\t}\n\n\tif err := i.Page.Valid(); err != nil {\n\t\terrs = append(errs, err)\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn errors.Join(errs...)\n\t}\n\n\treturn nil\n}\n\ntype ImpressumPage struct {\n\tTitle string `json:\"title\" yaml:\"title\"`\n\tBody string `json:\"body\" yaml:\"body\"`\n}\n\nfunc (ip ImpressumPage) Render(_ context.Context, w io.Writer) error {\n\tif _, err := fmt.Fprint(w, ip.Body); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (ip ImpressumPage) Valid() error {\n\tvar errs []error\n\n\tif len(ip.Title) == 0 {\n\t\terrs = append(errs, fmt.Errorf(\"%w: impressum page title must be defined\", ErrMissingValue))\n\t}\n\n\tif len(ip.Body) == 0 {\n\t\terrs = append(errs, fmt.Errorf(\"%w: impressum body title must be defined\", ErrMissingValue))\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn errors.Join(errs...)\n\t}\n\n\treturn nil\n}\n"], ["/anubis/lib/challenge/error.go", "package challenge\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net/http\"\n)\n\nvar (\n\tErrFailed = errors.New(\"challenge: user failed challenge\")\n\tErrMissingField = errors.New(\"challenge: missing field\")\n\tErrInvalidFormat = errors.New(\"challenge: field has invalid format\")\n)\n\nfunc NewError(verb, publicReason string, privateReason error) *Error {\n\treturn &Error{\n\t\tVerb: verb,\n\t\tPublicReason: publicReason,\n\t\tPrivateReason: privateReason,\n\t\tStatusCode: http.StatusForbidden,\n\t}\n}\n\ntype Error struct {\n\tPrivateReason error\n\tVerb string\n\tPublicReason string\n\tStatusCode int\n}\n\nfunc (e *Error) Error() string {\n\treturn fmt.Sprintf(\"challenge: error when processing challenge: %s: %v\", e.Verb, e.PrivateReason)\n}\n\nfunc (e *Error) Unwrap() error {\n\treturn e.PrivateReason\n}\n"], ["/anubis/lib/thoth/auth.go", "package thoth\n\nimport (\n\t\"context\"\n\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/metadata\"\n)\n\nfunc authUnaryClientInterceptor(token string) grpc.UnaryClientInterceptor {\n\treturn func(\n\t\tctx context.Context,\n\t\tmethod string,\n\t\treq interface{},\n\t\treply interface{},\n\t\tcc *grpc.ClientConn,\n\t\tinvoker grpc.UnaryInvoker,\n\t\topts ...grpc.CallOption,\n\t) error {\n\t\tmd := metadata.Pairs(\"authorization\", \"Bearer \"+token)\n\t\tctx = metadata.NewOutgoingContext(ctx, md)\n\t\treturn invoker(ctx, method, req, reply, cc, opts...)\n\t}\n}\n\nfunc authStreamClientInterceptor(token string) grpc.StreamClientInterceptor {\n\treturn func(\n\t\tctx context.Context,\n\t\tdesc *grpc.StreamDesc,\n\t\tcc *grpc.ClientConn,\n\t\tmethod string,\n\t\tstreamer grpc.Streamer,\n\t\topts ...grpc.CallOption,\n\t) (grpc.ClientStream, error) {\n\t\tmd := metadata.Pairs(\"authorization\", \"Bearer \"+token)\n\t\tctx = metadata.NewOutgoingContext(ctx, md)\n\t\treturn streamer(ctx, desc, cc, method, opts...)\n\t}\n}\n"], ["/anubis/lib/challenge/metrics.go", "package challenge\n\nimport (\n\t\"math\"\n\n\t\"github.com/prometheus/client_golang/prometheus\"\n\t\"github.com/prometheus/client_golang/prometheus/promauto\"\n)\n\nvar TimeTaken = promauto.NewHistogramVec(prometheus.HistogramOpts{\n\tName: \"anubis_time_taken\",\n\tHelp: \"The time taken for a browser to generate a response (milliseconds)\",\n\tBuckets: prometheus.ExponentialBucketsRange(1, math.Pow(2, 20), 20),\n}, []string{\"method\"})\n"], ["/anubis/lib/policy/checkresult.go", "package policy\n\nimport (\n\t\"log/slog\"\n\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n)\n\ntype CheckResult struct {\n\tName string\n\tRule config.Rule\n\tWeight int\n}\n\nfunc (cr CheckResult) LogValue() slog.Value {\n\treturn slog.GroupValue(\n\t\tslog.String(\"name\", cr.Name),\n\t\tslog.String(\"rule\", string(cr.Rule)),\n\t\tslog.Int(\"weight\", cr.Weight),\n\t)\n}\n"], ["/anubis/lib/policy/bot.go", "package policy\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/TecharoHQ/anubis/internal\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/checker\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n)\n\ntype Bot struct {\n\tRules checker.Impl\n\tChallenge *config.ChallengeRules\n\tWeight *config.Weight\n\tName string\n\tAction config.Rule\n}\n\nfunc (b Bot) Hash() string {\n\treturn internal.FastHash(fmt.Sprintf(\"%s::%s\", b.Name, b.Rules.Hash()))\n}\n"], ["/anubis/web/index.go", "package web\n\nimport (\n\t\"github.com/a-h/templ\"\n\n\t\"github.com/TecharoHQ/anubis/lib/localization\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n)\n\nfunc Base(title string, body templ.Component, impressum *config.Impressum, localizer *localization.SimpleLocalizer) templ.Component {\n\treturn base(title, body, impressum, nil, nil, localizer)\n}\n\nfunc BaseWithChallengeAndOGTags(title string, body templ.Component, impressum *config.Impressum, challenge string, rules *config.ChallengeRules, ogTags map[string]string, localizer *localization.SimpleLocalizer) (templ.Component, error) {\n\treturn base(title, body, impressum, struct {\n\t\tRules *config.ChallengeRules `json:\"rules\"`\n\t\tChallenge string `json:\"challenge\"`\n\t}{\n\t\tChallenge: challenge,\n\t\tRules: rules,\n\t}, ogTags, localizer), nil\n}\n\nfunc Index(localizer *localization.SimpleLocalizer) templ.Component {\n\treturn index(localizer)\n}\n\nfunc ErrorPage(msg, mail string, localizer *localization.SimpleLocalizer) templ.Component {\n\treturn errorPage(msg, mail, localizer)\n}\n\nfunc Bench(localizer *localization.SimpleLocalizer) templ.Component {\n\treturn bench(localizer)\n}\n"], ["/anubis/lib/thoth/thothmock/withthothmock.go", "package thothmock\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/TecharoHQ/anubis/lib/thoth\"\n)\n\nfunc WithMockThoth(t *testing.T) context.Context {\n\tt.Helper()\n\n\tthothCli := &thoth.Client{}\n\tthothCli.WithIPToASNService(MockIpToASNService())\n\tctx := thoth.With(t.Context(), thothCli)\n\treturn ctx\n}\n"], ["/anubis/internal/ja4h.go", "package internal\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/lum8rjack/go-ja4h\"\n)\n\nfunc JA4H(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tr.Header.Add(\"X-Http-Fingerprint-JA4H\", ja4h.JA4H(r))\n\t\tnext.ServeHTTP(w, r)\n\t})\n}\n"], ["/anubis/lib/store/all/all.go", "// Package all is a meta-package that imports all store implementations.\n//\n// This is a HACK to make tests work consistently.\npackage all\n\nimport (\n\t_ \"github.com/TecharoHQ/anubis/lib/store/bbolt\"\n\t_ \"github.com/TecharoHQ/anubis/lib/store/memory\"\n\t_ \"github.com/TecharoHQ/anubis/lib/store/valkey\"\n)\n"], ["/anubis/lib/thoth/context.go", "package thoth\n\nimport \"context\"\n\ntype ctxKey struct{}\n\nfunc With(ctx context.Context, cli *Client) context.Context {\n\treturn context.WithValue(ctx, ctxKey{}, cli)\n}\n\nfunc FromContext(ctx context.Context) (*Client, bool) {\n\tcli, ok := ctx.Value(ctxKey{}).(*Client)\n\treturn cli, ok\n}\n"], ["/anubis/lib/store/registry.go", "package store\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"sort\"\n\t\"sync\"\n)\n\nvar (\n\tregistry map[string]Factory = map[string]Factory{}\n\tregLock sync.RWMutex\n)\n\ntype Factory interface {\n\tBuild(ctx context.Context, config json.RawMessage) (Interface, error)\n\tValid(config json.RawMessage) error\n}\n\nfunc Register(name string, impl Factory) {\n\tregLock.Lock()\n\tdefer regLock.Unlock()\n\n\tregistry[name] = impl\n}\n\nfunc Get(name string) (Factory, bool) {\n\tregLock.RLock()\n\tdefer regLock.RUnlock()\n\tresult, ok := registry[name]\n\treturn result, ok\n}\n\nfunc Methods() []string {\n\tregLock.RLock()\n\tdefer regLock.RUnlock()\n\tvar result []string\n\tfor method := range registry {\n\t\tresult = append(result, method)\n\t}\n\tsort.Strings(result)\n\treturn result\n}\n"], ["/anubis/lib/challenge/challenge.go", "package challenge\n\nimport \"time\"\n\n// Challenge is the metadata about a single challenge issuance.\ntype Challenge struct {\n\tID string `json:\"id\"` // UUID identifying the challenge\n\tRandomData string `json:\"randomData\"` // The random data the client processes\n\tIssuedAt time.Time `json:\"issuedAt\"` // When the challenge was issued\n\tMetadata map[string]string `json:\"metadata\"` // Challenge metadata such as IP address and user agent\n}\n"], ["/anubis/data/embed.go", "package data\n\nimport \"embed\"\n\nvar (\n\t//go:embed botPolicies.yaml botPolicies.json all:apps all:bots all:clients all:common all:crawlers all:meta\n\tBotPolicies embed.FS\n)\n"], ["/anubis/web/embed.go", "package web\n\nimport \"embed\"\n\n//go:generate go tool github.com/a-h/templ/cmd/templ generate\n\nvar (\n\t//go:embed static\n\tStatic embed.FS\n)\n"], ["/anubis/internal/mimetype.go", "package internal\n\nimport \"mime\"\n\nfunc init() {\n\tmime.AddExtensionType(\".mjs\", \"text/javascript\")\n}\n"], ["/anubis/lib/policy/config/weight.go", "package config\n\ntype Weight struct {\n\tAdjust int `json:\"adjust\" yaml:\"adjust\"`\n}\n"]], "task_instance_info": {"created_time": "2025-08-20 20:50:29", "created_task_model": "DeepSeek-R1", "function_skeleton": "func makeReverseProxy (target string, targetSNI string, targetHost string, insecureSkipVerify bool) (http.Handler, error) {}", "code_description": "This code segment functions to: Configure a reverse proxy handler that forwards requests to a specified backend server while managing network protocol handling, secure connection parameters, and request header modifications based on provided configuration options."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```go\n[TASK_BEGIN]\nfunc makeReverseProxy(target string, targetSNI string, targetHost string, insecureSkipVerify bool) (http.Handler, error) {\n\ttargetURL, err := url.Parse(target)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid target URL: %w\", err)\n\t}\n\n\tproxy := httputil.NewSingleHostReverseProxy(targetURL)\n\t\n\tif targetURL.Scheme == \"https\" {\n\t\tproxy.Transport = &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\tServerName: targetSNI,\n\t\t\t\tInsecureSkipVerify: insecureSkipVerify,\n\t\t\t},\n\t\t}\n\t}\n\n\toriginalDirector := proxy.Director\n\tproxy.Director = func(req *http.Request) {\n\t\toriginalDirector(req)\n\t\t\n\t\tif targetHost != \"\" {\n\t\t\treq.Host = targetHost\n\t\t}\n\t\t\n\t\treq.Header.Set(\"X-Forwarded-Host\", req.Host)\n\t}\n\n\treturn proxy, nil\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 20-50-57"}, "editdistance_info": {"edit_distance": 30.4985, "calculate_time": "2025-08-20 20:50:57", "true_code_clean": "func makeReverseProxy(target string, targetSNI string, targetHost string, insecureSkipVerify bool) (http.Handler, error) {\n\ttargetUri, err := url.Parse(target)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to parse target URL: %w\", err)\n\t}\n\ttransport := http.DefaultTransport.(*http.Transport).Clone()\n\tif targetUri.Scheme == \"unix\" {\n\t\taddr := targetUri.Path\n\t\ttargetUri.Path = \"\"\n\t\ttransport.DialContext = func(ctx context.Context, _, _ string) (net.Conn, error) {\n\t\t\tdialer := net.Dialer{}\n\t\t\treturn dialer.DialContext(ctx, \"unix\", addr)\n\t\t}\n\t\ttransport.RegisterProtocol(\"unix\", libanubis.UnixRoundTripper{Transport: transport})\n\t}\n\tif insecureSkipVerify || targetSNI != \"\" {\n\t\ttransport.TLSClientConfig = &tls.Config{}\n\t\tif insecureSkipVerify {\n\t\t\tslog.Warn(\"TARGET_INSECURE_SKIP_VERIFY is set to true, TLS certificate validation will not be performed\", \"target\", target)\n\t\t\ttransport.TLSClientConfig.InsecureSkipVerify = true\n\t\t}\n\t\tif targetSNI != \"\" {\n\t\t\ttransport.TLSClientConfig.ServerName = targetSNI\n\t\t}\n\t}\n\trp := httputil.NewSingleHostReverseProxy(targetUri)\n\trp.Transport = transport\n\tif targetHost != \"\" {\n\t\toriginalDirector := rp.Director\n\t\trp.Director = func(req *http.Request) {\n\t\t\toriginalDirector(req)\n\t\t\treq.Host = targetHost\n\t\t}\n\t}\n\treturn rp, nil\n}", "predict_code_clean": "func makeReverseProxy(target string, targetSNI string, targetHost string, insecureSkipVerify bool) (http.Handler, error) {\n\ttargetURL, err := url.Parse(target)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid target URL: %w\", err)\n\t}\n\tproxy := httputil.NewSingleHostReverseProxy(targetURL)\n\tif targetURL.Scheme == \"https\" {\n\t\tproxy.Transport = &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\tServerName: targetSNI,\n\t\t\t\tInsecureSkipVerify: insecureSkipVerify,\n\t\t\t},\n\t\t}\n\t}\n\toriginalDirector := proxy.Director\n\tproxy.Director = func(req *http.Request) {\n\t\toriginalDirector(req)\n\t\tif targetHost != \"\" {\n\t\t\treq.Host = targetHost\n\t\t}\n\t\treq.Header.Set(\"X-Forwarded-Host\", req.Host)\n\t}\n\treturn proxy, nil\n}"}} {"repo_name": "anubis", "file_name": "/anubis/lib/config.go", "inference_info": {"prefix_code": "package lib\n\nimport (\n\t\"context\"\n\t\"crypto/ed25519\"\n\t\"crypto/rand\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log/slog\"\n\t\"net/http\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/TecharoHQ/anubis/data\"\n\t\"github.com/TecharoHQ/anubis/internal\"\n\t\"github.com/TecharoHQ/anubis/internal/ogtags\"\n\t\"github.com/TecharoHQ/anubis/lib/challenge\"\n\t\"github.com/TecharoHQ/anubis/lib/localization\"\n\t\"github.com/TecharoHQ/anubis/lib/policy\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/web\"\n\t\"github.com/TecharoHQ/anubis/xess\"\n\t\"github.com/a-h/templ\"\n)\n\ntype Options struct {\n\tNext http.Handler\n\tPolicy *policy.ParsedConfig\n\tTarget string\n\tCookieDynamicDomain bool\n\tCookieDomain string\n\tCookieExpiration time.Duration\n\tCookiePartitioned bool\n\tBasePrefix string\n\tWebmasterEmail string\n\tRedirectDomains []string\n\tED25519PrivateKey ed25519.PrivateKey\n\tHS512Secret []byte\n\tStripBasePrefix bool\n\tOpenGraph config.OpenGraph\n\tServeRobotsTXT bool\n\tCookieSecure bool\n}\n\n", "suffix_code": "\n\nfunc New(opts Options) (*Server, error) {\n\tif opts.ED25519PrivateKey == nil && opts.HS512Secret == nil {\n\t\tslog.Debug(\"opts.PrivateKey not set, generating a new one\")\n\t\t_, priv, err := ed25519.GenerateKey(rand.Reader)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"lib: can't generate private key: %v\", err)\n\t\t}\n\t\topts.ED25519PrivateKey = priv\n\t}\n\n\tanubis.BasePrefix = opts.BasePrefix\n\n\tresult := &Server{\n\t\tnext: opts.Next,\n\t\ted25519Priv: opts.ED25519PrivateKey,\n\t\ths512Secret: opts.HS512Secret,\n\t\tpolicy: opts.Policy,\n\t\topts: opts,\n\t\tOGTags: ogtags.NewOGTagCache(opts.Target, opts.Policy.OpenGraph, opts.Policy.Store),\n\t\tstore: opts.Policy.Store,\n\t}\n\n\tmux := http.NewServeMux()\n\txess.Mount(mux)\n\n\t// Helper to add global prefix\n\tregisterWithPrefix := func(pattern string, handler http.Handler, method string) {\n\t\tif method != \"\" {\n\t\t\tmethod = method + \" \" // methods must end with a space to register with them\n\t\t}\n\n\t\t// Ensure there's no double slash when concatenating BasePrefix and pattern\n\t\tbasePrefix := strings.TrimSuffix(anubis.BasePrefix, \"/\")\n\t\tprefix := method + basePrefix\n\n\t\t// If pattern doesn't start with a slash, add one\n\t\tif !strings.HasPrefix(pattern, \"/\") {\n\t\t\tpattern = \"/\" + pattern\n\t\t}\n\n\t\tmux.Handle(prefix+pattern, handler)\n\t}\n\n\t// Ensure there's no double slash when concatenating BasePrefix and StaticPath\n\tstripPrefix := strings.TrimSuffix(anubis.BasePrefix, \"/\") + anubis.StaticPath\n\tregisterWithPrefix(anubis.StaticPath, internal.UnchangingCache(internal.NoBrowsing(http.StripPrefix(stripPrefix, http.FileServerFS(web.Static)))), \"\")\n\n\tif opts.ServeRobotsTXT {\n\t\tregisterWithPrefix(\"/robots.txt\", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\thttp.ServeFileFS(w, r, web.Static, \"static/robots.txt\")\n\t\t}), \"GET\")\n\t\tregisterWithPrefix(\"/.well-known/robots.txt\", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\thttp.ServeFileFS(w, r, web.Static, \"static/robots.txt\")\n\t\t}), \"GET\")\n\t}\n\n\tif opts.Policy.Impressum != nil {\n\t\tregisterWithPrefix(anubis.APIPrefix+\"imprint\", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\ttempl.Handler(\n\t\t\t\tweb.Base(opts.Policy.Impressum.Page.Title, opts.Policy.Impressum.Page, opts.Policy.Impressum, localization.GetLocalizer(r)),\n\t\t\t).ServeHTTP(w, r)\n\t\t}), \"GET\")\n\t}\n\n\tregisterWithPrefix(anubis.APIPrefix+\"pass-challenge\", http.HandlerFunc(result.PassChallenge), \"GET\")\n\tregisterWithPrefix(anubis.APIPrefix+\"check\", http.HandlerFunc(result.maybeReverseProxyHttpStatusOnly), \"\")\n\tregisterWithPrefix(\"/\", http.HandlerFunc(result.maybeReverseProxyOrPage), \"\")\n\n\t//goland:noinspection GoBoolExpressions\n\tif anubis.Version == \"devel\" {\n\t\t// make-challenge is only used in tests. Only enable while version is devel\n\t\tregisterWithPrefix(anubis.APIPrefix+\"make-challenge\", http.HandlerFunc(result.MakeChallenge), \"POST\")\n\t}\n\n\tfor _, implKind := range challenge.Methods() {\n\t\timpl, _ := challenge.Get(implKind)\n\t\timpl.Setup(mux)\n\t}\n\n\tresult.mux = mux\n\n\treturn result, nil\n}\n", "middle_code": "func LoadPoliciesOrDefault(ctx context.Context, fname string, defaultDifficulty int) (*policy.ParsedConfig, error) {\n\tvar fin io.ReadCloser\n\tvar err error\n\tif fname != \"\" {\n\t\tfin, err = os.Open(fname)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"can't parse policy file %s: %w\", fname, err)\n\t\t}\n\t} else {\n\t\tfname = \"(data)/botPolicies.yaml\"\n\t\tfin, err = data.BotPolicies.Open(\"botPolicies.yaml\")\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"[unexpected] can't parse builtin policy file %s: %w\", fname, err)\n\t\t}\n\t}\n\tdefer func(fin io.ReadCloser) {\n\t\terr := fin.Close()\n\t\tif err != nil {\n\t\t\tslog.Error(\"failed to close policy file\", \"file\", fname, \"err\", err)\n\t\t}\n\t}(fin)\n\tanubisPolicy, err := policy.ParseConfig(ctx, fin, fname, defaultDifficulty)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't parse policy file %s: %w\", fname, err)\n\t}\n\tvar validationErrs []error\n\tfor _, b := range anubisPolicy.Bots {\n\t\tif _, ok := challenge.Get(b.Challenge.Algorithm); !ok {\n\t\t\tvalidationErrs = append(validationErrs, fmt.Errorf(\"%w %s\", policy.ErrChallengeRuleHasWrongAlgorithm, b.Challenge.Algorithm))\n\t\t}\n\t}\n\tif len(validationErrs) != 0 {\n\t\treturn nil, fmt.Errorf(\"can't do final validation of Anubis config: %w\", errors.Join(validationErrs...))\n\t}\n\treturn anubisPolicy, err\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "go", "sub_task_type": null}, "context_code": [["/anubis/cmd/anubis/main.go", "package main\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"crypto/ed25519\"\n\t\"crypto/rand\"\n\t\"crypto/tls\"\n\t\"embed\"\n\t\"encoding/hex\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io/fs\"\n\t\"log\"\n\t\"log/slog\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/http/httputil\"\n\t\"net/url\"\n\t\"os\"\n\t\"os/signal\"\n\t\"path/filepath\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/TecharoHQ/anubis/data\"\n\t\"github.com/TecharoHQ/anubis/internal\"\n\tlibanubis \"github.com/TecharoHQ/anubis/lib\"\n\tbotPolicy \"github.com/TecharoHQ/anubis/lib/policy\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/lib/thoth\"\n\t\"github.com/TecharoHQ/anubis/web\"\n\t\"github.com/facebookgo/flagenv\"\n\t_ \"github.com/joho/godotenv/autoload\"\n\t\"github.com/prometheus/client_golang/prometheus/promhttp\"\n\thealthv1 \"google.golang.org/grpc/health/grpc_health_v1\"\n)\n\nvar (\n\tbasePrefix = flag.String(\"base-prefix\", \"\", \"base prefix (root URL) the application is served under e.g. /myapp\")\n\tbind = flag.String(\"bind\", \":8923\", \"network address to bind HTTP to\")\n\tbindNetwork = flag.String(\"bind-network\", \"tcp\", \"network family to bind HTTP to, e.g. unix, tcp\")\n\tchallengeDifficulty = flag.Int(\"difficulty\", anubis.DefaultDifficulty, \"difficulty of the challenge\")\n\tcookieDomain = flag.String(\"cookie-domain\", \"\", \"if set, the top-level domain that the Anubis cookie will be valid for\")\n\tcookieDynamicDomain = flag.Bool(\"cookie-dynamic-domain\", false, \"if set, automatically set the cookie Domain value based on the request domain\")\n\tcookieExpiration = flag.Duration(\"cookie-expiration-time\", anubis.CookieDefaultExpirationTime, \"The amount of time the authorization cookie is valid for\")\n\tcookiePrefix = flag.String(\"cookie-prefix\", \"techaro.lol-anubis\", \"prefix for browser cookies created by Anubis\")\n\tcookiePartitioned = flag.Bool(\"cookie-partitioned\", false, \"if true, sets the partitioned flag on Anubis cookies, enabling CHIPS support\")\n\tforcedLanguage = flag.String(\"forced-language\", \"\", \"if set, this language is being used instead of the one from the request's Accept-Language header\")\n\ths512Secret = flag.String(\"hs512-secret\", \"\", \"secret used to sign JWTs, uses ed25519 if not set\")\n\tcookieSecure = flag.Bool(\"cookie-secure\", true, \"if true, sets the secure flag on Anubis cookies\")\n\ted25519PrivateKeyHex = flag.String(\"ed25519-private-key-hex\", \"\", \"private key used to sign JWTs, if not set a random one will be assigned\")\n\ted25519PrivateKeyHexFile = flag.String(\"ed25519-private-key-hex-file\", \"\", \"file name containing value for ed25519-private-key-hex\")\n\tmetricsBind = flag.String(\"metrics-bind\", \":9090\", \"network address to bind metrics to\")\n\tmetricsBindNetwork = flag.String(\"metrics-bind-network\", \"tcp\", \"network family for the metrics server to bind to\")\n\tsocketMode = flag.String(\"socket-mode\", \"0770\", \"socket mode (permissions) for unix domain sockets.\")\n\trobotsTxt = flag.Bool(\"serve-robots-txt\", false, \"serve a robots.txt file that disallows all robots\")\n\tpolicyFname = flag.String(\"policy-fname\", \"\", \"full path to anubis policy document (defaults to a sensible built-in policy)\")\n\tredirectDomains = flag.String(\"redirect-domains\", \"\", \"list of domains separated by commas which anubis is allowed to redirect to. Leaving this unset allows any domain.\")\n\tslogLevel = flag.String(\"slog-level\", \"INFO\", \"logging level (see https://pkg.go.dev/log/slog#hdr-Levels)\")\n\tstripBasePrefix = flag.Bool(\"strip-base-prefix\", false, \"if true, strips the base prefix from requests forwarded to the target server\")\n\ttarget = flag.String(\"target\", \"http://localhost:3923\", \"target to reverse proxy to, set to an empty string to disable proxying when only using auth request\")\n\ttargetSNI = flag.String(\"target-sni\", \"\", \"if set, the value of the TLS handshake hostname when forwarding requests to the target\")\n\ttargetHost = flag.String(\"target-host\", \"\", \"if set, the value of the Host header when forwarding requests to the target\")\n\ttargetInsecureSkipVerify = flag.Bool(\"target-insecure-skip-verify\", false, \"if true, skips TLS validation for the backend\")\n\thealthcheck = flag.Bool(\"healthcheck\", false, \"run a health check against Anubis\")\n\tuseRemoteAddress = flag.Bool(\"use-remote-address\", false, \"read the client's IP address from the network request, useful for debugging and running Anubis on bare metal\")\n\tdebugBenchmarkJS = flag.Bool(\"debug-benchmark-js\", false, \"respond to every request with a challenge for benchmarking hashrate\")\n\togPassthrough = flag.Bool(\"og-passthrough\", false, \"enable Open Graph tag passthrough\")\n\togTimeToLive = flag.Duration(\"og-expiry-time\", 24*time.Hour, \"Open Graph tag cache expiration time\")\n\togCacheConsiderHost = flag.Bool(\"og-cache-consider-host\", false, \"enable or disable the use of the host in the Open Graph tag cache\")\n\textractResources = flag.String(\"extract-resources\", \"\", \"if set, extract the static resources to the specified folder\")\n\twebmasterEmail = flag.String(\"webmaster-email\", \"\", \"if set, displays webmaster's email on the reject page for appeals\")\n\tversionFlag = flag.Bool(\"version\", false, \"print Anubis version\")\n\txffStripPrivate = flag.Bool(\"xff-strip-private\", true, \"if set, strip private addresses from X-Forwarded-For\")\n\n\tthothInsecure = flag.Bool(\"thoth-insecure\", false, \"if set, connect to Thoth over plain HTTP/2, don't enable this unless support told you to\")\n\tthothURL = flag.String(\"thoth-url\", \"\", \"if set, URL for Thoth, the IP reputation database for Anubis\")\n\tthothToken = flag.String(\"thoth-token\", \"\", \"if set, API token for Thoth, the IP reputation database for Anubis\")\n)\n\nfunc keyFromHex(value string) (ed25519.PrivateKey, error) {\n\tkeyBytes, err := hex.DecodeString(value)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"supplied key is not hex-encoded: %w\", err)\n\t}\n\n\tif len(keyBytes) != ed25519.SeedSize {\n\t\treturn nil, fmt.Errorf(\"supplied key is not %d bytes long, got %d bytes\", ed25519.SeedSize, len(keyBytes))\n\t}\n\n\treturn ed25519.NewKeyFromSeed(keyBytes), nil\n}\n\nfunc doHealthCheck() error {\n\tresp, err := http.Get(\"http://localhost\" + *metricsBind + \"/healthz\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to fetch metrics: %w\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn fmt.Errorf(\"unexpected status code: %d\", resp.StatusCode)\n\t}\n\n\treturn nil\n}\n\n// parseBindNetFromAddr determine bind network and address based on the given network and address.\nfunc parseBindNetFromAddr(address string) (string, string) {\n\tdefaultScheme := \"http://\"\n\tif !strings.Contains(address, \"://\") {\n\t\tif strings.HasPrefix(address, \":\") {\n\t\t\taddress = defaultScheme + \"localhost\" + address\n\t\t} else {\n\t\t\taddress = defaultScheme + address\n\t\t}\n\t}\n\n\tbindUri, err := url.Parse(address)\n\tif err != nil {\n\t\tlog.Fatal(fmt.Errorf(\"failed to parse bind URL: %w\", err))\n\t}\n\n\tswitch bindUri.Scheme {\n\tcase \"unix\":\n\t\treturn \"unix\", bindUri.Path\n\tcase \"tcp\", \"http\", \"https\":\n\t\treturn \"tcp\", bindUri.Host\n\tdefault:\n\t\tlog.Fatal(fmt.Errorf(\"unsupported network scheme %s in address %s\", bindUri.Scheme, address))\n\t}\n\treturn \"\", address\n}\n\nfunc setupListener(network string, address string) (net.Listener, string) {\n\tformattedAddress := \"\"\n\n\tif network == \"\" {\n\t\t// keep compatibility\n\t\tnetwork, address = parseBindNetFromAddr(address)\n\t}\n\n\tswitch network {\n\tcase \"unix\":\n\t\tformattedAddress = \"unix:\" + address\n\tcase \"tcp\":\n\t\tif strings.HasPrefix(address, \":\") { // assume it's just a port e.g. :4259\n\t\t\tformattedAddress = \"http://localhost\" + address\n\t\t} else {\n\t\t\tformattedAddress = \"http://\" + address\n\t\t}\n\tdefault:\n\t\tformattedAddress = fmt.Sprintf(`(%s) %s`, network, address)\n\t}\n\n\tlistener, err := net.Listen(network, address)\n\tif err != nil {\n\t\tlog.Fatal(fmt.Errorf(\"failed to bind to %s: %w\", formattedAddress, err))\n\t}\n\n\t// additional permission handling for unix sockets\n\tif network == \"unix\" {\n\t\tmode, err := strconv.ParseUint(*socketMode, 8, 0)\n\t\tif err != nil {\n\t\t\tlistener.Close()\n\t\t\tlog.Fatal(fmt.Errorf(\"could not parse socket mode %s: %w\", *socketMode, err))\n\t\t}\n\n\t\terr = os.Chmod(address, os.FileMode(mode))\n\t\tif err != nil {\n\t\t\terr := listener.Close()\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"failed to close listener: %v\", err)\n\t\t\t}\n\t\t\tlog.Fatal(fmt.Errorf(\"could not change socket mode: %w\", err))\n\t\t}\n\t}\n\n\treturn listener, formattedAddress\n}\n\nfunc makeReverseProxy(target string, targetSNI string, targetHost string, insecureSkipVerify bool) (http.Handler, error) {\n\ttargetUri, err := url.Parse(target)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to parse target URL: %w\", err)\n\t}\n\n\ttransport := http.DefaultTransport.(*http.Transport).Clone()\n\n\t// https://github.com/oauth2-proxy/oauth2-proxy/blob/4e2100a2879ef06aea1411790327019c1a09217c/pkg/upstream/http.go#L124\n\tif targetUri.Scheme == \"unix\" {\n\t\t// clean path up so we don't use the socket path in proxied requests\n\t\taddr := targetUri.Path\n\t\ttargetUri.Path = \"\"\n\t\t// tell transport how to dial unix sockets\n\t\ttransport.DialContext = func(ctx context.Context, _, _ string) (net.Conn, error) {\n\t\t\tdialer := net.Dialer{}\n\t\t\treturn dialer.DialContext(ctx, \"unix\", addr)\n\t\t}\n\t\t// tell transport how to handle the unix url scheme\n\t\ttransport.RegisterProtocol(\"unix\", libanubis.UnixRoundTripper{Transport: transport})\n\t}\n\n\tif insecureSkipVerify || targetSNI != \"\" {\n\t\ttransport.TLSClientConfig = &tls.Config{}\n\t\tif insecureSkipVerify {\n\t\t\tslog.Warn(\"TARGET_INSECURE_SKIP_VERIFY is set to true, TLS certificate validation will not be performed\", \"target\", target)\n\t\t\ttransport.TLSClientConfig.InsecureSkipVerify = true\n\t\t}\n\t\tif targetSNI != \"\" {\n\t\t\ttransport.TLSClientConfig.ServerName = targetSNI\n\t\t}\n\t}\n\n\trp := httputil.NewSingleHostReverseProxy(targetUri)\n\trp.Transport = transport\n\n\tif targetHost != \"\" {\n\t\toriginalDirector := rp.Director\n\t\trp.Director = func(req *http.Request) {\n\t\t\toriginalDirector(req)\n\t\t\treq.Host = targetHost\n\t\t}\n\t}\n\n\treturn rp, nil\n}\n\nfunc main() {\n\tflagenv.Parse()\n\tflag.Parse()\n\n\tif *versionFlag {\n\t\tfmt.Println(\"Anubis\", anubis.Version)\n\t\treturn\n\t}\n\n\tinternal.InitSlog(*slogLevel)\n\tinternal.SetHealth(\"anubis\", healthv1.HealthCheckResponse_NOT_SERVING)\n\n\tif *healthcheck {\n\t\tlog.Println(\"running healthcheck\")\n\t\tif err := doHealthCheck(); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\treturn\n\t}\n\n\tif *extractResources != \"\" {\n\t\tif err := extractEmbedFS(data.BotPolicies, \".\", *extractResources); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tif err := extractEmbedFS(web.Static, \"static\", *extractResources); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Printf(\"Extracted embedded static files to %s\\n\", *extractResources)\n\t\treturn\n\t}\n\n\t// install signal handler\n\tctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)\n\tdefer stop()\n\n\twg := new(sync.WaitGroup)\n\n\tif *metricsBind != \"\" {\n\t\twg.Add(1)\n\t\tgo metricsServer(ctx, wg.Done)\n\t}\n\n\tvar rp http.Handler\n\t// when using anubis via Systemd and environment variables, then it is not possible to set targe to an empty string but only to space\n\tif strings.TrimSpace(*target) != \"\" {\n\t\tvar err error\n\t\trp, err = makeReverseProxy(*target, *targetSNI, *targetHost, *targetInsecureSkipVerify)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"can't make reverse proxy: %v\", err)\n\t\t}\n\t}\n\n\tif *cookieDomain != \"\" && *cookieDynamicDomain {\n\t\tlog.Fatalf(\"you can't set COOKIE_DOMAIN and COOKIE_DYNAMIC_DOMAIN at the same time\")\n\t}\n\n\t// Thoth configuration\n\tswitch {\n\tcase *thothURL != \"\" && *thothToken == \"\":\n\t\tslog.Warn(\"THOTH_URL is set but no THOTH_TOKEN is set\")\n\tcase *thothURL == \"\" && *thothToken != \"\":\n\t\tslog.Warn(\"THOTH_TOKEN is set but no THOTH_URL is set\")\n\tcase *thothURL != \"\" && *thothToken != \"\":\n\t\tslog.Debug(\"connecting to Thoth\")\n\t\tthothClient, err := thoth.New(ctx, *thothURL, *thothToken, *thothInsecure)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"can't dial thoth at %s: %v\", *thothURL, err)\n\t\t}\n\n\t\tctx = thoth.With(ctx, thothClient)\n\t}\n\n\tpolicy, err := libanubis.LoadPoliciesOrDefault(ctx, *policyFname, *challengeDifficulty)\n\tif err != nil {\n\t\tlog.Fatalf(\"can't parse policy file: %v\", err)\n\t}\n\n\truleErrorIDs := make(map[string]string)\n\tfor _, rule := range policy.Bots {\n\t\tif rule.Action != config.RuleDeny {\n\t\t\tcontinue\n\t\t}\n\n\t\thash := rule.Hash()\n\t\truleErrorIDs[rule.Name] = hash\n\t}\n\n\t// replace the bot policy rules with a single rule that always benchmarks\n\tif *debugBenchmarkJS {\n\t\tpolicy.Bots = []botPolicy.Bot{{\n\t\t\tName: \"\",\n\t\t\tRules: botPolicy.NewHeaderExistsChecker(\"User-Agent\"),\n\t\t\tAction: config.RuleBenchmark,\n\t\t}}\n\t}\n\tif *basePrefix != \"\" && !strings.HasPrefix(*basePrefix, \"/\") {\n\t\tlog.Fatalf(\"[misconfiguration] base-prefix must start with a slash, eg: /%s\", *basePrefix)\n\t} else if strings.HasSuffix(*basePrefix, \"/\") {\n\t\tlog.Fatalf(\"[misconfiguration] base-prefix must not end with a slash\")\n\t}\n\tif *stripBasePrefix && *basePrefix == \"\" {\n\t\tlog.Fatalf(\"[misconfiguration] strip-base-prefix is set to true, but base-prefix is not set, \" +\n\t\t\t\"this may result in unexpected behavior\")\n\t}\n\n\tvar ed25519Priv ed25519.PrivateKey\n\tif *hs512Secret != \"\" && (*ed25519PrivateKeyHex != \"\" || *ed25519PrivateKeyHexFile != \"\") {\n\t\tlog.Fatal(\"do not specify both HS512 and ED25519 secrets\")\n\t} else if *hs512Secret != \"\" {\n\t\ted25519Priv = ed25519.PrivateKey(*hs512Secret)\n\t} else if *ed25519PrivateKeyHex != \"\" && *ed25519PrivateKeyHexFile != \"\" {\n\t\tlog.Fatal(\"do not specify both ED25519_PRIVATE_KEY_HEX and ED25519_PRIVATE_KEY_HEX_FILE\")\n\t} else if *ed25519PrivateKeyHex != \"\" {\n\t\ted25519Priv, err = keyFromHex(*ed25519PrivateKeyHex)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to parse and validate ED25519_PRIVATE_KEY_HEX: %v\", err)\n\t\t}\n\t} else if *ed25519PrivateKeyHexFile != \"\" {\n\t\thexFile, err := os.ReadFile(*ed25519PrivateKeyHexFile)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to read ED25519_PRIVATE_KEY_HEX_FILE %s: %v\", *ed25519PrivateKeyHexFile, err)\n\t\t}\n\n\t\ted25519Priv, err = keyFromHex(string(bytes.TrimSpace(hexFile)))\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to parse and validate content of ED25519_PRIVATE_KEY_HEX_FILE: %v\", err)\n\t\t}\n\t} else {\n\t\t_, ed25519Priv, err = ed25519.GenerateKey(rand.Reader)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to generate ed25519 key: %v\", err)\n\t\t}\n\n\t\tslog.Warn(\"generating random key, Anubis will have strange behavior when multiple instances are behind the same load balancer target, for more information: see https://anubis.techaro.lol/docs/admin/installation#key-generation\")\n\t}\n\n\tvar redirectDomainsList []string\n\tif *redirectDomains != \"\" {\n\t\tdomains := strings.Split(*redirectDomains, \",\")\n\t\tfor _, domain := range domains {\n\t\t\t_, err = url.Parse(domain)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"cannot parse redirect-domain %q: %s\", domain, err.Error())\n\t\t\t}\n\t\t\tredirectDomainsList = append(redirectDomainsList, strings.TrimSpace(domain))\n\t\t}\n\t} else {\n\t\tslog.Warn(\"REDIRECT_DOMAINS is not set, Anubis will only redirect to the same domain a request is coming from, see https://anubis.techaro.lol/docs/admin/configuration/redirect-domains\")\n\t}\n\n\tanubis.CookieName = *cookiePrefix + \"-auth\"\n\tanubis.TestCookieName = *cookiePrefix + \"-cookie-verification\"\n\tanubis.ForcedLanguage = *forcedLanguage\n\n\t// If OpenGraph configuration values are not set in the config file, use the\n\t// values from flags / envvars.\n\tif !policy.OpenGraph.Enabled {\n\t\tpolicy.OpenGraph.Enabled = *ogPassthrough\n\t\tpolicy.OpenGraph.ConsiderHost = *ogCacheConsiderHost\n\t\tpolicy.OpenGraph.TimeToLive = *ogTimeToLive\n\t\tpolicy.OpenGraph.Override = map[string]string{}\n\t}\n\n\ts, err := libanubis.New(libanubis.Options{\n\t\tBasePrefix: *basePrefix,\n\t\tStripBasePrefix: *stripBasePrefix,\n\t\tNext: rp,\n\t\tPolicy: policy,\n\t\tServeRobotsTXT: *robotsTxt,\n\t\tED25519PrivateKey: ed25519Priv,\n\t\tHS512Secret: []byte(*hs512Secret),\n\t\tCookieDomain: *cookieDomain,\n\t\tCookieDynamicDomain: *cookieDynamicDomain,\n\t\tCookieExpiration: *cookieExpiration,\n\t\tCookiePartitioned: *cookiePartitioned,\n\t\tRedirectDomains: redirectDomainsList,\n\t\tTarget: *target,\n\t\tWebmasterEmail: *webmasterEmail,\n\t\tOpenGraph: policy.OpenGraph,\n\t\tCookieSecure: *cookieSecure,\n\t})\n\tif err != nil {\n\t\tlog.Fatalf(\"can't construct libanubis.Server: %v\", err)\n\t}\n\n\tvar h http.Handler\n\th = s\n\th = internal.RemoteXRealIP(*useRemoteAddress, *bindNetwork, h)\n\th = internal.XForwardedForToXRealIP(h)\n\th = internal.XForwardedForUpdate(*xffStripPrivate, h)\n\th = internal.JA4H(h)\n\n\tsrv := http.Server{Handler: h, ErrorLog: internal.GetFilteredHTTPLogger()}\n\tlistener, listenerUrl := setupListener(*bindNetwork, *bind)\n\tslog.Info(\n\t\t\"listening\",\n\t\t\"url\", listenerUrl,\n\t\t\"difficulty\", *challengeDifficulty,\n\t\t\"serveRobotsTXT\", *robotsTxt,\n\t\t\"target\", *target,\n\t\t\"version\", anubis.Version,\n\t\t\"use-remote-address\", *useRemoteAddress,\n\t\t\"debug-benchmark-js\", *debugBenchmarkJS,\n\t\t\"og-passthrough\", *ogPassthrough,\n\t\t\"og-expiry-time\", *ogTimeToLive,\n\t\t\"base-prefix\", *basePrefix,\n\t\t\"cookie-expiration-time\", *cookieExpiration,\n\t\t\"rule-error-ids\", ruleErrorIDs,\n\t)\n\n\tgo func() {\n\t\t<-ctx.Done()\n\t\tc, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\t\tdefer cancel()\n\t\tif err := srv.Shutdown(c); err != nil {\n\t\t\tlog.Printf(\"cannot shut down: %v\", err)\n\t\t}\n\t}()\n\n\tinternal.SetHealth(\"anubis\", healthv1.HealthCheckResponse_SERVING)\n\n\tif err := srv.Serve(listener); !errors.Is(err, http.ErrServerClosed) {\n\t\tlog.Fatal(err)\n\t}\n\twg.Wait()\n}\n\nfunc metricsServer(ctx context.Context, done func()) {\n\tdefer done()\n\n\tmux := http.NewServeMux()\n\tmux.Handle(\"/metrics\", promhttp.Handler())\n\tmux.HandleFunc(\"/healthz\", func(w http.ResponseWriter, r *http.Request) {\n\t\tst, ok := internal.GetHealth(\"anubis\")\n\t\tif !ok {\n\t\t\tslog.Error(\"health service anubis does not exist, file a bug\")\n\t\t}\n\n\t\tswitch st {\n\t\tcase healthv1.HealthCheckResponse_NOT_SERVING:\n\t\t\thttp.Error(w, \"NOT OK\", http.StatusInternalServerError)\n\t\t\treturn\n\t\tcase healthv1.HealthCheckResponse_SERVING:\n\t\t\tfmt.Fprintln(w, \"OK\")\n\t\t\treturn\n\t\tdefault:\n\t\t\thttp.Error(w, \"UNKNOWN\", http.StatusFailedDependency)\n\t\t\treturn\n\t\t}\n\t})\n\n\tsrv := http.Server{Handler: mux, ErrorLog: internal.GetFilteredHTTPLogger()}\n\tlistener, metricsUrl := setupListener(*metricsBindNetwork, *metricsBind)\n\tslog.Debug(\"listening for metrics\", \"url\", metricsUrl)\n\n\tgo func() {\n\t\t<-ctx.Done()\n\t\tc, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\t\tdefer cancel()\n\t\tif err := srv.Shutdown(c); err != nil {\n\t\t\tlog.Printf(\"cannot shut down: %v\", err)\n\t\t}\n\t}()\n\n\tif err := srv.Serve(listener); !errors.Is(err, http.ErrServerClosed) {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc extractEmbedFS(fsys embed.FS, root string, destDir string) error {\n\treturn fs.WalkDir(fsys, root, func(path string, d fs.DirEntry, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\trelPath, err := filepath.Rel(root, path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdestPath := filepath.Join(destDir, root, relPath)\n\n\t\tif d.IsDir() {\n\t\t\treturn os.MkdirAll(destPath, 0o700)\n\t\t}\n\n\t\tembeddedData, err := fs.ReadFile(fsys, path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn os.WriteFile(destPath, embeddedData, 0o644)\n\t})\n}\n"], ["/anubis/lib/http.go", "package lib\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"net/http\"\n\t\"regexp\"\n\t\"slices\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/TecharoHQ/anubis/internal\"\n\t\"github.com/TecharoHQ/anubis/lib/challenge\"\n\t\"github.com/TecharoHQ/anubis/lib/localization\"\n\t\"github.com/TecharoHQ/anubis/lib/policy\"\n\t\"github.com/TecharoHQ/anubis/web\"\n\t\"github.com/a-h/templ\"\n\t\"github.com/golang-jwt/jwt/v5\"\n\t\"golang.org/x/net/publicsuffix\"\n)\n\nvar domainMatchRegexp = regexp.MustCompile(`^((xn--)?[a-z0-9]+(-[a-z0-9]+)*\\.)+[a-z]{2,}$`)\n\ntype CookieOpts struct {\n\tValue string\n\tHost string\n\tPath string\n\tName string\n\tExpiry time.Duration\n}\n\nfunc (s *Server) SetCookie(w http.ResponseWriter, cookieOpts CookieOpts) {\n\tvar domain = s.opts.CookieDomain\n\tvar name = anubis.CookieName\n\tvar path = \"/\"\n\tif cookieOpts.Name != \"\" {\n\t\tname = cookieOpts.Name\n\t}\n\tif cookieOpts.Path != \"\" {\n\t\tpath = cookieOpts.Path\n\t}\n\tif s.opts.CookieDynamicDomain && domainMatchRegexp.MatchString(cookieOpts.Host) {\n\t\tif etld, err := publicsuffix.EffectiveTLDPlusOne(cookieOpts.Host); err == nil {\n\t\t\tdomain = etld\n\t\t}\n\t}\n\n\tif cookieOpts.Expiry == 0 {\n\t\tcookieOpts.Expiry = s.opts.CookieExpiration\n\t}\n\n\thttp.SetCookie(w, &http.Cookie{\n\t\tName: name,\n\t\tValue: cookieOpts.Value,\n\t\tExpires: time.Now().Add(cookieOpts.Expiry),\n\t\tSameSite: http.SameSiteNoneMode,\n\t\tDomain: domain,\n\t\tSecure: s.opts.CookieSecure,\n\t\tPartitioned: s.opts.CookiePartitioned,\n\t\tPath: path,\n\t})\n}\n\nfunc (s *Server) ClearCookie(w http.ResponseWriter, cookieOpts CookieOpts) {\n\tvar domain = s.opts.CookieDomain\n\tvar name = anubis.CookieName\n\tvar path = \"/\"\n\tif cookieOpts.Name != \"\" {\n\t\tname = cookieOpts.Name\n\t}\n\tif cookieOpts.Path != \"\" {\n\t\tpath = cookieOpts.Path\n\t}\n\tif s.opts.CookieDynamicDomain && domainMatchRegexp.MatchString(cookieOpts.Host) {\n\t\tif etld, err := publicsuffix.EffectiveTLDPlusOne(cookieOpts.Host); err == nil {\n\t\t\tdomain = etld\n\t\t}\n\t}\n\n\thttp.SetCookie(w, &http.Cookie{\n\t\tName: name,\n\t\tValue: \"\",\n\t\tMaxAge: -1,\n\t\tExpires: time.Now().Add(-1 * time.Minute),\n\t\tSameSite: http.SameSiteNoneMode,\n\t\tPartitioned: s.opts.CookiePartitioned,\n\t\tDomain: domain,\n\t\tSecure: s.opts.CookieSecure,\n\t\tPath: path,\n\t})\n}\n\n// https://github.com/oauth2-proxy/oauth2-proxy/blob/master/pkg/upstream/http.go#L124\ntype UnixRoundTripper struct {\n\tTransport *http.Transport\n}\n\n// set bare minimum stuff\nfunc (t UnixRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {\n\treq = req.Clone(req.Context())\n\tif req.Host == \"\" {\n\t\treq.Host = \"localhost\"\n\t}\n\treq.URL.Host = req.Host // proxy error: no Host in request URL\n\treq.URL.Scheme = \"http\" // make http.Transport happy and avoid an infinite recursion\n\treturn t.Transport.RoundTrip(req)\n}\n\nfunc randomChance(n int) bool {\n\treturn rand.Intn(n) == 0\n}\n\nfunc (s *Server) RenderIndex(w http.ResponseWriter, r *http.Request, rule *policy.Bot, returnHTTPStatusOnly bool) {\n\tlocalizer := localization.GetLocalizer(r)\n\n\tif returnHTTPStatusOnly {\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\tw.Write([]byte(localizer.T(\"authorization_required\")))\n\t\treturn\n\t}\n\n\tlg := internal.GetRequestLogger(r)\n\n\tif !strings.Contains(r.Header.Get(\"Accept-Encoding\"), \"gzip\") && randomChance(64) {\n\t\tlg.Error(\"client was given a challenge but does not in fact support gzip compression\")\n\t\ts.respondWithError(w, r, localizer.T(\"client_error_browser\"))\n\t}\n\n\tchallengesIssued.WithLabelValues(\"embedded\").Add(1)\n\tchall, err := s.challengeFor(r)\n\tif err != nil {\n\t\tlg.Error(\"can't get challenge\", \"err\", \"err\")\n\t\ts.ClearCookie(w, CookieOpts{Name: anubis.TestCookieName, Host: r.Host})\n\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s: %s\", localizer.T(\"internal_server_error\"), rule.Challenge.Algorithm))\n\t\treturn\n\t}\n\n\tvar ogTags map[string]string = nil\n\tif s.opts.OpenGraph.Enabled {\n\t\tvar err error\n\t\togTags, err = s.OGTags.GetOGTags(r.Context(), r.URL, r.Host)\n\t\tif err != nil {\n\t\t\tlg.Error(\"failed to get OG tags\", \"err\", err)\n\t\t}\n\t}\n\n\ts.SetCookie(w, CookieOpts{\n\t\tValue: chall.ID,\n\t\tHost: r.Host,\n\t\tPath: \"/\",\n\t\tName: anubis.TestCookieName,\n\t\tExpiry: 30 * time.Minute,\n\t})\n\n\timpl, ok := challenge.Get(rule.Challenge.Algorithm)\n\tif !ok {\n\t\tlg.Error(\"check failed\", \"err\", \"can't get algorithm\", \"algorithm\", rule.Challenge.Algorithm)\n\t\ts.ClearCookie(w, CookieOpts{Name: anubis.TestCookieName, Host: r.Host})\n\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s: %s\", localizer.T(\"internal_server_error\"), rule.Challenge.Algorithm))\n\t\treturn\n\t}\n\n\tin := &challenge.IssueInput{\n\t\tImpressum: s.policy.Impressum,\n\t\tRule: rule,\n\t\tChallenge: chall,\n\t\tOGTags: ogTags,\n\t\tStore: s.store,\n\t}\n\n\tcomponent, err := impl.Issue(r, lg, in)\n\tif err != nil {\n\t\tlg.Error(\"[unexpected] render failed, please open an issue\", \"err\", err) // This is likely a bug in the template. Should never be triggered as CI tests for this.\n\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s \\\"RenderIndex\\\"\", localizer.T(\"internal_server_error\")))\n\t\treturn\n\t}\n\n\thandler := internal.GzipMiddleware(1, internal.NoStoreCache(templ.Handler(\n\t\tcomponent,\n\t\ttempl.WithStatus(s.opts.Policy.StatusCodes.Challenge),\n\t)))\n\thandler.ServeHTTP(w, r)\n}\n\nfunc (s *Server) RenderBench(w http.ResponseWriter, r *http.Request) {\n\tlocalizer := localization.GetLocalizer(r)\n\n\ttempl.Handler(\n\t\tweb.Base(localizer.T(\"benchmarking_anubis\"), web.Bench(localizer), s.policy.Impressum, localizer),\n\t).ServeHTTP(w, r)\n}\n\nfunc (s *Server) respondWithError(w http.ResponseWriter, r *http.Request, message string) {\n\ts.respondWithStatus(w, r, message, http.StatusInternalServerError)\n}\n\nfunc (s *Server) respondWithStatus(w http.ResponseWriter, r *http.Request, msg string, status int) {\n\tlocalizer := localization.GetLocalizer(r)\n\n\ttempl.Handler(web.Base(localizer.T(\"oh_noes\"), web.ErrorPage(msg, s.opts.WebmasterEmail, localizer), s.policy.Impressum, localizer), templ.WithStatus(status)).ServeHTTP(w, r)\n}\n\nfunc (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\ts.mux.ServeHTTP(w, r)\n}\n\nfunc (s *Server) stripBasePrefixFromRequest(r *http.Request) *http.Request {\n\tif !s.opts.StripBasePrefix || s.opts.BasePrefix == \"\" {\n\t\treturn r\n\t}\n\n\tbasePrefix := strings.TrimSuffix(s.opts.BasePrefix, \"/\")\n\tpath := r.URL.Path\n\n\tif !strings.HasPrefix(path, basePrefix) {\n\t\treturn r\n\t}\n\n\ttrimmedPath := strings.TrimPrefix(path, basePrefix)\n\tif trimmedPath == \"\" {\n\t\ttrimmedPath = \"/\"\n\t}\n\n\t// Clone the request and URL\n\treqCopy := r.Clone(r.Context())\n\turlCopy := *r.URL\n\turlCopy.Path = trimmedPath\n\treqCopy.URL = &urlCopy\n\n\treturn reqCopy\n}\n\nfunc (s *Server) ServeHTTPNext(w http.ResponseWriter, r *http.Request) {\n\tif s.next == nil {\n\t\tlocalizer := localization.GetLocalizer(r)\n\n\t\tredir := r.FormValue(\"redir\")\n\t\turlParsed, err := r.URL.Parse(redir)\n\t\tif err != nil {\n\t\t\ts.respondWithStatus(w, r, localizer.T(\"redirect_not_parseable\"), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tif (len(urlParsed.Host) > 0 && len(s.opts.RedirectDomains) != 0 && !slices.Contains(s.opts.RedirectDomains, urlParsed.Host)) || urlParsed.Host != r.URL.Host {\n\t\t\ts.respondWithStatus(w, r, localizer.T(\"redirect_domain_not_allowed\"), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tif redir != \"\" {\n\t\t\thttp.Redirect(w, r, redir, http.StatusFound)\n\t\t\treturn\n\t\t}\n\n\t\ttempl.Handler(\n\t\t\tweb.Base(localizer.T(\"you_are_not_a_bot\"), web.StaticHappy(localizer), s.policy.Impressum, localizer),\n\t\t).ServeHTTP(w, r)\n\t} else {\n\t\trequestsProxied.WithLabelValues(r.Host).Inc()\n\t\tr = s.stripBasePrefixFromRequest(r)\n\t\ts.next.ServeHTTP(w, r)\n\t}\n}\n\nfunc (s *Server) signJWT(claims jwt.MapClaims) (string, error) {\n\tclaims[\"iat\"] = time.Now().Unix()\n\tclaims[\"nbf\"] = time.Now().Add(-1 * time.Minute).Unix()\n\tclaims[\"exp\"] = time.Now().Add(s.opts.CookieExpiration).Unix()\n\n\tif len(s.hs512Secret) == 0 {\n\t\treturn jwt.NewWithClaims(jwt.SigningMethodEdDSA, claims).SignedString(s.ed25519Priv)\n\t} else {\n\t\treturn jwt.NewWithClaims(jwt.SigningMethodHS512, claims).SignedString(s.hs512Secret)\n\t}\n}\n"], ["/anubis/lib/anubis.go", "package lib\n\nimport (\n\t\"context\"\n\t\"crypto/ed25519\"\n\t\"crypto/rand\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"slices\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/golang-jwt/jwt/v5\"\n\t\"github.com/google/cel-go/common/types\"\n\t\"github.com/google/uuid\"\n\n\t\"github.com/prometheus/client_golang/prometheus\"\n\t\"github.com/prometheus/client_golang/prometheus/promauto\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/TecharoHQ/anubis/decaymap\"\n\t\"github.com/TecharoHQ/anubis/internal\"\n\t\"github.com/TecharoHQ/anubis/internal/dnsbl\"\n\t\"github.com/TecharoHQ/anubis/internal/ogtags\"\n\t\"github.com/TecharoHQ/anubis/lib/challenge\"\n\t\"github.com/TecharoHQ/anubis/lib/localization\"\n\t\"github.com/TecharoHQ/anubis/lib/policy\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/checker\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n\n\t// challenge implementations\n\t_ \"github.com/TecharoHQ/anubis/lib/challenge/metarefresh\"\n\t_ \"github.com/TecharoHQ/anubis/lib/challenge/proofofwork\"\n)\n\nvar (\n\tchallengesIssued = promauto.NewCounterVec(prometheus.CounterOpts{\n\t\tName: \"anubis_challenges_issued\",\n\t\tHelp: \"The total number of challenges issued\",\n\t}, []string{\"method\"})\n\n\tchallengesValidated = promauto.NewCounterVec(prometheus.CounterOpts{\n\t\tName: \"anubis_challenges_validated\",\n\t\tHelp: \"The total number of challenges validated\",\n\t}, []string{\"method\"})\n\n\tdroneBLHits = promauto.NewCounterVec(prometheus.CounterOpts{\n\t\tName: \"anubis_dronebl_hits\",\n\t\tHelp: \"The total number of hits from DroneBL\",\n\t}, []string{\"status\"})\n\n\tfailedValidations = promauto.NewCounterVec(prometheus.CounterOpts{\n\t\tName: \"anubis_failed_validations\",\n\t\tHelp: \"The total number of failed validations\",\n\t}, []string{\"method\"})\n\n\trequestsProxied = promauto.NewCounterVec(prometheus.CounterOpts{\n\t\tName: \"anubis_proxied_requests_total\",\n\t\tHelp: \"Number of requests proxied through Anubis to upstream targets\",\n\t}, []string{\"host\"})\n)\n\ntype Server struct {\n\tnext http.Handler\n\tmux *http.ServeMux\n\tpolicy *policy.ParsedConfig\n\tOGTags *ogtags.OGTagCache\n\ted25519Priv ed25519.PrivateKey\n\ths512Secret []byte\n\topts Options\n\tstore store.Interface\n}\n\nfunc (s *Server) getTokenKeyfunc() jwt.Keyfunc {\n\t// return ED25519 key if HS512 is not set\n\tif len(s.hs512Secret) == 0 {\n\t\treturn func(token *jwt.Token) (interface{}, error) {\n\t\t\treturn s.ed25519Priv.Public().(ed25519.PublicKey), nil\n\t\t}\n\t} else {\n\t\treturn func(token *jwt.Token) (interface{}, error) {\n\t\t\treturn s.hs512Secret, nil\n\t\t}\n\t}\n}\n\nfunc (s *Server) challengeFor(r *http.Request) (*challenge.Challenge, error) {\n\tckies := r.CookiesNamed(anubis.TestCookieName)\n\n\tif len(ckies) == 0 {\n\t\treturn s.issueChallenge(r.Context(), r)\n\t}\n\n\tj := store.JSON[challenge.Challenge]{Underlying: s.store}\n\n\tckie := ckies[0]\n\tchall, err := j.Get(r.Context(), \"challenge:\"+ckie.Value)\n\tif err != nil {\n\t\tif errors.Is(err, store.ErrNotFound) {\n\t\t\treturn s.issueChallenge(r.Context(), r)\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\treturn &chall, nil\n}\n\nfunc (s *Server) issueChallenge(ctx context.Context, r *http.Request) (*challenge.Challenge, error) {\n\tid, err := uuid.NewV7()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar randomData = make([]byte, 256)\n\tif _, err := rand.Read(randomData); err != nil {\n\t\treturn nil, err\n\t}\n\n\tchall := challenge.Challenge{\n\t\tID: id.String(),\n\t\tRandomData: fmt.Sprintf(\"%x\", randomData),\n\t\tIssuedAt: time.Now(),\n\t\tMetadata: map[string]string{\n\t\t\t\"User-Agent\": r.Header.Get(\"User-Agent\"),\n\t\t\t\"X-Real-Ip\": r.Header.Get(\"X-Real-Ip\"),\n\t\t},\n\t}\n\n\tj := store.JSON[challenge.Challenge]{Underlying: s.store}\n\tif err := j.Set(ctx, \"challenge:\"+id.String(), chall, 30*time.Minute); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &chall, err\n}\n\nfunc (s *Server) maybeReverseProxyHttpStatusOnly(w http.ResponseWriter, r *http.Request) {\n\ts.maybeReverseProxy(w, r, true)\n}\n\nfunc (s *Server) maybeReverseProxyOrPage(w http.ResponseWriter, r *http.Request) {\n\ts.maybeReverseProxy(w, r, false)\n}\n\nfunc (s *Server) maybeReverseProxy(w http.ResponseWriter, r *http.Request, httpStatusOnly bool) {\n\tlg := internal.GetRequestLogger(r)\n\n\t// Adjust cookie path if base prefix is not empty\n\tcookiePath := \"/\"\n\tif anubis.BasePrefix != \"\" {\n\t\tcookiePath = strings.TrimSuffix(anubis.BasePrefix, \"/\") + \"/\"\n\t}\n\n\tcr, rule, err := s.check(r)\n\tif err != nil {\n\t\tlg.Error(\"check failed\", \"err\", err)\n\t\tlocalizer := localization.GetLocalizer(r)\n\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s \\\"maybeReverseProxy\\\"\", localizer.T(\"internal_server_error\")))\n\t\treturn\n\t}\n\n\tr.Header.Add(\"X-Anubis-Rule\", cr.Name)\n\tr.Header.Add(\"X-Anubis-Action\", string(cr.Rule))\n\tlg = lg.With(\"check_result\", cr)\n\tpolicy.Applications.WithLabelValues(cr.Name, string(cr.Rule)).Add(1)\n\n\tip := r.Header.Get(\"X-Real-Ip\")\n\n\tif s.handleDNSBL(w, r, ip, lg) {\n\t\treturn\n\t}\n\n\tif s.checkRules(w, r, cr, lg, rule) {\n\t\treturn\n\t}\n\n\tckie, err := r.Cookie(anubis.CookieName)\n\tif err != nil {\n\t\tlg.Debug(\"cookie not found\", \"path\", r.URL.Path)\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.RenderIndex(w, r, rule, httpStatusOnly)\n\t\treturn\n\t}\n\n\tif err := ckie.Valid(); err != nil {\n\t\tlg.Debug(\"cookie is invalid\", \"err\", err)\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.RenderIndex(w, r, rule, httpStatusOnly)\n\t\treturn\n\t}\n\n\tif time.Now().After(ckie.Expires) && !ckie.Expires.IsZero() {\n\t\tlg.Debug(\"cookie expired\", \"path\", r.URL.Path)\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.RenderIndex(w, r, rule, httpStatusOnly)\n\t\treturn\n\t}\n\n\ttoken, err := jwt.ParseWithClaims(ckie.Value, jwt.MapClaims{}, s.getTokenKeyfunc(), jwt.WithExpirationRequired(), jwt.WithStrictDecoding())\n\n\tif err != nil || !token.Valid {\n\t\tlg.Debug(\"invalid token\", \"path\", r.URL.Path, \"err\", err)\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.RenderIndex(w, r, rule, httpStatusOnly)\n\t\treturn\n\t}\n\n\tclaims, ok := token.Claims.(jwt.MapClaims)\n\tif !ok {\n\t\tlg.Debug(\"invalid token claims type\", \"path\", r.URL.Path)\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.RenderIndex(w, r, rule, httpStatusOnly)\n\t\treturn\n\t}\n\n\tpolicyRule, ok := claims[\"policyRule\"].(string)\n\tif !ok {\n\t\tlg.Debug(\"policyRule claim is not a string\")\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.RenderIndex(w, r, rule, httpStatusOnly)\n\t\treturn\n\t}\n\n\tif policyRule != rule.Hash() {\n\t\tlg.Debug(\"user originally passed with a different rule, issuing new challenge\", \"old\", policyRule, \"new\", rule.Name)\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.RenderIndex(w, r, rule, httpStatusOnly)\n\t\treturn\n\t}\n\n\tr.Header.Add(\"X-Anubis-Status\", \"PASS\")\n\ts.ServeHTTPNext(w, r)\n}\n\nfunc (s *Server) checkRules(w http.ResponseWriter, r *http.Request, cr policy.CheckResult, lg *slog.Logger, rule *policy.Bot) bool {\n\t// Adjust cookie path if base prefix is not empty\n\tcookiePath := \"/\"\n\tif anubis.BasePrefix != \"\" {\n\t\tcookiePath = strings.TrimSuffix(anubis.BasePrefix, \"/\") + \"/\"\n\t}\n\n\tlocalizer := localization.GetLocalizer(r)\n\n\tswitch cr.Rule {\n\tcase config.RuleAllow:\n\t\tlg.Debug(\"allowing traffic to origin (explicit)\")\n\t\ts.ServeHTTPNext(w, r)\n\t\treturn true\n\tcase config.RuleDeny:\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\tlg.Info(\"explicit deny\")\n\t\tif rule == nil {\n\t\t\tlg.Error(\"rule is nil, cannot calculate checksum\")\n\t\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s \\\"maybeReverseProxy.RuleDeny\\\"\", localizer.T(\"internal_server_error\")))\n\t\t\treturn true\n\t\t}\n\t\thash := rule.Hash()\n\n\t\tlg.Debug(\"rule hash\", \"hash\", hash)\n\t\ts.respondWithStatus(w, r, fmt.Sprintf(\"%s %s\", localizer.T(\"access_denied\"), hash), s.policy.StatusCodes.Deny)\n\t\treturn true\n\tcase config.RuleChallenge:\n\t\tlg.Debug(\"challenge requested\")\n\tcase config.RuleBenchmark:\n\t\tlg.Debug(\"serving benchmark page\")\n\t\ts.RenderBench(w, r)\n\t\treturn true\n\tdefault:\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\tslog.Error(\"CONFIG ERROR: unknown rule\", \"rule\", cr.Rule)\n\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s \\\"maybeReverseProxy.Rules\\\"\", localizer.T(\"internal_server_error\")))\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (s *Server) handleDNSBL(w http.ResponseWriter, r *http.Request, ip string, lg *slog.Logger) bool {\n\tdb := &store.JSON[dnsbl.DroneBLResponse]{Underlying: s.store, Prefix: \"dronebl:\"}\n\tif s.policy.DNSBL && ip != \"\" {\n\t\tresp, err := db.Get(r.Context(), ip)\n\t\tif err != nil {\n\t\t\tlg.Debug(\"looking up ip in dnsbl\")\n\t\t\tresp, err := dnsbl.Lookup(ip)\n\t\t\tif err != nil {\n\t\t\t\tlg.Error(\"can't look up ip in dnsbl\", \"err\", err)\n\t\t\t}\n\t\t\tdb.Set(r.Context(), ip, resp, 24*time.Hour)\n\t\t\tdroneBLHits.WithLabelValues(resp.String()).Inc()\n\t\t}\n\n\t\tif resp != dnsbl.AllGood {\n\t\t\tlg.Info(\"DNSBL hit\", \"status\", resp.String())\n\t\t\tlocalizer := localization.GetLocalizer(r)\n\t\t\ts.respondWithStatus(w, r, fmt.Sprintf(\"%s: %s, %s https://dronebl.org/lookup?ip=%s\",\n\t\t\t\tlocalizer.T(\"dronebl_entry\"),\n\t\t\t\tresp.String(),\n\t\t\t\tlocalizer.T(\"see_dronebl_lookup\"),\n\t\t\t\tip), s.policy.StatusCodes.Deny)\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (s *Server) MakeChallenge(w http.ResponseWriter, r *http.Request) {\n\tlg := internal.GetRequestLogger(r)\n\tlocalizer := localization.GetLocalizer(r)\n\n\tredir := r.FormValue(\"redir\")\n\tif redir == \"\" {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tencoder := json.NewEncoder(w)\n\t\tlg.Error(\"invalid invocation of MakeChallenge\", \"redir\", redir)\n\t\tencoder.Encode(struct {\n\t\t\tError string `json:\"error\"`\n\t\t}{\n\t\t\tError: localizer.T(\"invalid_invocation\"),\n\t\t})\n\t\treturn\n\t}\n\n\tr.URL.Path = redir\n\n\tencoder := json.NewEncoder(w)\n\tcr, rule, err := s.check(r)\n\tif err != nil {\n\t\tlg.Error(\"check failed\", \"err\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\terr := encoder.Encode(struct {\n\t\t\tError string `json:\"error\"`\n\t\t}{\n\t\t\tError: fmt.Sprintf(\"%s \\\"makeChallenge\\\"\", localizer.T(\"internal_server_error\")),\n\t\t})\n\t\tif err != nil {\n\t\t\tlg.Error(\"failed to encode error response\", \"err\", err)\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t}\n\t\treturn\n\t}\n\tlg = lg.With(\"check_result\", cr)\n\n\tchall, err := s.challengeFor(r)\n\tif err != nil {\n\t\tlg.Error(\"failed to fetch or issue challenge\", \"err\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\terr := encoder.Encode(struct {\n\t\t\tError string `json:\"error\"`\n\t\t}{\n\t\t\tError: fmt.Sprintf(\"%s \\\"makeChallenge\\\"\", localizer.T(\"internal_server_error\")),\n\t\t})\n\t\tif err != nil {\n\t\t\tlg.Error(\"failed to encode error response\", \"err\", err)\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t}\n\t\treturn\n\t}\n\n\ts.SetCookie(w, CookieOpts{Host: r.Host, Name: anubis.TestCookieName, Value: chall.ID})\n\n\terr = encoder.Encode(struct {\n\t\tRules *config.ChallengeRules `json:\"rules\"`\n\t\tChallenge string `json:\"challenge\"`\n\t}{\n\t\tChallenge: chall.RandomData,\n\t\tRules: rule.Challenge,\n\t})\n\tif err != nil {\n\t\tlg.Error(\"failed to encode challenge\", \"err\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\tlg.Debug(\"made challenge\", \"challenge\", chall, \"rules\", rule.Challenge, \"cr\", cr)\n\tchallengesIssued.WithLabelValues(\"api\").Inc()\n}\n\nfunc (s *Server) PassChallenge(w http.ResponseWriter, r *http.Request) {\n\tlg := internal.GetRequestLogger(r)\n\tlocalizer := localization.GetLocalizer(r)\n\n\tredir := r.FormValue(\"redir\")\n\tredirURL, err := url.ParseRequestURI(redir)\n\tif err != nil {\n\t\tlg.Error(\"invalid redirect\", \"err\", err)\n\t\ts.respondWithStatus(w, r, localizer.T(\"invalid_redirect\"), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tswitch redirURL.Scheme {\n\tcase \"\", \"http\", \"https\":\n\t\t// allowed\n\tdefault:\n\t\tlg.Error(\"XSS attempt blocked, invalid redirect scheme\", \"scheme\", redirURL.Scheme)\n\t\ts.respondWithStatus(w, r, localizer.T(\"invalid_redirect\"), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// Adjust cookie path if base prefix is not empty\n\tcookiePath := \"/\"\n\tif anubis.BasePrefix != \"\" {\n\t\tcookiePath = strings.TrimSuffix(anubis.BasePrefix, \"/\") + \"/\"\n\t}\n\n\tif _, err := r.Cookie(anubis.TestCookieName); errors.Is(err, http.ErrNoCookie) {\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.ClearCookie(w, CookieOpts{Name: anubis.TestCookieName, Host: r.Host})\n\t\tlg.Warn(\"user has cookies disabled, this is not an anubis bug\")\n\t\ts.respondWithError(w, r, localizer.T(\"cookies_disabled\"))\n\t\treturn\n\t}\n\n\t// used by the path checker rule\n\tr.URL = redirURL\n\n\turlParsed, err := r.URL.Parse(redir)\n\tif err != nil {\n\t\ts.respondWithError(w, r, localizer.T(\"redirect_not_parseable\"))\n\t\treturn\n\t}\n\tif (len(urlParsed.Host) > 0 && len(s.opts.RedirectDomains) != 0 && !slices.Contains(s.opts.RedirectDomains, urlParsed.Host)) || urlParsed.Host != r.URL.Host {\n\t\ts.respondWithError(w, r, localizer.T(\"redirect_domain_not_allowed\"))\n\t\treturn\n\t}\n\n\tcr, rule, err := s.check(r)\n\tif err != nil {\n\t\tlg.Error(\"check failed\", \"err\", err)\n\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s \\\"passChallenge\\\"\", localizer.T(\"internal_server_error\")))\n\t\treturn\n\t}\n\tlg = lg.With(\"check_result\", cr)\n\n\timpl, ok := challenge.Get(rule.Challenge.Algorithm)\n\tif !ok {\n\t\tlg.Error(\"check failed\", \"err\", err)\n\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s: %s\", localizer.T(\"internal_server_error\"), rule.Challenge.Algorithm))\n\t\treturn\n\t}\n\n\tchall, err := s.challengeFor(r)\n\tif err != nil {\n\t\tlg.Error(\"check failed\", \"err\", err)\n\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s: %s\", localizer.T(\"internal_server_error\"), rule.Challenge.Algorithm))\n\t\treturn\n\t}\n\n\tin := &challenge.ValidateInput{\n\t\tChallenge: chall,\n\t\tRule: rule,\n\t\tStore: s.store,\n\t}\n\n\tif err := impl.Validate(r, lg, in); err != nil {\n\t\tfailedValidations.WithLabelValues(rule.Challenge.Algorithm).Inc()\n\t\tvar cerr *challenge.Error\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\tlg.Debug(\"challenge validate call failed\", \"err\", err)\n\n\t\tswitch {\n\t\tcase errors.As(err, &cerr):\n\t\t\tswitch {\n\t\t\tcase errors.Is(err, challenge.ErrFailed):\n\t\t\t\ts.respondWithStatus(w, r, cerr.PublicReason, cerr.StatusCode)\n\t\t\tcase errors.Is(err, challenge.ErrInvalidFormat), errors.Is(err, challenge.ErrMissingField):\n\t\t\t\ts.respondWithError(w, r, cerr.PublicReason)\n\t\t\t}\n\t\t}\n\t}\n\n\t// generate JWT cookie\n\ttokenString, err := s.signJWT(jwt.MapClaims{\n\t\t\"challenge\": chall.ID,\n\t\t\"method\": rule.Challenge.Algorithm,\n\t\t\"policyRule\": rule.Hash(),\n\t\t\"action\": string(cr.Rule),\n\t})\n\tif err != nil {\n\t\tlg.Error(\"failed to sign JWT\", \"err\", err)\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.respondWithError(w, r, localizer.T(\"failed_to_sign_jwt\"))\n\t\treturn\n\t}\n\n\ts.SetCookie(w, CookieOpts{Path: cookiePath, Host: r.Host, Value: tokenString})\n\n\tchallengesValidated.WithLabelValues(rule.Challenge.Algorithm).Inc()\n\tlg.Debug(\"challenge passed, redirecting to app\")\n\thttp.Redirect(w, r, redir, http.StatusFound)\n}\n\nfunc cr(name string, rule config.Rule, weight int) policy.CheckResult {\n\treturn policy.CheckResult{\n\t\tName: name,\n\t\tRule: rule,\n\t\tWeight: weight,\n\t}\n}\n\n// Check evaluates the list of rules, and returns the result\nfunc (s *Server) check(r *http.Request) (policy.CheckResult, *policy.Bot, error) {\n\thost := r.Header.Get(\"X-Real-Ip\")\n\tif host == \"\" {\n\t\treturn decaymap.Zilch[policy.CheckResult](), nil, fmt.Errorf(\"[misconfiguration] X-Real-Ip header is not set\")\n\t}\n\n\taddr := net.ParseIP(host)\n\tif addr == nil {\n\t\treturn decaymap.Zilch[policy.CheckResult](), nil, fmt.Errorf(\"[misconfiguration] %q is not an IP address\", host)\n\t}\n\n\tweight := 0\n\n\tfor _, b := range s.policy.Bots {\n\t\tmatch, err := b.Rules.Check(r)\n\t\tif err != nil {\n\t\t\treturn decaymap.Zilch[policy.CheckResult](), nil, fmt.Errorf(\"can't run check %s: %w\", b.Name, err)\n\t\t}\n\n\t\tif match {\n\t\t\tswitch b.Action {\n\t\t\tcase config.RuleDeny, config.RuleAllow, config.RuleBenchmark, config.RuleChallenge:\n\t\t\t\treturn cr(\"bot/\"+b.Name, b.Action, weight), &b, nil\n\t\t\tcase config.RuleWeigh:\n\t\t\t\tslog.Debug(\"adjusting weight\", \"name\", b.Name, \"delta\", b.Weight.Adjust)\n\t\t\t\tweight += b.Weight.Adjust\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, t := range s.policy.Thresholds {\n\t\tresult, _, err := t.Program.ContextEval(r.Context(), &policy.ThresholdRequest{Weight: weight})\n\t\tif err != nil {\n\t\t\tslog.Error(\"error when evaluating threshold expression\", \"expression\", t.Expression.String(), \"err\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tvar matches bool\n\n\t\tif val, ok := result.(types.Bool); ok {\n\t\t\tmatches = bool(val)\n\t\t}\n\n\t\tif matches {\n\t\t\treturn cr(\"threshold/\"+t.Name, t.Action, weight), &policy.Bot{\n\t\t\t\tChallenge: t.Challenge,\n\t\t\t\tRules: &checker.List{},\n\t\t\t}, nil\n\t\t}\n\t}\n\n\treturn cr(\"default/allow\", config.RuleAllow, weight), &policy.Bot{\n\t\tChallenge: &config.ChallengeRules{\n\t\t\tDifficulty: s.policy.DefaultDifficulty,\n\t\t\tReportAs: s.policy.DefaultDifficulty,\n\t\t\tAlgorithm: config.DefaultAlgorithm,\n\t\t},\n\t\tRules: &checker.List{},\n\t}, nil\n}\n"], ["/anubis/lib/policy/policy.go", "package policy\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log/slog\"\n\t\"sync/atomic\"\n\n\t\"github.com/TecharoHQ/anubis/lib/policy/checker\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n\t\"github.com/TecharoHQ/anubis/lib/thoth\"\n\t\"github.com/prometheus/client_golang/prometheus\"\n\t\"github.com/prometheus/client_golang/prometheus/promauto\"\n\n\t_ \"github.com/TecharoHQ/anubis/lib/store/all\"\n)\n\nvar (\n\tApplications = promauto.NewCounterVec(prometheus.CounterOpts{\n\t\tName: \"anubis_policy_results\",\n\t\tHelp: \"The results of each policy rule\",\n\t}, []string{\"rule\", \"action\"})\n\n\tErrChallengeRuleHasWrongAlgorithm = errors.New(\"config.Bot.ChallengeRules: algorithm is invalid\")\n\twarnedAboutThresholds = &atomic.Bool{}\n)\n\ntype ParsedConfig struct {\n\torig *config.Config\n\n\tBots []Bot\n\tThresholds []*Threshold\n\tDNSBL bool\n\tImpressum *config.Impressum\n\tOpenGraph config.OpenGraph\n\tDefaultDifficulty int\n\tStatusCodes config.StatusCodes\n\tStore store.Interface\n}\n\nfunc newParsedConfig(orig *config.Config) *ParsedConfig {\n\treturn &ParsedConfig{\n\t\torig: orig,\n\t\tOpenGraph: orig.OpenGraph,\n\t\tStatusCodes: orig.StatusCodes,\n\t}\n}\n\nfunc ParseConfig(ctx context.Context, fin io.Reader, fname string, defaultDifficulty int) (*ParsedConfig, error) {\n\tc, err := config.Load(fin, fname)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar validationErrs []error\n\n\ttc, hasThothClient := thoth.FromContext(ctx)\n\n\tresult := newParsedConfig(c)\n\tresult.DefaultDifficulty = defaultDifficulty\n\n\tfor _, b := range c.Bots {\n\t\tif berr := b.Valid(); berr != nil {\n\t\t\tvalidationErrs = append(validationErrs, berr)\n\t\t\tcontinue\n\t\t}\n\n\t\tparsedBot := Bot{\n\t\t\tName: b.Name,\n\t\t\tAction: b.Action,\n\t\t}\n\n\t\tcl := checker.List{}\n\n\t\tif len(b.RemoteAddr) > 0 {\n\t\t\tc, err := NewRemoteAddrChecker(b.RemoteAddr)\n\t\t\tif err != nil {\n\t\t\t\tvalidationErrs = append(validationErrs, fmt.Errorf(\"while processing rule %s remote addr set: %w\", b.Name, err))\n\t\t\t} else {\n\t\t\t\tcl = append(cl, c)\n\t\t\t}\n\t\t}\n\n\t\tif b.UserAgentRegex != nil {\n\t\t\tc, err := NewUserAgentChecker(*b.UserAgentRegex)\n\t\t\tif err != nil {\n\t\t\t\tvalidationErrs = append(validationErrs, fmt.Errorf(\"while processing rule %s user agent regex: %w\", b.Name, err))\n\t\t\t} else {\n\t\t\t\tcl = append(cl, c)\n\t\t\t}\n\t\t}\n\n\t\tif b.PathRegex != nil {\n\t\t\tc, err := NewPathChecker(*b.PathRegex)\n\t\t\tif err != nil {\n\t\t\t\tvalidationErrs = append(validationErrs, fmt.Errorf(\"while processing rule %s path regex: %w\", b.Name, err))\n\t\t\t} else {\n\t\t\t\tcl = append(cl, c)\n\t\t\t}\n\t\t}\n\n\t\tif len(b.HeadersRegex) > 0 {\n\t\t\tc, err := NewHeadersChecker(b.HeadersRegex)\n\t\t\tif err != nil {\n\t\t\t\tvalidationErrs = append(validationErrs, fmt.Errorf(\"while processing rule %s headers regex map: %w\", b.Name, err))\n\t\t\t} else {\n\t\t\t\tcl = append(cl, c)\n\t\t\t}\n\t\t}\n\n\t\tif b.Expression != nil {\n\t\t\tc, err := NewCELChecker(b.Expression)\n\t\t\tif err != nil {\n\t\t\t\tvalidationErrs = append(validationErrs, fmt.Errorf(\"while processing rule %s expressions: %w\", b.Name, err))\n\t\t\t} else {\n\t\t\t\tcl = append(cl, c)\n\t\t\t}\n\t\t}\n\n\t\tif b.ASNs != nil {\n\t\t\tif !hasThothClient {\n\t\t\t\tslog.Warn(\"You have specified a Thoth specific check but you have no Thoth client configured. Please read https://anubis.techaro.lol/docs/admin/thoth for more information\", \"check\", \"asn\", \"settings\", b.ASNs)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tcl = append(cl, tc.ASNCheckerFor(b.ASNs.Match))\n\t\t}\n\n\t\tif b.GeoIP != nil {\n\t\t\tif !hasThothClient {\n\t\t\t\tslog.Warn(\"You have specified a Thoth specific check but you have no Thoth client configured. Please read https://anubis.techaro.lol/docs/admin/thoth for more information\", \"check\", \"geoip\", \"settings\", b.GeoIP)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tcl = append(cl, tc.GeoIPCheckerFor(b.GeoIP.Countries))\n\t\t}\n\n\t\tif b.Challenge == nil {\n\t\t\tparsedBot.Challenge = &config.ChallengeRules{\n\t\t\t\tDifficulty: defaultDifficulty,\n\t\t\t\tReportAs: defaultDifficulty,\n\t\t\t\tAlgorithm: \"fast\",\n\t\t\t}\n\t\t} else {\n\t\t\tparsedBot.Challenge = b.Challenge\n\t\t\tif parsedBot.Challenge.Algorithm == \"\" {\n\t\t\t\tparsedBot.Challenge.Algorithm = config.DefaultAlgorithm\n\t\t\t}\n\t\t}\n\n\t\tif b.Weight != nil {\n\t\t\tparsedBot.Weight = b.Weight\n\t\t}\n\n\t\tresult.Impressum = c.Impressum\n\n\t\tparsedBot.Rules = cl\n\n\t\tresult.Bots = append(result.Bots, parsedBot)\n\t}\n\n\tfor _, t := range c.Thresholds {\n\t\tif t.Name == \"legacy-anubis-behaviour\" && t.Expression.String() == \"true\" {\n\t\t\tif !warnedAboutThresholds.Load() {\n\t\t\t\tslog.Warn(\"configuration file does not contain thresholds, see docs for details on how to upgrade\", \"fname\", fname, \"docs_url\", \"https://anubis.techaro.lol/docs/admin/configuration/thresholds/\")\n\t\t\t\twarnedAboutThresholds.Store(true)\n\t\t\t}\n\n\t\t\tt.Challenge.Difficulty = defaultDifficulty\n\t\t\tt.Challenge.ReportAs = defaultDifficulty\n\t\t}\n\n\t\tthreshold, err := ParsedThresholdFromConfig(t)\n\t\tif err != nil {\n\t\t\tvalidationErrs = append(validationErrs, fmt.Errorf(\"can't compile threshold config for %s: %w\", t.Name, err))\n\t\t\tcontinue\n\t\t}\n\n\t\tresult.Thresholds = append(result.Thresholds, threshold)\n\t}\n\n\tstFac, ok := store.Get(c.Store.Backend)\n\tswitch ok {\n\tcase true:\n\t\tstore, err := stFac.Build(ctx, c.Store.Parameters)\n\t\tif err != nil {\n\t\t\tvalidationErrs = append(validationErrs, err)\n\t\t} else {\n\t\t\tresult.Store = store\n\t\t}\n\tcase false:\n\t\tvalidationErrs = append(validationErrs, config.ErrUnknownStoreBackend)\n\t}\n\n\tif len(validationErrs) > 0 {\n\t\treturn nil, fmt.Errorf(\"errors validating policy config JSON %s: %w\", fname, errors.Join(validationErrs...))\n\t}\n\n\tresult.DNSBL = c.DNSBL\n\n\treturn result, nil\n}\n"], ["/anubis/lib/policy/config/config.go", "package config\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/fs\"\n\t\"net\"\n\t\"net/http\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis/data\"\n\t\"k8s.io/apimachinery/pkg/util/yaml\"\n)\n\nvar (\n\tErrNoBotRulesDefined = errors.New(\"config: must define at least one (1) bot rule\")\n\tErrBotMustHaveName = errors.New(\"config.Bot: must set name\")\n\tErrBotMustHaveUserAgentOrPath = errors.New(\"config.Bot: must set either user_agent_regex, path_regex, headers_regex, or remote_addresses\")\n\tErrBotMustHaveUserAgentOrPathNotBoth = errors.New(\"config.Bot: must set either user_agent_regex, path_regex, and not both\")\n\tErrUnknownAction = errors.New(\"config.Bot: unknown action\")\n\tErrInvalidUserAgentRegex = errors.New(\"config.Bot: invalid user agent regex\")\n\tErrInvalidPathRegex = errors.New(\"config.Bot: invalid path regex\")\n\tErrInvalidHeadersRegex = errors.New(\"config.Bot: invalid headers regex\")\n\tErrInvalidCIDR = errors.New(\"config.Bot: invalid CIDR\")\n\tErrRegexEndsWithNewline = errors.New(\"config.Bot: regular expression ends with newline (try >- instead of > in yaml)\")\n\tErrInvalidImportStatement = errors.New(\"config.ImportStatement: invalid source file\")\n\tErrCantSetBotAndImportValuesAtOnce = errors.New(\"config.BotOrImport: can't set bot rules and import values at the same time\")\n\tErrMustSetBotOrImportRules = errors.New(\"config.BotOrImport: rule definition is invalid, you must set either bot rules or an import statement, not both\")\n\tErrStatusCodeNotValid = errors.New(\"config.StatusCode: status code not valid, must be between 100 and 599\")\n)\n\ntype Rule string\n\nconst (\n\tRuleUnknown Rule = \"\"\n\tRuleAllow Rule = \"ALLOW\"\n\tRuleDeny Rule = \"DENY\"\n\tRuleChallenge Rule = \"CHALLENGE\"\n\tRuleWeigh Rule = \"WEIGH\"\n\tRuleBenchmark Rule = \"DEBUG_BENCHMARK\"\n)\n\nfunc (r Rule) Valid() error {\n\tswitch r {\n\tcase RuleAllow, RuleDeny, RuleChallenge, RuleWeigh, RuleBenchmark:\n\t\treturn nil\n\tdefault:\n\t\treturn ErrUnknownAction\n\t}\n}\n\nconst DefaultAlgorithm = \"fast\"\n\ntype BotConfig struct {\n\tUserAgentRegex *string `json:\"user_agent_regex,omitempty\" yaml:\"user_agent_regex,omitempty\"`\n\tPathRegex *string `json:\"path_regex,omitempty\" yaml:\"path_regex,omitempty\"`\n\tHeadersRegex map[string]string `json:\"headers_regex,omitempty\" yaml:\"headers_regex,omitempty\"`\n\tExpression *ExpressionOrList `json:\"expression,omitempty\" yaml:\"expression,omitempty\"`\n\tChallenge *ChallengeRules `json:\"challenge,omitempty\" yaml:\"challenge,omitempty\"`\n\tWeight *Weight `json:\"weight,omitempty\" yaml:\"weight,omitempty\"`\n\tName string `json:\"name\" yaml:\"name\"`\n\tAction Rule `json:\"action\" yaml:\"action\"`\n\tRemoteAddr []string `json:\"remote_addresses,omitempty\" yaml:\"remote_addresses,omitempty\"`\n\n\t// Thoth features\n\tGeoIP *GeoIP `json:\"geoip,omitempty\"`\n\tASNs *ASNs `json:\"asns,omitempty\"`\n}\n\nfunc (b BotConfig) Zero() bool {\n\tfor _, cond := range []bool{\n\t\tb.Name != \"\",\n\t\tb.UserAgentRegex != nil,\n\t\tb.PathRegex != nil,\n\t\tlen(b.HeadersRegex) != 0,\n\t\tb.Action != \"\",\n\t\tlen(b.RemoteAddr) != 0,\n\t\tb.Challenge != nil,\n\t\tb.GeoIP != nil,\n\t\tb.ASNs != nil,\n\t} {\n\t\tif cond {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc (b *BotConfig) Valid() error {\n\tvar errs []error\n\n\tif b.Name == \"\" {\n\t\terrs = append(errs, ErrBotMustHaveName)\n\t}\n\n\tallFieldsEmpty := b.UserAgentRegex == nil &&\n\t\tb.PathRegex == nil &&\n\t\tlen(b.RemoteAddr) == 0 &&\n\t\tlen(b.HeadersRegex) == 0 &&\n\t\tb.ASNs == nil &&\n\t\tb.GeoIP == nil\n\n\tif allFieldsEmpty && b.Expression == nil {\n\t\terrs = append(errs, ErrBotMustHaveUserAgentOrPath)\n\t}\n\n\tif b.UserAgentRegex != nil && b.PathRegex != nil {\n\t\terrs = append(errs, ErrBotMustHaveUserAgentOrPathNotBoth)\n\t}\n\n\tif b.UserAgentRegex != nil {\n\t\tif strings.HasSuffix(*b.UserAgentRegex, \"\\n\") {\n\t\t\terrs = append(errs, fmt.Errorf(\"%w: user agent regex: %q\", ErrRegexEndsWithNewline, *b.UserAgentRegex))\n\t\t}\n\n\t\tif _, err := regexp.Compile(*b.UserAgentRegex); err != nil {\n\t\t\terrs = append(errs, ErrInvalidUserAgentRegex, err)\n\t\t}\n\t}\n\n\tif b.PathRegex != nil {\n\t\tif strings.HasSuffix(*b.PathRegex, \"\\n\") {\n\t\t\terrs = append(errs, fmt.Errorf(\"%w: path regex: %q\", ErrRegexEndsWithNewline, *b.PathRegex))\n\t\t}\n\n\t\tif _, err := regexp.Compile(*b.PathRegex); err != nil {\n\t\t\terrs = append(errs, ErrInvalidPathRegex, err)\n\t\t}\n\t}\n\n\tif len(b.HeadersRegex) > 0 {\n\t\tfor name, expr := range b.HeadersRegex {\n\t\t\tif name == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif strings.HasSuffix(expr, \"\\n\") {\n\t\t\t\terrs = append(errs, fmt.Errorf(\"%w: header %s regex: %q\", ErrRegexEndsWithNewline, name, expr))\n\t\t\t}\n\n\t\t\tif _, err := regexp.Compile(expr); err != nil {\n\t\t\t\terrs = append(errs, ErrInvalidHeadersRegex, err)\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(b.RemoteAddr) > 0 {\n\t\tfor _, cidr := range b.RemoteAddr {\n\t\t\tif _, _, err := net.ParseCIDR(cidr); err != nil {\n\t\t\t\terrs = append(errs, ErrInvalidCIDR, err)\n\t\t\t}\n\t\t}\n\t}\n\n\tif b.Expression != nil {\n\t\tif err := b.Expression.Valid(); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\tswitch b.Action {\n\tcase RuleAllow, RuleBenchmark, RuleChallenge, RuleDeny, RuleWeigh:\n\t\t// okay\n\tdefault:\n\t\terrs = append(errs, fmt.Errorf(\"%w: %q\", ErrUnknownAction, b.Action))\n\t}\n\n\tif b.Action == RuleChallenge && b.Challenge != nil {\n\t\tif err := b.Challenge.Valid(); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\tif b.Action == RuleWeigh && b.Weight == nil {\n\t\tb.Weight = &Weight{Adjust: 5}\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"config: bot entry for %q is not valid:\\n%w\", b.Name, errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n\ntype ChallengeRules struct {\n\tAlgorithm string `json:\"algorithm,omitempty\" yaml:\"algorithm,omitempty\"`\n\tDifficulty int `json:\"difficulty,omitempty\" yaml:\"difficulty,omitempty\"`\n\tReportAs int `json:\"report_as,omitempty\" yaml:\"report_as,omitempty\"`\n}\n\nvar (\n\tErrChallengeDifficultyTooLow = errors.New(\"config.ChallengeRules: difficulty is too low (must be >= 1)\")\n\tErrChallengeDifficultyTooHigh = errors.New(\"config.ChallengeRules: difficulty is too high (must be <= 64)\")\n\tErrChallengeMustHaveAlgorithm = errors.New(\"config.ChallengeRules: must have algorithm name set\")\n)\n\nfunc (cr ChallengeRules) Valid() error {\n\tvar errs []error\n\n\tif cr.Algorithm == \"\" {\n\t\terrs = append(errs, ErrChallengeMustHaveAlgorithm)\n\t}\n\n\tif cr.Difficulty < 1 {\n\t\terrs = append(errs, fmt.Errorf(\"%w, got: %d\", ErrChallengeDifficultyTooLow, cr.Difficulty))\n\t}\n\n\tif cr.Difficulty > 64 {\n\t\terrs = append(errs, fmt.Errorf(\"%w, got: %d\", ErrChallengeDifficultyTooHigh, cr.Difficulty))\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"config: challenge rules entry is not valid:\\n%w\", errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n\ntype ImportStatement struct {\n\tImport string `json:\"import\"`\n\tBots []BotConfig\n}\n\nfunc (is *ImportStatement) open() (fs.File, error) {\n\tif strings.HasPrefix(is.Import, \"(data)/\") {\n\t\tfname := strings.TrimPrefix(is.Import, \"(data)/\")\n\t\tfin, err := data.BotPolicies.Open(fname)\n\t\treturn fin, err\n\t}\n\n\treturn os.Open(is.Import)\n}\n\nfunc (is *ImportStatement) load() error {\n\tfin, err := is.open()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%w: %s: %w\", ErrInvalidImportStatement, is.Import, err)\n\t}\n\tdefer fin.Close()\n\n\tvar imported []BotOrImport\n\tvar result []BotConfig\n\n\tif err := yaml.NewYAMLToJSONDecoder(fin).Decode(&imported); err != nil {\n\t\treturn fmt.Errorf(\"can't parse %s: %w\", is.Import, err)\n\t}\n\n\tvar errs []error\n\n\tfor _, b := range imported {\n\t\tif err := b.Valid(); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\n\t\tif b.ImportStatement != nil {\n\t\t\tresult = append(result, b.ImportStatement.Bots...)\n\t\t}\n\n\t\tif b.BotConfig != nil {\n\t\t\tresult = append(result, *b.BotConfig)\n\t\t}\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"config %s is not valid:\\n%w\", is.Import, errors.Join(errs...))\n\t}\n\n\tis.Bots = result\n\n\treturn nil\n}\n\nfunc (is *ImportStatement) Valid() error {\n\treturn is.load()\n}\n\ntype BotOrImport struct {\n\t*BotConfig `json:\",inline\"`\n\t*ImportStatement `json:\",inline\"`\n}\n\nfunc (boi *BotOrImport) Valid() error {\n\tif boi.BotConfig != nil && boi.ImportStatement != nil {\n\t\treturn ErrCantSetBotAndImportValuesAtOnce\n\t}\n\n\tif boi.BotConfig != nil {\n\t\treturn boi.BotConfig.Valid()\n\t}\n\n\tif boi.ImportStatement != nil {\n\t\treturn boi.ImportStatement.Valid()\n\t}\n\n\treturn ErrMustSetBotOrImportRules\n}\n\ntype StatusCodes struct {\n\tChallenge int `json:\"CHALLENGE\"`\n\tDeny int `json:\"DENY\"`\n}\n\nfunc (sc StatusCodes) Valid() error {\n\tvar errs []error\n\n\tif sc.Challenge == 0 || (sc.Challenge < 100 && sc.Challenge >= 599) {\n\t\terrs = append(errs, fmt.Errorf(\"%w: challenge is %d\", ErrStatusCodeNotValid, sc.Challenge))\n\t}\n\n\tif sc.Deny == 0 || (sc.Deny < 100 && sc.Deny >= 599) {\n\t\terrs = append(errs, fmt.Errorf(\"%w: deny is %d\", ErrStatusCodeNotValid, sc.Deny))\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"status codes not valid:\\n%w\", errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n\ntype fileConfig struct {\n\tBots []BotOrImport `json:\"bots\"`\n\tDNSBL bool `json:\"dnsbl\"`\n\tOpenGraph openGraphFileConfig `json:\"openGraph,omitempty\"`\n\tImpressum *Impressum `json:\"impressum,omitempty\"`\n\tStatusCodes StatusCodes `json:\"status_codes\"`\n\tStore *Store `json:\"store\"`\n\tThresholds []Threshold `json:\"thresholds\"`\n}\n\nfunc (c *fileConfig) Valid() error {\n\tvar errs []error\n\n\tif len(c.Bots) == 0 {\n\t\terrs = append(errs, ErrNoBotRulesDefined)\n\t}\n\n\tfor i, b := range c.Bots {\n\t\tif err := b.Valid(); err != nil {\n\t\t\terrs = append(errs, fmt.Errorf(\"bot %d: %w\", i, err))\n\t\t}\n\t}\n\n\tif c.OpenGraph.Enabled {\n\t\tif err := c.OpenGraph.Valid(); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\tif err := c.StatusCodes.Valid(); err != nil {\n\t\terrs = append(errs, err)\n\t}\n\n\tfor i, t := range c.Thresholds {\n\t\tif err := t.Valid(); err != nil {\n\t\t\terrs = append(errs, fmt.Errorf(\"threshold %d: %w\", i, err))\n\t\t}\n\t}\n\n\tif c.Store != nil {\n\t\tif err := c.Store.Valid(); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"config is not valid:\\n%w\", errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n\nfunc Load(fin io.Reader, fname string) (*Config, error) {\n\tc := &fileConfig{\n\t\tStatusCodes: StatusCodes{\n\t\t\tChallenge: http.StatusOK,\n\t\t\tDeny: http.StatusOK,\n\t\t},\n\t\tStore: &Store{\n\t\t\tBackend: \"memory\",\n\t\t},\n\t}\n\n\tif err := yaml.NewYAMLToJSONDecoder(fin).Decode(&c); err != nil {\n\t\treturn nil, fmt.Errorf(\"can't parse policy config YAML %s: %w\", fname, err)\n\t}\n\n\tif err := c.Valid(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult := &Config{\n\t\tDNSBL: c.DNSBL,\n\t\tOpenGraph: OpenGraph{\n\t\t\tEnabled: c.OpenGraph.Enabled,\n\t\t\tConsiderHost: c.OpenGraph.ConsiderHost,\n\t\t\tOverride: c.OpenGraph.Override,\n\t\t},\n\t\tStatusCodes: c.StatusCodes,\n\t\tStore: c.Store,\n\t}\n\n\tif c.OpenGraph.TimeToLive != \"\" {\n\t\t// XXX(Xe): already validated in Valid()\n\t\togTTL, _ := time.ParseDuration(c.OpenGraph.TimeToLive)\n\t\tresult.OpenGraph.TimeToLive = ogTTL\n\t}\n\n\tvar validationErrs []error\n\n\tfor _, boi := range c.Bots {\n\t\tif boi.ImportStatement != nil {\n\t\t\tif err := boi.load(); err != nil {\n\t\t\t\tvalidationErrs = append(validationErrs, err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tresult.Bots = append(result.Bots, boi.ImportStatement.Bots...)\n\t\t}\n\n\t\tif boi.BotConfig != nil {\n\t\t\tif err := boi.BotConfig.Valid(); err != nil {\n\t\t\t\tvalidationErrs = append(validationErrs, err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tresult.Bots = append(result.Bots, *boi.BotConfig)\n\t\t}\n\t}\n\n\tif c.Impressum != nil {\n\t\tif err := c.Impressum.Valid(); err != nil {\n\t\t\tvalidationErrs = append(validationErrs, err)\n\t\t}\n\n\t\tresult.Impressum = c.Impressum\n\t}\n\n\tif len(c.Thresholds) == 0 {\n\t\tc.Thresholds = DefaultThresholds\n\t}\n\n\tfor _, t := range c.Thresholds {\n\t\tif err := t.Valid(); err != nil {\n\t\t\tvalidationErrs = append(validationErrs, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tresult.Thresholds = append(result.Thresholds, t)\n\t}\n\n\tif len(validationErrs) > 0 {\n\t\treturn nil, fmt.Errorf(\"errors validating policy config %s: %w\", fname, errors.Join(validationErrs...))\n\t}\n\n\treturn result, nil\n}\n\ntype Config struct {\n\tBots []BotConfig\n\tThresholds []Threshold\n\tDNSBL bool\n\tImpressum *Impressum\n\tOpenGraph OpenGraph\n\tStatusCodes StatusCodes\n\tStore *Store\n}\n\nfunc (c Config) Valid() error {\n\tvar errs []error\n\n\tif len(c.Bots) == 0 {\n\t\terrs = append(errs, ErrNoBotRulesDefined)\n\t}\n\n\tfor _, b := range c.Bots {\n\t\tif err := b.Valid(); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"config is not valid:\\n%w\", errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n"], ["/anubis/internal/headers.go", "package internal\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/netip\"\n\t\"strings\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/sebest/xff\"\n)\n\n// TODO: move into config\ntype XFFComputePreferences struct {\n\tStripPrivate bool\n\tStripLoopback bool\n\tStripCGNAT bool\n\tStripLLU bool\n\tFlatten bool\n}\n\nvar CGNat = netip.MustParsePrefix(\"100.64.0.0/10\")\n\n// UnchangingCache sets the Cache-Control header to cache a response for 1 year if\n// and only if the application is compiled in \"release\" mode by Docker.\nfunc UnchangingCache(next http.Handler) http.Handler {\n\t//goland:noinspection GoBoolExpressions\n\tif anubis.Version == \"devel\" {\n\t\treturn next\n\t}\n\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Cache-Control\", \"public, max-age=31536000\")\n\t\tnext.ServeHTTP(w, r)\n\t})\n}\n\n// RemoteXRealIP sets the X-Real-Ip header to the request's real IP if\n// the setting is enabled by the user.\nfunc RemoteXRealIP(useRemoteAddress bool, bindNetwork string, next http.Handler) http.Handler {\n\tif !useRemoteAddress {\n\t\tslog.Debug(\"skipping middleware, useRemoteAddress is empty\")\n\t\treturn next\n\t}\n\n\tif bindNetwork == \"unix\" {\n\t\t// For local sockets there is no real remote address but the localhost\n\t\t// address should be sensible.\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tr.Header.Set(\"X-Real-Ip\", \"127.0.0.1\")\n\t\t\tnext.ServeHTTP(w, r)\n\t\t})\n\t}\n\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\thost, _, err := net.SplitHostPort(r.RemoteAddr)\n\t\tif err != nil {\n\t\t\tpanic(err) // this should never happen\n\t\t}\n\t\tr.Header.Set(\"X-Real-Ip\", host)\n\t\tnext.ServeHTTP(w, r)\n\t})\n}\n\n// XForwardedForToXRealIP sets the X-Real-Ip header based on the contents\n// of the X-Forwarded-For header.\nfunc XForwardedForToXRealIP(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif xffHeader := r.Header.Get(\"X-Forwarded-For\"); r.Header.Get(\"X-Real-Ip\") == \"\" && xffHeader != \"\" {\n\t\t\tip := xff.Parse(xffHeader)\n\t\t\tslog.Debug(\"setting x-real-ip\", \"val\", ip)\n\t\t\tr.Header.Set(\"X-Real-Ip\", ip)\n\t\t}\n\n\t\tnext.ServeHTTP(w, r)\n\t})\n}\n\n// XForwardedForUpdate sets or updates the X-Forwarded-For header, adding\n// the known remote address to an existing chain if present\nfunc XForwardedForUpdate(stripPrivate bool, next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tdefer next.ServeHTTP(w, r)\n\n\t\tpref := XFFComputePreferences{\n\t\t\tStripPrivate: stripPrivate,\n\t\t\tStripLoopback: true,\n\t\t\tStripCGNAT: true,\n\t\t\tFlatten: true,\n\t\t\tStripLLU: true,\n\t\t}\n\n\t\tremoteAddr := r.RemoteAddr\n\t\torigXFFHeader := r.Header.Get(\"X-Forwarded-For\")\n\n\t\tif remoteAddr == \"@\" {\n\t\t\t// remote is a unix socket\n\t\t\t// do not touch chain\n\t\t\treturn\n\t\t}\n\n\t\txffHeaderString, err := computeXFFHeader(remoteAddr, origXFFHeader, pref)\n\t\tif err != nil {\n\t\t\tslog.Debug(\"computing X-Forwarded-For header failed\", \"err\", err)\n\t\t\treturn\n\t\t}\n\n\t\tif len(xffHeaderString) == 0 {\n\t\t\tr.Header.Del(\"X-Forwarded-For\")\n\t\t} else {\n\t\t\tr.Header.Set(\"X-Forwarded-For\", xffHeaderString)\n\t\t}\n\t})\n}\n\nvar (\n\tErrCantSplitHostParse = errors.New(\"internal: unable to net.SplitHostParse\")\n\tErrCantParseRemoteIP = errors.New(\"internal: unable to parse remote IP\")\n)\n\nfunc computeXFFHeader(remoteAddr string, origXFFHeader string, pref XFFComputePreferences) (string, error) {\n\tremoteIP, _, err := net.SplitHostPort(remoteAddr)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"%w: %w\", ErrCantSplitHostParse, err)\n\t}\n\tparsedRemoteIP, err := netip.ParseAddr(remoteIP)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"%w: %w\", ErrCantParseRemoteIP, err)\n\t}\n\n\torigForwardedList := make([]string, 0, 4)\n\tif origXFFHeader != \"\" {\n\t\torigForwardedList = strings.Split(origXFFHeader, \",\")\n\t\tfor i := range origForwardedList {\n\t\t\torigForwardedList[i] = strings.TrimSpace(origForwardedList[i])\n\t\t}\n\t}\n\torigForwardedList = append(origForwardedList, parsedRemoteIP.String())\n\tforwardedList := make([]string, 0, len(origForwardedList))\n\t// this behavior is equivalent to\n\t// ingress-nginx \"compute-full-forwarded-for\"\n\t// https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/configmap/#compute-full-forwarded-for\n\t//\n\t// this would be the correct place to strip and/or flatten this list\n\t//\n\t// strip - iterate backwards and eliminate configured trusted IPs\n\t// flatten - only return the last element to avoid spoofing confusion\n\t//\n\t// many applications handle this in different ways, but\n\t// generally they'd be expected to do these two things on\n\t// their own end to find the first non-spoofed IP\n\tfor i := len(origForwardedList) - 1; i >= 0; i-- {\n\t\tsegmentIP, err := netip.ParseAddr(origForwardedList[i])\n\t\tif err != nil {\n\t\t\t// can't assess this element, so the remainder of the chain\n\t\t\t// can't be trusted. not a fatal error, since anyone can\n\t\t\t// spoof an XFF header\n\t\t\tslog.Debug(\"failed to parse XFF segment\", \"err\", err)\n\t\t\tbreak\n\t\t}\n\t\tif pref.StripPrivate && segmentIP.IsPrivate() {\n\t\t\tcontinue\n\t\t}\n\t\tif pref.StripLoopback && segmentIP.IsLoopback() {\n\t\t\tcontinue\n\t\t}\n\t\tif pref.StripLLU && segmentIP.IsLinkLocalUnicast() {\n\t\t\tcontinue\n\t\t}\n\t\tif pref.StripCGNAT && CGNat.Contains(segmentIP) {\n\t\t\tcontinue\n\t\t}\n\t\tforwardedList = append([]string{segmentIP.String()}, forwardedList...)\n\t}\n\tvar xffHeaderString string\n\tif len(forwardedList) == 0 {\n\t\txffHeaderString = \"\"\n\t\treturn xffHeaderString, nil\n\t}\n\tif pref.Flatten {\n\t\txffHeaderString = forwardedList[len(forwardedList)-1]\n\t} else {\n\t\txffHeaderString = strings.Join(forwardedList, \",\")\n\t}\n\treturn xffHeaderString, nil\n}\n\n// NoStoreCache sets the Cache-Control header to no-store for the response.\nfunc NoStoreCache(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Cache-Control\", \"no-store\")\n\t\tnext.ServeHTTP(w, r)\n\t})\n}\n\n// NoBrowsing prevents directory browsing by returning a 404 for any request that ends with a \"/\".\nfunc NoBrowsing(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif strings.HasSuffix(r.URL.Path, \"/\") {\n\t\t\thttp.NotFound(w, r)\n\t\t\treturn\n\t\t}\n\t\tnext.ServeHTTP(w, r)\n\t})\n}\n"], ["/anubis/lib/challenge/metarefresh/metarefresh.go", "package metarefresh\n\nimport (\n\t\"crypto/subtle\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net/http\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/TecharoHQ/anubis/lib/challenge\"\n\t\"github.com/TecharoHQ/anubis/lib/localization\"\n\t\"github.com/TecharoHQ/anubis/web\"\n\t\"github.com/a-h/templ\"\n)\n\n//go:generate go tool github.com/a-h/templ/cmd/templ generate\n\nfunc init() {\n\tchallenge.Register(\"metarefresh\", &Impl{})\n}\n\ntype Impl struct{}\n\nfunc (i *Impl) Setup(mux *http.ServeMux) {}\n\nfunc (i *Impl) Issue(r *http.Request, lg *slog.Logger, in *challenge.IssueInput) (templ.Component, error) {\n\tu, err := r.URL.Parse(anubis.BasePrefix + \"/.within.website/x/cmd/anubis/api/pass-challenge\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't render page: %w\", err)\n\t}\n\n\tq := u.Query()\n\tq.Set(\"redir\", r.URL.String())\n\tq.Set(\"challenge\", in.Challenge.RandomData)\n\tu.RawQuery = q.Encode()\n\n\tloc := localization.GetLocalizer(r)\n\tcomponent, err := web.BaseWithChallengeAndOGTags(loc.T(\"making_sure_not_bot\"), page(u.String(), in.Rule.Challenge.Difficulty, loc), in.Impressum, in.Challenge.RandomData, in.Rule.Challenge, in.OGTags, loc)\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't render page: %w\", err)\n\t}\n\n\treturn component, nil\n}\n\nfunc (i *Impl) Validate(r *http.Request, lg *slog.Logger, in *challenge.ValidateInput) error {\n\tgotChallenge := r.FormValue(\"challenge\")\n\n\tif subtle.ConstantTimeCompare([]byte(in.Challenge.RandomData), []byte(gotChallenge)) != 1 {\n\t\treturn challenge.NewError(\"validate\", \"invalid response\", fmt.Errorf(\"%w: wanted response %s but got %s\", challenge.ErrFailed, in.Challenge.RandomData, gotChallenge))\n\t}\n\n\treturn nil\n}\n"], ["/anubis/internal/ogtags/ogtags.go", "package ogtags\n\nimport (\n\t\"context\"\n\t\"log/slog\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n)\n\nconst (\n\tmaxContentLength = 8 << 20 // 8 MiB is enough for anyone\n\thttpTimeout = 5 * time.Second /*todo: make this configurable?*/\n\n\tschemeSeparatorLength = 3 // Length of \"://\"\n\tquerySeparatorLength = 1 // Length of \"?\" for query strings\n)\n\ntype OGTagCache struct {\n\tcache store.JSON[map[string]string]\n\ttargetURL *url.URL\n\tclient *http.Client\n\n\t// Pre-built strings for optimization\n\tunixPrefix string // \"http://unix\"\n\tapprovedTags []string\n\tapprovedPrefixes []string\n\togTimeToLive time.Duration\n\togCacheConsiderHost bool\n\togPassthrough bool\n\togOverride map[string]string\n}\n\nfunc NewOGTagCache(target string, conf config.OpenGraph, backend store.Interface) *OGTagCache {\n\t// Predefined approved tags and prefixes\n\tdefaultApprovedTags := []string{\"description\", \"keywords\", \"author\"}\n\tdefaultApprovedPrefixes := []string{\"og:\", \"twitter:\", \"fediverse:\"}\n\n\tvar parsedTargetURL *url.URL\n\tvar err error\n\n\tif target == \"\" {\n\t\t// Default to localhost if target is empty\n\t\tparsedTargetURL, _ = url.Parse(\"http://localhost\")\n\t} else {\n\t\tparsedTargetURL, err = url.Parse(target)\n\t\tif err != nil {\n\t\t\tslog.Debug(\"og: failed to parse target URL, treating as non-unix\", \"target\", target, \"error\", err)\n\t\t\t// If parsing fails, treat it as a non-unix target for backward compatibility or default behavior\n\t\t\t// For now, assume it's not a scheme issue but maybe an invalid char, etc.\n\t\t\t// A simple string target might be intended if it's not a full URL.\n\t\t\tparsedTargetURL = &url.URL{Scheme: \"http\", Host: target} // Assume http if scheme missing and host-like\n\t\t\tif !strings.Contains(target, \"://\") && !strings.HasPrefix(target, \"unix:\") {\n\t\t\t\t// If it looks like just a host/host:port (and not unix), prepend http:// (todo: is this bad...? Trace path to see if i can yell at user to do it right)\n\t\t\t\tparsedTargetURL, _ = url.Parse(\"http://\" + target) // fetch cares about scheme but anubis doesn't\n\t\t\t}\n\t\t}\n\t}\n\n\tclient := &http.Client{\n\t\tTimeout: httpTimeout,\n\t}\n\n\t// Configure custom transport for Unix sockets\n\tif parsedTargetURL.Scheme == \"unix\" {\n\t\tsocketPath := parsedTargetURL.Path // For unix scheme, path is the socket path\n\t\tclient.Transport = &http.Transport{\n\t\t\tDialContext: func(_ context.Context, _, _ string) (net.Conn, error) {\n\t\t\t\treturn net.Dial(\"unix\", socketPath)\n\t\t\t},\n\t\t}\n\t}\n\n\treturn &OGTagCache{\n\t\tcache: store.JSON[map[string]string]{\n\t\t\tUnderlying: backend,\n\t\t\tPrefix: \"ogtags:\",\n\t\t},\n\t\ttargetURL: parsedTargetURL,\n\t\togPassthrough: conf.Enabled,\n\t\togTimeToLive: conf.TimeToLive,\n\t\togCacheConsiderHost: conf.ConsiderHost,\n\t\togOverride: conf.Override,\n\t\tapprovedTags: defaultApprovedTags,\n\t\tapprovedPrefixes: defaultApprovedPrefixes,\n\t\tclient: client,\n\t\tunixPrefix: \"http://unix\",\n\t}\n}\n\n// getTarget constructs the target URL string for fetching OG tags.\n// Optimized to minimize allocations by building strings directly.\nfunc (c *OGTagCache) getTarget(u *url.URL) string {\n\tvar escapedPath = u.EscapedPath() // will cause an allocation if path contains special characters\n\tif c.targetURL.Scheme == \"unix\" {\n\t\t// Build URL string directly without creating intermediate URL object\n\t\tvar sb strings.Builder\n\t\tsb.Grow(len(c.unixPrefix) + len(escapedPath) + len(u.RawQuery) + querySeparatorLength) // Pre-allocate\n\t\tsb.WriteString(c.unixPrefix)\n\t\tsb.WriteString(escapedPath)\n\t\tif u.RawQuery != \"\" {\n\t\t\tsb.WriteByte('?')\n\t\t\tsb.WriteString(u.RawQuery)\n\t\t}\n\t\treturn sb.String()\n\t}\n\n\t// For regular http/https targets, build URL string directly\n\tvar sb strings.Builder\n\t// Pre-calculate size: scheme + \"://\" + host + path + \"?\" + query\n\testimatedSize := len(c.targetURL.Scheme) + schemeSeparatorLength + len(c.targetURL.Host) + len(escapedPath) + len(u.RawQuery) + querySeparatorLength\n\tsb.Grow(estimatedSize)\n\n\tsb.WriteString(c.targetURL.Scheme)\n\tsb.WriteString(\"://\")\n\tsb.WriteString(c.targetURL.Host)\n\tsb.WriteString(escapedPath)\n\tif u.RawQuery != \"\" {\n\t\tsb.WriteByte('?')\n\t\tsb.WriteString(u.RawQuery)\n\t}\n\n\treturn sb.String()\n}\n"], ["/anubis/cmd/robots2policy/main.go", "package main\n\nimport (\n\t\"bufio\"\n\t\"encoding/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\n\t\"sigs.k8s.io/yaml\"\n)\n\nvar (\n\tinputFile = flag.String(\"input\", \"\", \"path to robots.txt file (use - for stdin)\")\n\toutputFile = flag.String(\"output\", \"\", \"output file path (use - for stdout, defaults to stdout)\")\n\toutputFormat = flag.String(\"format\", \"yaml\", \"output format: yaml or json\")\n\tbaseAction = flag.String(\"action\", \"CHALLENGE\", \"default action for disallowed paths: ALLOW, DENY, CHALLENGE, WEIGH\")\n\tcrawlDelay = flag.Int(\"crawl-delay-weight\", 0, \"if > 0, add weight adjustment for crawl-delay (difficulty adjustment)\")\n\tpolicyName = flag.String(\"name\", \"robots-txt-policy\", \"name for the generated policy\")\n\tuserAgentDeny = flag.String(\"deny-user-agents\", \"DENY\", \"action for specifically blocked user agents: DENY, CHALLENGE\")\n\thelpFlag = flag.Bool(\"help\", false, \"show help\")\n)\n\ntype RobotsRule struct {\n\tUserAgent string\n\tDisallows []string\n\tAllows []string\n\tCrawlDelay int\n\tIsBlacklist bool // true if this is a specifically denied user agent\n}\n\ntype AnubisRule struct {\n\tExpression *config.ExpressionOrList `yaml:\"expression,omitempty\" json:\"expression,omitempty\"`\n\tChallenge *config.ChallengeRules `yaml:\"challenge,omitempty\" json:\"challenge,omitempty\"`\n\tWeight *config.Weight `yaml:\"weight,omitempty\" json:\"weight,omitempty\"`\n\tName string `yaml:\"name\" json:\"name\"`\n\tAction string `yaml:\"action\" json:\"action\"`\n}\n\nfunc init() {\n\tflag.Usage = func() {\n\t\tfmt.Fprintf(os.Stderr, \"Usage of %s:\\n\", os.Args[0])\n\t\tfmt.Fprintf(os.Stderr, \"%s [options] -input \\n\\n\", os.Args[0])\n\t\tflag.PrintDefaults()\n\t\tfmt.Fprintln(os.Stderr, \"\\nExamples:\")\n\t\tfmt.Fprintln(os.Stderr, \" # Convert local robots.txt file\")\n\t\tfmt.Fprintln(os.Stderr, \" robots2policy -input robots.txt -output policy.yaml\")\n\t\tfmt.Fprintln(os.Stderr, \"\")\n\t\tfmt.Fprintln(os.Stderr, \" # Convert from URL\")\n\t\tfmt.Fprintln(os.Stderr, \" robots2policy -input https://example.com/robots.txt -format json\")\n\t\tfmt.Fprintln(os.Stderr, \"\")\n\t\tfmt.Fprintln(os.Stderr, \" # Read from stdin, write to stdout\")\n\t\tfmt.Fprintln(os.Stderr, \" curl https://example.com/robots.txt | robots2policy -input -\")\n\t\tos.Exit(2)\n\t}\n}\n\nfunc main() {\n\tflag.Parse()\n\n\tif len(flag.Args()) > 0 || *helpFlag || *inputFile == \"\" {\n\t\tflag.Usage()\n\t}\n\n\t// Read robots.txt\n\tvar input io.Reader\n\tif *inputFile == \"-\" {\n\t\tinput = os.Stdin\n\t} else if strings.HasPrefix(*inputFile, \"http://\") || strings.HasPrefix(*inputFile, \"https://\") {\n\t\tresp, err := http.Get(*inputFile)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to fetch robots.txt from URL: %v\", err)\n\t\t}\n\t\tdefer resp.Body.Close()\n\t\tinput = resp.Body\n\t} else {\n\t\tfile, err := os.Open(*inputFile)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to open input file: %v\", err)\n\t\t}\n\t\tdefer file.Close()\n\t\tinput = file\n\t}\n\n\t// Parse robots.txt\n\trules, err := parseRobotsTxt(input)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to parse robots.txt: %v\", err)\n\t}\n\n\t// Convert to Anubis rules\n\tanubisRules := convertToAnubisRules(rules)\n\n\t// Check if any rules were generated\n\tif len(anubisRules) == 0 {\n\t\tlog.Fatal(\"no valid rules generated from robots.txt - file may be empty or contain no disallow directives\")\n\t}\n\n\t// Generate output\n\tvar output []byte\n\tswitch strings.ToLower(*outputFormat) {\n\tcase \"yaml\":\n\t\toutput, err = yaml.Marshal(anubisRules)\n\tcase \"json\":\n\t\toutput, err = json.MarshalIndent(anubisRules, \"\", \" \")\n\tdefault:\n\t\tlog.Fatalf(\"unsupported output format: %s (use yaml or json)\", *outputFormat)\n\t}\n\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to marshal output: %v\", err)\n\t}\n\n\t// Write output\n\tif *outputFile == \"\" || *outputFile == \"-\" {\n\t\tfmt.Print(string(output))\n\t} else {\n\t\terr = os.WriteFile(*outputFile, output, 0644)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to write output file: %v\", err)\n\t\t}\n\t\tfmt.Printf(\"Generated Anubis policy written to %s\\n\", *outputFile)\n\t}\n}\n\nfunc parseRobotsTxt(input io.Reader) ([]RobotsRule, error) {\n\tscanner := bufio.NewScanner(input)\n\tvar rules []RobotsRule\n\tvar currentRule *RobotsRule\n\n\tfor scanner.Scan() {\n\t\tline := strings.TrimSpace(scanner.Text())\n\n\t\t// Skip empty lines and comments\n\t\tif line == \"\" || strings.HasPrefix(line, \"#\") {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Split on first colon\n\t\tparts := strings.SplitN(line, \":\", 2)\n\t\tif len(parts) != 2 {\n\t\t\tcontinue\n\t\t}\n\n\t\tdirective := strings.TrimSpace(strings.ToLower(parts[0]))\n\t\tvalue := strings.TrimSpace(parts[1])\n\n\t\tswitch directive {\n\t\tcase \"user-agent\":\n\t\t\t// Start a new rule section\n\t\t\tif currentRule != nil {\n\t\t\t\trules = append(rules, *currentRule)\n\t\t\t}\n\t\t\tcurrentRule = &RobotsRule{\n\t\t\t\tUserAgent: value,\n\t\t\t\tDisallows: make([]string, 0),\n\t\t\t\tAllows: make([]string, 0),\n\t\t\t}\n\n\t\tcase \"disallow\":\n\t\t\tif currentRule != nil && value != \"\" {\n\t\t\t\tcurrentRule.Disallows = append(currentRule.Disallows, value)\n\t\t\t}\n\n\t\tcase \"allow\":\n\t\t\tif currentRule != nil && value != \"\" {\n\t\t\t\tcurrentRule.Allows = append(currentRule.Allows, value)\n\t\t\t}\n\n\t\tcase \"crawl-delay\":\n\t\t\tif currentRule != nil {\n\t\t\t\tif delay, err := parseIntSafe(value); err == nil {\n\t\t\t\t\tcurrentRule.CrawlDelay = delay\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Don't forget the last rule\n\tif currentRule != nil {\n\t\trules = append(rules, *currentRule)\n\t}\n\n\t// Mark blacklisted user agents (those with \"Disallow: /\")\n\tfor i := range rules {\n\t\tfor _, disallow := range rules[i].Disallows {\n\t\t\tif disallow == \"/\" {\n\t\t\t\trules[i].IsBlacklist = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn rules, scanner.Err()\n}\n\nfunc parseIntSafe(s string) (int, error) {\n\tvar result int\n\t_, err := fmt.Sscanf(s, \"%d\", &result)\n\treturn result, err\n}\n\nfunc convertToAnubisRules(robotsRules []RobotsRule) []AnubisRule {\n\tvar anubisRules []AnubisRule\n\truleCounter := 0\n\n\tfor _, robotsRule := range robotsRules {\n\t\tuserAgent := robotsRule.UserAgent\n\n\t\t// Handle crawl delay as weight adjustment (do this first before any continues)\n\t\tif robotsRule.CrawlDelay > 0 && *crawlDelay > 0 {\n\t\t\truleCounter++\n\t\t\trule := AnubisRule{\n\t\t\t\tName: fmt.Sprintf(\"%s-crawl-delay-%d\", *policyName, ruleCounter),\n\t\t\t\tAction: \"WEIGH\",\n\t\t\t\tWeight: &config.Weight{Adjust: *crawlDelay},\n\t\t\t}\n\n\t\t\tif userAgent == \"*\" {\n\t\t\t\trule.Expression = &config.ExpressionOrList{\n\t\t\t\t\tAll: []string{\"true\"}, // Always applies\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\trule.Expression = &config.ExpressionOrList{\n\t\t\t\t\tAll: []string{fmt.Sprintf(\"userAgent.contains(%q)\", userAgent)},\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tanubisRules = append(anubisRules, rule)\n\t\t}\n\n\t\t// Handle blacklisted user agents (complete deny/challenge)\n\t\tif robotsRule.IsBlacklist {\n\t\t\truleCounter++\n\t\t\trule := AnubisRule{\n\t\t\t\tName: fmt.Sprintf(\"%s-blacklist-%d\", *policyName, ruleCounter),\n\t\t\t\tAction: *userAgentDeny,\n\t\t\t}\n\n\t\t\tif userAgent == \"*\" {\n\t\t\t\t// This would block everything - convert to a weight adjustment instead\n\t\t\t\trule.Name = fmt.Sprintf(\"%s-global-restriction-%d\", *policyName, ruleCounter)\n\t\t\t\trule.Action = \"WEIGH\"\n\t\t\t\trule.Weight = &config.Weight{Adjust: 20} // Increase difficulty significantly\n\t\t\t\trule.Expression = &config.ExpressionOrList{\n\t\t\t\t\tAll: []string{\"true\"}, // Always applies\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\trule.Expression = &config.ExpressionOrList{\n\t\t\t\t\tAll: []string{fmt.Sprintf(\"userAgent.contains(%q)\", userAgent)},\n\t\t\t\t}\n\t\t\t}\n\t\t\tanubisRules = append(anubisRules, rule)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Handle specific disallow rules\n\t\tfor _, disallow := range robotsRule.Disallows {\n\t\t\tif disallow == \"/\" {\n\t\t\t\tcontinue // Already handled as blacklist above\n\t\t\t}\n\n\t\t\truleCounter++\n\t\t\trule := AnubisRule{\n\t\t\t\tName: fmt.Sprintf(\"%s-disallow-%d\", *policyName, ruleCounter),\n\t\t\t\tAction: *baseAction,\n\t\t\t}\n\n\t\t\t// Build CEL expression\n\t\t\tvar conditions []string\n\n\t\t\t// Add user agent condition if not wildcard\n\t\t\tif userAgent != \"*\" {\n\t\t\t\tconditions = append(conditions, fmt.Sprintf(\"userAgent.contains(%q)\", userAgent))\n\t\t\t}\n\n\t\t\t// Add path condition\n\t\t\tpathCondition := buildPathCondition(disallow)\n\t\t\tconditions = append(conditions, pathCondition)\n\n\t\t\trule.Expression = &config.ExpressionOrList{\n\t\t\t\tAll: conditions,\n\t\t\t}\n\n\t\t\tanubisRules = append(anubisRules, rule)\n\t\t}\n\n\t}\n\n\treturn anubisRules\n}\n\nfunc buildPathCondition(robotsPath string) string {\n\t// Handle wildcards in robots.txt paths\n\tif strings.Contains(robotsPath, \"*\") || strings.Contains(robotsPath, \"?\") {\n\t\t// Convert robots.txt wildcards to regex\n\t\tregex := regexp.QuoteMeta(robotsPath)\n\t\tregex = strings.ReplaceAll(regex, `\\*`, `.*`) // * becomes .*\n\t\tregex = strings.ReplaceAll(regex, `\\?`, `.`) // ? becomes .\n\t\tregex = \"^\" + regex\n\t\treturn fmt.Sprintf(\"path.matches(%q)\", regex)\n\t}\n\n\t// Simple prefix match for most cases\n\treturn fmt.Sprintf(\"path.startsWith(%q)\", robotsPath)\n}\n"], ["/anubis/lib/challenge/proofofwork/proofofwork.go", "package proofofwork\n\nimport (\n\t\"crypto/subtle\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net/http\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com/TecharoHQ/anubis/internal\"\n\tchall \"github.com/TecharoHQ/anubis/lib/challenge\"\n\t\"github.com/TecharoHQ/anubis/lib/localization\"\n\t\"github.com/TecharoHQ/anubis/web\"\n\t\"github.com/a-h/templ\"\n)\n\nfunc init() {\n\tchall.Register(\"fast\", &Impl{Algorithm: \"fast\"})\n\tchall.Register(\"slow\", &Impl{Algorithm: \"slow\"})\n}\n\ntype Impl struct {\n\tAlgorithm string\n}\n\nfunc (i *Impl) Setup(mux *http.ServeMux) {\n\t/* no implementation required */\n}\n\nfunc (i *Impl) Issue(r *http.Request, lg *slog.Logger, in *chall.IssueInput) (templ.Component, error) {\n\tloc := localization.GetLocalizer(r)\n\tcomponent, err := web.BaseWithChallengeAndOGTags(loc.T(\"making_sure_not_bot\"), web.Index(loc), in.Impressum, in.Challenge.RandomData, in.Rule.Challenge, in.OGTags, loc)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't render page: %w\", err)\n\t}\n\n\treturn component, nil\n}\n\nfunc (i *Impl) Validate(r *http.Request, lg *slog.Logger, in *chall.ValidateInput) error {\n\trule := in.Rule\n\tchallenge := in.Challenge.RandomData\n\n\tnonceStr := r.FormValue(\"nonce\")\n\tif nonceStr == \"\" {\n\t\treturn chall.NewError(\"validate\", \"invalid response\", fmt.Errorf(\"%w nonce\", chall.ErrMissingField))\n\t}\n\n\tnonce, err := strconv.Atoi(nonceStr)\n\tif err != nil {\n\t\treturn chall.NewError(\"validate\", \"invalid response\", fmt.Errorf(\"%w: nonce: %w\", chall.ErrInvalidFormat, err))\n\n\t}\n\n\telapsedTimeStr := r.FormValue(\"elapsedTime\")\n\tif elapsedTimeStr == \"\" {\n\t\treturn chall.NewError(\"validate\", \"invalid response\", fmt.Errorf(\"%w elapsedTime\", chall.ErrMissingField))\n\t}\n\n\telapsedTime, err := strconv.ParseFloat(elapsedTimeStr, 64)\n\tif err != nil {\n\t\treturn chall.NewError(\"validate\", \"invalid response\", fmt.Errorf(\"%w: elapsedTime: %w\", chall.ErrInvalidFormat, err))\n\t}\n\n\tresponse := r.FormValue(\"response\")\n\tif response == \"\" {\n\t\treturn chall.NewError(\"validate\", \"invalid response\", fmt.Errorf(\"%w response\", chall.ErrMissingField))\n\t}\n\n\tcalcString := fmt.Sprintf(\"%s%d\", challenge, nonce)\n\tcalculated := internal.SHA256sum(calcString)\n\n\tif subtle.ConstantTimeCompare([]byte(response), []byte(calculated)) != 1 {\n\t\treturn chall.NewError(\"validate\", \"invalid response\", fmt.Errorf(\"%w: wanted response %s but got %s\", chall.ErrFailed, calculated, response))\n\t}\n\n\t// compare the leading zeroes\n\tif !strings.HasPrefix(response, strings.Repeat(\"0\", rule.Challenge.Difficulty)) {\n\t\treturn chall.NewError(\"validate\", \"invalid response\", fmt.Errorf(\"%w: wanted %d leading zeros but got %s\", chall.ErrFailed, rule.Challenge.Difficulty, response))\n\t}\n\n\tlg.Debug(\"challenge took\", \"elapsedTime\", elapsedTime)\n\tchall.TimeTaken.WithLabelValues(i.Algorithm).Observe(elapsedTime)\n\n\treturn nil\n}\n"], ["/anubis/lib/thoth/cachediptoasn.go", "package thoth\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net/netip\"\n\n\tiptoasnv1 \"github.com/TecharoHQ/thoth-proto/gen/techaro/thoth/iptoasn/v1\"\n\t\"github.com/gaissmai/bart\"\n\t\"google.golang.org/grpc\"\n)\n\ntype IPToASNWithCache struct {\n\tnext iptoasnv1.IpToASNServiceClient\n\ttable *bart.Table[*iptoasnv1.LookupResponse]\n}\n\nfunc NewIpToASNWithCache(next iptoasnv1.IpToASNServiceClient) *IPToASNWithCache {\n\tresult := &IPToASNWithCache{\n\t\tnext: next,\n\t\ttable: &bart.Table[*iptoasnv1.LookupResponse]{},\n\t}\n\n\tfor _, pfx := range []netip.Prefix{\n\t\tnetip.MustParsePrefix(\"10.0.0.0/8\"), // RFC 1918\n\t\tnetip.MustParsePrefix(\"172.16.0.0/12\"), // RFC 1918\n\t\tnetip.MustParsePrefix(\"192.168.0.0/16\"), // RFC 1918\n\t\tnetip.MustParsePrefix(\"127.0.0.0/8\"), // Loopback\n\t\tnetip.MustParsePrefix(\"169.254.0.0/16\"), // Link-local\n\t\tnetip.MustParsePrefix(\"100.64.0.0/10\"), // CGNAT\n\t\tnetip.MustParsePrefix(\"192.0.0.0/24\"), // Protocol assignments\n\t\tnetip.MustParsePrefix(\"192.0.2.0/24\"), // TEST-NET-1\n\t\tnetip.MustParsePrefix(\"198.18.0.0/15\"), // Benchmarking\n\t\tnetip.MustParsePrefix(\"198.51.100.0/24\"), // TEST-NET-2\n\t\tnetip.MustParsePrefix(\"203.0.113.0/24\"), // TEST-NET-3\n\t\tnetip.MustParsePrefix(\"240.0.0.0/4\"), // Reserved\n\t\tnetip.MustParsePrefix(\"255.255.255.255/32\"), // Broadcast\n\t\tnetip.MustParsePrefix(\"fc00::/7\"), // Unique local address\n\t\tnetip.MustParsePrefix(\"fe80::/10\"), // Link-local\n\t\tnetip.MustParsePrefix(\"::1/128\"), // Loopback\n\t\tnetip.MustParsePrefix(\"::/128\"), // Unspecified\n\t\tnetip.MustParsePrefix(\"100::/64\"), // Discard-only\n\t\tnetip.MustParsePrefix(\"2001:db8::/32\"), // Documentation\n\t} {\n\t\tresult.table.Insert(pfx, &iptoasnv1.LookupResponse{Announced: false})\n\t}\n\n\treturn result\n}\n\nfunc (ip2asn *IPToASNWithCache) Lookup(ctx context.Context, lr *iptoasnv1.LookupRequest, opts ...grpc.CallOption) (*iptoasnv1.LookupResponse, error) {\n\taddr, err := netip.ParseAddr(lr.GetIpAddress())\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"input is not an IP address: %w\", err)\n\t}\n\n\tcachedResponse, ok := ip2asn.table.Lookup(addr)\n\tif ok {\n\t\treturn cachedResponse, nil\n\t}\n\n\tresp, err := ip2asn.next.Lookup(ctx, lr, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar errs []error\n\tfor _, cidr := range resp.GetCidr() {\n\t\tpfx, err := netip.ParsePrefix(cidr)\n\t\tif err != nil {\n\t\t\terrs = append(errs, err)\n\t\t\tcontinue\n\t\t}\n\t\tip2asn.table.Insert(pfx, resp)\n\t}\n\n\tif len(errs) != 0 {\n\t\tslog.Error(\"errors parsing IP prefixes\", \"err\", errors.Join(errs...))\n\t}\n\n\treturn resp, nil\n}\n"], ["/anubis/xess/xess.go", "// Package xess vendors a copy of Xess and makes it available at /.xess/xess.css\n//\n// This is intended to be used as a vendored package in other projects.\npackage xess\n\nimport (\n\t\"embed\"\n\t\"net/http\"\n\t\"path/filepath\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/TecharoHQ/anubis/internal\"\n)\n\nvar (\n\t//go:embed *.css static\n\tStatic embed.FS\n\n\tURL = \"/.within.website/x/xess/xess.css\"\n)\n\nfunc init() {\n\tMount(http.DefaultServeMux)\n\n\t//goland:noinspection GoBoolExpressions\n\tif anubis.Version != \"devel\" {\n\t\tURL = filepath.Join(filepath.Dir(URL), \"xess.min.css\")\n\t}\n\n\tURL = URL + \"?cachebuster=\" + anubis.Version\n}\n\n// Mount registers the xess static file handlers on the given mux\nfunc Mount(mux *http.ServeMux) {\n\tprefix := anubis.BasePrefix + \"/.within.website/x/xess/\"\n\n\tmux.Handle(prefix, internal.UnchangingCache(http.StripPrefix(prefix, http.FileServerFS(Static))))\n}\n"], ["/anubis/lib/policy/checker.go", "package policy\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/netip\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com/TecharoHQ/anubis/internal\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/checker\"\n\t\"github.com/gaissmai/bart\"\n)\n\nvar (\n\tErrMisconfiguration = errors.New(\"[unexpected] policy: administrator misconfiguration\")\n)\n\ntype RemoteAddrChecker struct {\n\tprefixTable *bart.Lite\n\thash string\n}\n\nfunc NewRemoteAddrChecker(cidrs []string) (checker.Impl, error) {\n\ttable := new(bart.Lite)\n\n\tfor _, cidr := range cidrs {\n\t\tprefix, err := netip.ParsePrefix(cidr)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"%w: range %s not parsing: %w\", ErrMisconfiguration, cidr, err)\n\t\t}\n\n\t\ttable.Insert(prefix)\n\t}\n\n\treturn &RemoteAddrChecker{\n\t\tprefixTable: table,\n\t\thash: internal.FastHash(strings.Join(cidrs, \",\")),\n\t}, nil\n}\n\nfunc (rac *RemoteAddrChecker) Check(r *http.Request) (bool, error) {\n\thost := r.Header.Get(\"X-Real-Ip\")\n\tif host == \"\" {\n\t\treturn false, fmt.Errorf(\"%w: header X-Real-Ip is not set\", ErrMisconfiguration)\n\t}\n\n\taddr, err := netip.ParseAddr(host)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"%w: %s is not an IP address: %w\", ErrMisconfiguration, host, err)\n\t}\n\n\treturn rac.prefixTable.Contains(addr), nil\n}\n\nfunc (rac *RemoteAddrChecker) Hash() string {\n\treturn rac.hash\n}\n\ntype HeaderMatchesChecker struct {\n\theader string\n\tregexp *regexp.Regexp\n\thash string\n}\n\nfunc NewUserAgentChecker(rexStr string) (checker.Impl, error) {\n\treturn NewHeaderMatchesChecker(\"User-Agent\", rexStr)\n}\n\nfunc NewHeaderMatchesChecker(header, rexStr string) (checker.Impl, error) {\n\trex, err := regexp.Compile(strings.TrimSpace(rexStr))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: regex %s failed parse: %w\", ErrMisconfiguration, rexStr, err)\n\t}\n\treturn &HeaderMatchesChecker{strings.TrimSpace(header), rex, internal.FastHash(header + \": \" + rexStr)}, nil\n}\n\nfunc (hmc *HeaderMatchesChecker) Check(r *http.Request) (bool, error) {\n\tif hmc.regexp.MatchString(r.Header.Get(hmc.header)) {\n\t\treturn true, nil\n\t}\n\n\treturn false, nil\n}\n\nfunc (hmc *HeaderMatchesChecker) Hash() string {\n\treturn hmc.hash\n}\n\ntype PathChecker struct {\n\tregexp *regexp.Regexp\n\thash string\n}\n\nfunc NewPathChecker(rexStr string) (checker.Impl, error) {\n\trex, err := regexp.Compile(strings.TrimSpace(rexStr))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: regex %s failed parse: %w\", ErrMisconfiguration, rexStr, err)\n\t}\n\treturn &PathChecker{rex, internal.FastHash(rexStr)}, nil\n}\n\nfunc (pc *PathChecker) Check(r *http.Request) (bool, error) {\n\tif pc.regexp.MatchString(r.URL.Path) {\n\t\treturn true, nil\n\t}\n\n\treturn false, nil\n}\n\nfunc (pc *PathChecker) Hash() string {\n\treturn pc.hash\n}\n\nfunc NewHeaderExistsChecker(key string) checker.Impl {\n\treturn headerExistsChecker{strings.TrimSpace(key)}\n}\n\ntype headerExistsChecker struct {\n\theader string\n}\n\nfunc (hec headerExistsChecker) Check(r *http.Request) (bool, error) {\n\tif r.Header.Get(hec.header) != \"\" {\n\t\treturn true, nil\n\t}\n\n\treturn false, nil\n}\n\nfunc (hec headerExistsChecker) Hash() string {\n\treturn internal.FastHash(hec.header)\n}\n\nfunc NewHeadersChecker(headermap map[string]string) (checker.Impl, error) {\n\tvar result checker.List\n\tvar errs []error\n\n\tfor key, rexStr := range headermap {\n\t\tif rexStr == \".*\" {\n\t\t\tresult = append(result, headerExistsChecker{strings.TrimSpace(key)})\n\t\t\tcontinue\n\t\t}\n\n\t\trex, err := regexp.Compile(strings.TrimSpace(rexStr))\n\t\tif err != nil {\n\t\t\terrs = append(errs, fmt.Errorf(\"while compiling header %s regex %s: %w\", key, rexStr, err))\n\t\t\tcontinue\n\t\t}\n\n\t\tresult = append(result, &HeaderMatchesChecker{key, rex, internal.FastHash(key + \": \" + rexStr)})\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn nil, errors.Join(errs...)\n\t}\n\n\treturn result, nil\n}\n"], ["/anubis/internal/ogtags/fetch.go", "package ogtags\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log/slog\"\n\t\"mime\"\n\t\"net\"\n\t\"net/http\"\n\n\t\"golang.org/x/net/html\"\n)\n\nvar (\n\tErrOgHandled = errors.New(\"og: handled error\") // used to indicate that the error was handled and should not be logged\n\temptyMap = map[string]string{} // used to indicate an empty result in the cache. Can't use nil as it would be a cache miss.\n)\n\n// fetchHTMLDocumentWithCache fetches the HTML document from the given URL string,\n// preserving the original host header.\nfunc (c *OGTagCache) fetchHTMLDocumentWithCache(ctx context.Context, urlStr string, originalHost string, cacheKey string) (*html.Node, error) {\n\treq, err := http.NewRequestWithContext(ctx, \"GET\", urlStr, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create http request: %w\", err)\n\t}\n\n\t// Set the Host header to the original host\n\tif originalHost != \"\" {\n\t\treq.Host = originalHost\n\t}\n\n\t// Add proxy headers\n\treq.Header.Set(\"X-Forwarded-Proto\", \"https\")\n\treq.Header.Set(\"User-Agent\", \"Anubis-OGTag-Fetcher/1.0\") // For tracking purposes\n\n\t// Send the request\n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\tvar netErr net.Error\n\t\tif errors.As(err, &netErr) && netErr.Timeout() {\n\t\t\tslog.Debug(\"og: request timed out\", \"url\", urlStr)\n\t\t\tc.cache.Set(ctx, cacheKey, emptyMap, c.ogTimeToLive/2) // Cache empty result for half the TTL to not spam the server\n\t\t}\n\t\treturn nil, fmt.Errorf(\"http get failed: %w\", err)\n\t}\n\n\t// Ensure the response body is closed\n\tdefer func(Body io.ReadCloser) {\n\t\terr := Body.Close()\n\t\tif err != nil {\n\t\t\tslog.Debug(\"og: error closing response body\", \"url\", urlStr, \"error\", err)\n\t\t}\n\t}(resp.Body)\n\n\tif resp.StatusCode != http.StatusOK {\n\t\tslog.Debug(\"og: received non-OK status code\", \"url\", urlStr, \"status\", resp.StatusCode)\n\t\tc.cache.Set(ctx, cacheKey, emptyMap, c.ogTimeToLive) // Cache empty result for non-successful status codes\n\t\treturn nil, fmt.Errorf(\"%w: page not found\", ErrOgHandled)\n\t}\n\n\t// Check content type\n\tct := resp.Header.Get(\"Content-Type\")\n\tif ct == \"\" {\n\t\treturn nil, fmt.Errorf(\"missing Content-Type header\")\n\t} else {\n\t\tmediaType, _, err := mime.ParseMediaType(ct)\n\t\tif err != nil {\n\t\t\tslog.Debug(\"og: malformed Content-Type header\", \"url\", urlStr, \"contentType\", ct)\n\t\t\treturn nil, fmt.Errorf(\"%w malformed Content-Type header: %w\", ErrOgHandled, err)\n\t\t}\n\n\t\tif mediaType != \"text/html\" && mediaType != \"application/xhtml+xml\" {\n\t\t\tslog.Debug(\"og: unsupported Content-Type\", \"url\", urlStr, \"contentType\", mediaType)\n\t\t\treturn nil, fmt.Errorf(\"%w unsupported Content-Type: %s\", ErrOgHandled, mediaType)\n\t\t}\n\t}\n\n\tresp.Body = http.MaxBytesReader(nil, resp.Body, maxContentLength)\n\n\tdoc, err := html.Parse(resp.Body)\n\tif err != nil {\n\t\t// Check if the error is specifically because the limit was exceeded\n\t\tvar maxBytesErr *http.MaxBytesError\n\t\tif errors.As(err, &maxBytesErr) {\n\t\t\tslog.Debug(\"og: content exceeded max length\", \"url\", urlStr, \"limit\", maxContentLength)\n\t\t\treturn nil, fmt.Errorf(\"content too large: exceeded %d bytes\", maxContentLength)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"failed to parse HTML: %w\", err)\n\t}\n\n\treturn doc, nil\n}\n"], ["/anubis/lib/store/bbolt/bbolt.go", "package bbolt\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n\t\"go.etcd.io/bbolt\"\n)\n\n// Sentinel error values used for testing and in admin-visible error messages.\nvar (\n\tErrBucketDoesNotExist = errors.New(\"bbolt: bucket does not exist\")\n\tErrNotExists = errors.New(\"bbolt: value does not exist in store\")\n)\n\n// Store implements store.Interface backed by bbolt[1].\n//\n// In essence, bbolt is a hierarchical key/value store with a twist: every value\n// needs to belong to a bucket. Buckets can contain an infinite number of\n// buckets. As such, Anubis nests values in buckets. Each value in the store\n// is given its own bucket with two keys:\n//\n// 1. data - The raw data, usually in JSON\n// 2. expiry - The expiry time formatted as a time.RFC3339Nano timestamp string\n//\n// When Anubis stores a new bit of data, it creates a new bucket for that value.\n// This allows the cleanup phase to iterate over every bucket in the database and\n// only scan the expiry times without having to decode the entire record.\n//\n// bbolt is not suitable for environments where multiple instance of Anubis need\n// to read from and write to the same backend store. For that, use the valkey\n// storage backend.\n//\n// [1]: https://github.com/etcd-io/bbolt\ntype Store struct {\n\tbdb *bbolt.DB\n}\n\n// Delete a key from the datastore. If the key does not exist, return an error.\nfunc (s *Store) Delete(ctx context.Context, key string) error {\n\treturn s.bdb.Update(func(tx *bbolt.Tx) error {\n\t\tif tx.Bucket([]byte(key)) == nil {\n\t\t\treturn fmt.Errorf(\"%w: %q\", ErrNotExists, key)\n\t\t}\n\n\t\treturn tx.DeleteBucket([]byte(key))\n\t})\n}\n\n// Get a value from the datastore.\n//\n// Because each value is stored in its own bucket with data and expiry keys,\n// two get operations are required:\n//\n// 1. Get the expiry key, parse as time.RFC3339Nano. If the key has expired, run deletion in the background and return a \"key not found\" error.\n// 2. Get the data key, copy into the result byteslice, return it.\nfunc (s *Store) Get(ctx context.Context, key string) ([]byte, error) {\n\tvar result []byte\n\n\tif err := s.bdb.View(func(tx *bbolt.Tx) error {\n\t\titemBucket := tx.Bucket([]byte(key))\n\t\tif itemBucket == nil {\n\t\t\treturn fmt.Errorf(\"%w: %q\", store.ErrNotFound, key)\n\t\t}\n\n\t\texpiryStr := itemBucket.Get([]byte(\"expiry\"))\n\t\tif expiryStr == nil {\n\t\t\treturn fmt.Errorf(\"[unexpected] %w: %q (expiry is nil)\", store.ErrNotFound, key)\n\t\t}\n\n\t\texpiry, err := time.Parse(time.RFC3339Nano, string(expiryStr))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"[unexpected] %w: %w\", store.ErrCantDecode, err)\n\t\t}\n\n\t\tif time.Now().After(expiry) {\n\t\t\tgo s.Delete(context.Background(), key)\n\t\t\treturn fmt.Errorf(\"%w: %q\", store.ErrNotFound, key)\n\t\t}\n\n\t\tdataStr := itemBucket.Get([]byte(\"data\"))\n\t\tif dataStr == nil {\n\t\t\treturn fmt.Errorf(\"[unexpected] %w: %q (data is nil)\", store.ErrNotFound, key)\n\t\t}\n\n\t\tresult = make([]byte, len(dataStr))\n\t\tif n := copy(result, dataStr); n != len(dataStr) {\n\t\t\treturn fmt.Errorf(\"[unexpected] %w: %d bytes copied of %d\", store.ErrCantDecode, n, len(dataStr))\n\t\t}\n\n\t\treturn nil\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn result, nil\n}\n\n// Set a value into the store with a given expiry.\nfunc (s *Store) Set(ctx context.Context, key string, value []byte, expiry time.Duration) error {\n\texpires := time.Now().Add(expiry)\n\n\treturn s.bdb.Update(func(tx *bbolt.Tx) error {\n\t\tvalueBkt, err := tx.CreateBucketIfNotExists([]byte(key))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"%w: %w: %q (create bucket)\", store.ErrCantEncode, err, key)\n\t\t}\n\n\t\tif err := valueBkt.Put([]byte(\"expiry\"), []byte(expires.Format(time.RFC3339Nano))); err != nil {\n\t\t\treturn fmt.Errorf(\"%w: %q (expiry)\", store.ErrCantEncode, key)\n\t\t}\n\n\t\tif err := valueBkt.Put([]byte(\"data\"), value); err != nil {\n\t\t\treturn fmt.Errorf(\"%w: %q (data)\", store.ErrCantEncode, key)\n\t\t}\n\n\t\treturn nil\n\t})\n}\n\nfunc (s *Store) cleanup(ctx context.Context) error {\n\tnow := time.Now()\n\n\treturn s.bdb.Update(func(tx *bbolt.Tx) error {\n\t\treturn tx.ForEach(func(key []byte, valueBkt *bbolt.Bucket) error {\n\t\t\tvar expiry time.Time\n\t\t\tvar err error\n\n\t\t\texpiryStr := valueBkt.Get([]byte(\"expiry\"))\n\t\t\tif expiryStr == nil {\n\t\t\t\tslog.Warn(\"while running cleanup, expiry is not set somehow, file a bug?\", \"key\", string(key))\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\texpiry, err = time.Parse(time.RFC3339Nano, string(expiryStr))\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"[unexpected] %w in bucket %q: %w\", store.ErrCantDecode, string(key), err)\n\t\t\t}\n\n\t\t\tif now.After(expiry) {\n\t\t\t\treturn tx.DeleteBucket(key)\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\t})\n}\n\nfunc (s *Store) cleanupThread(ctx context.Context) {\n\tt := time.NewTicker(time.Hour)\n\tdefer t.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase <-t.C:\n\t\t\tif err := s.cleanup(ctx); err != nil {\n\t\t\t\tslog.Error(\"error during bbolt cleanup\", \"err\", err)\n\t\t\t}\n\t\t}\n\t}\n}\n"], ["/anubis/lib/thoth/thoth.go", "package thoth\n\nimport (\n\t\"context\"\n\t\"crypto/tls\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\tiptoasnv1 \"github.com/TecharoHQ/thoth-proto/gen/techaro/thoth/iptoasn/v1\"\n\tgrpcprom \"github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus\"\n\t\"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/timeout\"\n\t\"github.com/prometheus/client_golang/prometheus\"\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/credentials\"\n\t\"google.golang.org/grpc/credentials/insecure\"\n\thealthv1 \"google.golang.org/grpc/health/grpc_health_v1\"\n)\n\ntype Client struct {\n\tconn *grpc.ClientConn\n\thealth healthv1.HealthClient\n\tIPToASN iptoasnv1.IpToASNServiceClient\n}\n\nfunc New(ctx context.Context, thothURL, apiToken string, plaintext bool) (*Client, error) {\n\tclMetrics := grpcprom.NewClientMetrics(\n\t\tgrpcprom.WithClientHandlingTimeHistogram(\n\t\t\tgrpcprom.WithHistogramBuckets([]float64{0.001, 0.01, 0.1, 0.3, 0.6, 1, 3, 6, 9, 20, 30, 60, 90, 120}),\n\t\t),\n\t)\n\tprometheus.DefaultRegisterer.Register(clMetrics)\n\n\tdo := []grpc.DialOption{\n\t\tgrpc.WithChainUnaryInterceptor(\n\t\t\ttimeout.UnaryClientInterceptor(500*time.Millisecond),\n\t\t\tclMetrics.UnaryClientInterceptor(),\n\t\t\tauthUnaryClientInterceptor(apiToken),\n\t\t),\n\t\tgrpc.WithChainStreamInterceptor(\n\t\t\tclMetrics.StreamClientInterceptor(),\n\t\t\tauthStreamClientInterceptor(apiToken),\n\t\t),\n\t\tgrpc.WithUserAgent(fmt.Sprint(\"Techaro/anubis:\", anubis.Version)),\n\t}\n\n\tif plaintext {\n\t\tdo = append(do, grpc.WithTransportCredentials(insecure.NewCredentials()))\n\t} else {\n\t\tdo = append(do, grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{})))\n\t}\n\n\tconn, err := grpc.NewClient(\n\t\tthothURL,\n\t\tdo...,\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't dial thoth at %s: %w\", thothURL, err)\n\t}\n\n\thc := healthv1.NewHealthClient(conn)\n\n\treturn &Client{\n\t\tconn: conn,\n\t\thealth: hc,\n\t\tIPToASN: NewIpToASNWithCache(iptoasnv1.NewIpToASNServiceClient(conn)),\n\t}, nil\n}\n\nfunc (c *Client) Close() error {\n\tif c.conn != nil {\n\t\treturn c.conn.Close()\n\t}\n\treturn nil\n}\n\nfunc (c *Client) WithIPToASNService(impl iptoasnv1.IpToASNServiceClient) {\n\tc.IPToASN = impl\n}\n"], ["/anubis/lib/challenge/interface.go", "package challenge\n\nimport (\n\t\"log/slog\"\n\t\"net/http\"\n\t\"sort\"\n\t\"sync\"\n\n\t\"github.com/TecharoHQ/anubis/lib/policy\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n\t\"github.com/a-h/templ\"\n)\n\nvar (\n\tregistry map[string]Impl = map[string]Impl{}\n\tregLock sync.RWMutex\n)\n\nfunc Register(name string, impl Impl) {\n\tregLock.Lock()\n\tdefer regLock.Unlock()\n\n\tregistry[name] = impl\n}\n\nfunc Get(name string) (Impl, bool) {\n\tregLock.RLock()\n\tdefer regLock.RUnlock()\n\tresult, ok := registry[name]\n\treturn result, ok\n}\n\nfunc Methods() []string {\n\tregLock.RLock()\n\tdefer regLock.RUnlock()\n\tvar result []string\n\tfor method := range registry {\n\t\tresult = append(result, method)\n\t}\n\tsort.Strings(result)\n\treturn result\n}\n\ntype IssueInput struct {\n\tImpressum *config.Impressum\n\tRule *policy.Bot\n\tChallenge *Challenge\n\tOGTags map[string]string\n\tStore store.Interface\n}\n\ntype ValidateInput struct {\n\tRule *policy.Bot\n\tChallenge *Challenge\n\tStore store.Interface\n}\n\ntype Impl interface {\n\t// Setup registers any additional routes with the Impl for assets or API routes.\n\tSetup(mux *http.ServeMux)\n\n\t// Issue a new challenge to the user, called by the Anubis.\n\tIssue(r *http.Request, lg *slog.Logger, in *IssueInput) (templ.Component, error)\n\n\t// Validate a challenge, making sure that it passes muster.\n\tValidate(r *http.Request, lg *slog.Logger, in *ValidateInput) error\n}\n"], ["/anubis/cmd/robots2policy/batch/batch_process.go", "/*\nBatch process robots.txt files from archives like https://github.com/nrjones8/robots-dot-txt-archive-bot/tree/master/data/cleaned\ninto Anubis CEL policies. Usage: go run batch_process.go \n*/\npackage main\n\nimport (\n\t\"fmt\"\n\t\"io/fs\"\n\t\"log\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\nfunc main() {\n\tif len(os.Args) < 2 {\n\t\tfmt.Println(\"Usage: go run batch_process.go \")\n\t\tfmt.Println(\"Example: go run batch_process.go ./cleaned\")\n\t\tos.Exit(1)\n\t}\n\n\tcleanedDir := os.Args[1]\n\toutputDir := \"generated_policies\"\n\n\t// Create output directory\n\tif err := os.MkdirAll(outputDir, 0755); err != nil {\n\t\tlog.Fatalf(\"Failed to create output directory: %v\", err)\n\t}\n\n\tcount := 0\n\terr := filepath.WalkDir(cleanedDir, func(path string, d fs.DirEntry, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Skip directories\n\t\tif d.IsDir() {\n\t\t\treturn nil\n\t\t}\n\n\t\t// Generate policy name from file path\n\t\trelPath, _ := filepath.Rel(cleanedDir, path)\n\t\tpolicyName := strings.ReplaceAll(relPath, \"/\", \"-\")\n\t\tpolicyName = strings.TrimSuffix(policyName, \"-robots.txt\")\n\t\tpolicyName = strings.ReplaceAll(policyName, \".\", \"-\")\n\n\t\toutputFile := filepath.Join(outputDir, policyName+\".yaml\")\n\n\t\tcmd := exec.Command(\"go\", \"run\", \"main.go\",\n\t\t\t\"-input\", path,\n\t\t\t\"-output\", outputFile,\n\t\t\t\"-name\", policyName,\n\t\t\t\"-format\", \"yaml\")\n\n\t\tif err := cmd.Run(); err != nil {\n\t\t\tfmt.Printf(\"Warning: Failed to process %s: %v\\n\", path, err)\n\t\t\treturn nil // Continue processing other files\n\t\t}\n\n\t\tcount++\n\t\tif count%100 == 0 {\n\t\t\tfmt.Printf(\"Processed %d files...\\n\", count)\n\t\t} else if count%10 == 0 {\n\t\t\tfmt.Print(\".\")\n\t\t}\n\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\tlog.Fatalf(\"Error walking directory: %v\", err)\n\t}\n\n\tfmt.Printf(\"Successfully processed %d robots.txt files\\n\", count)\n\tfmt.Printf(\"Generated policies saved to: %s/\\n\", outputDir)\n}\n"], ["/anubis/lib/challenge/metarefresh/metarefresh_templ.go", "// Code generated by templ - DO NOT EDIT.\n\n// templ: version: v0.3.906\npackage metarefresh\n\n//lint:file-ignore SA4006 This context is only used if a nested component is present.\n\nimport \"github.com/a-h/templ\"\nimport templruntime \"github.com/a-h/templ/runtime\"\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/TecharoHQ/anubis/lib/localization\"\n)\n\nfunc page(redir string, difficulty int, loc *localization.SimpleLocalizer) templ.Component {\n\treturn templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {\n\t\ttempl_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context\n\t\tif templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {\n\t\t\treturn templ_7745c5c3_CtxErr\n\t\t}\n\t\ttempl_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)\n\t\tif !templ_7745c5c3_IsBuffer {\n\t\t\tdefer func() {\n\t\t\t\ttempl_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)\n\t\t\t\tif templ_7745c5c3_Err == nil {\n\t\t\t\t\ttempl_7745c5c3_Err = templ_7745c5c3_BufErr\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\tctx = templ.InitializeContext(ctx)\n\t\ttempl_7745c5c3_Var1 := templ.GetChildren(ctx)\n\t\tif templ_7745c5c3_Var1 == nil {\n\t\t\ttempl_7745c5c3_Var1 = templ.NopComponent\n\t\t}\n\t\tctx = templ.ClearChildren(ctx)\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var4 string\n\t\ttempl_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(loc.T(\"loading\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `metarefresh.templ`, Line: 14, Col: 35}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var5 string\n\t\ttempl_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(loc.T(\"connection_security\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `metarefresh.templ`, Line: 15, Col: 35}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\treturn nil\n\t})\n}\n\nvar _ = templruntime.GeneratedTemplate\n"], ["/anubis/lib/store/valkey/factory.go", "package valkey\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n\tvalkey \"github.com/redis/go-redis/v9\"\n)\n\nvar (\n\tErrNoURL = errors.New(\"valkey.Config: no URL defined\")\n\tErrBadURL = errors.New(\"valkey.Config: URL is invalid\")\n)\n\nfunc init() {\n\tstore.Register(\"valkey\", Factory{})\n}\n\ntype Factory struct{}\n\nfunc (Factory) Build(ctx context.Context, data json.RawMessage) (store.Interface, error) {\n\tvar config Config\n\n\tif err := json.Unmarshal([]byte(data), &config); err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\tif err := config.Valid(); err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\topts, err := valkey.ParseURL(config.URL)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\trdb := valkey.NewClient(opts)\n\n\tif _, err := rdb.Ping(ctx).Result(); err != nil {\n\t\treturn nil, fmt.Errorf(\"can't ping valkey instance: %w\", err)\n\t}\n\n\treturn &Store{\n\t\trdb: rdb,\n\t}, nil\n}\n\nfunc (Factory) Valid(data json.RawMessage) error {\n\tvar config Config\n\tif err := json.Unmarshal([]byte(data), &config); err != nil {\n\t\treturn fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\tif err := config.Valid(); err != nil {\n\t\treturn fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\treturn nil\n}\n\ntype Config struct {\n\tURL string `json:\"url\"`\n}\n\nfunc (c Config) Valid() error {\n\tvar errs []error\n\n\tif c.URL == \"\" {\n\t\terrs = append(errs, ErrNoURL)\n\t}\n\n\tif _, err := valkey.ParseURL(c.URL); err != nil {\n\t\terrs = append(errs, ErrBadURL)\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"valkey.Config: invalid config: %w\", errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n"], ["/anubis/lib/localization/localization.go", "package localization\n\nimport (\n\t\"embed\"\n\t\"encoding/json\"\n\t\"net/http\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/nicksnyder/go-i18n/v2/i18n\"\n\t\"golang.org/x/text/language\"\n)\n\n//go:embed locales/*.json\nvar localeFS embed.FS\n\ntype LocalizationService struct {\n\tbundle *i18n.Bundle\n}\n\nvar (\n\tglobalService *LocalizationService\n\tonce sync.Once\n)\n\nfunc NewLocalizationService() *LocalizationService {\n\tonce.Do(func() {\n\t\tbundle := i18n.NewBundle(language.English)\n\t\tbundle.RegisterUnmarshalFunc(\"json\", json.Unmarshal)\n\n\t\t// Read all JSON files from the locales directory\n\t\tentries, err := localeFS.ReadDir(\"locales\")\n\t\tif err != nil {\n\t\t\t// Try fallback - create a minimal service with default messages\n\t\t\tglobalService = &LocalizationService{bundle: bundle}\n\t\t\treturn\n\t\t}\n\n\t\tloadedAny := false\n\t\tfor _, entry := range entries {\n\t\t\tif !entry.IsDir() && strings.HasSuffix(entry.Name(), \".json\") {\n\t\t\t\tfilePath := \"locales/\" + entry.Name()\n\t\t\t\t_, err := bundle.LoadMessageFileFS(localeFS, filePath)\n\t\t\t\tif err != nil {\n\t\t\t\t\t// Log error but continue with other files\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tloadedAny = true\n\t\t\t}\n\t\t}\n\n\t\tif !loadedAny {\n\t\t\t// If no files were loaded successfully, create minimal service\n\t\t\tglobalService = &LocalizationService{bundle: bundle}\n\t\t\treturn\n\t\t}\n\n\t\tglobalService = &LocalizationService{bundle: bundle}\n\t})\n\n\t// Safety check - if globalService is still nil, create a minimal one\n\tif globalService == nil {\n\t\tbundle := i18n.NewBundle(language.English)\n\t\tbundle.RegisterUnmarshalFunc(\"json\", json.Unmarshal)\n\t\tglobalService = &LocalizationService{bundle: bundle}\n\t}\n\n\treturn globalService\n}\n\nfunc (ls *LocalizationService) GetLocalizer(lang string) *i18n.Localizer {\n\treturn i18n.NewLocalizer(ls.bundle, lang)\n}\n\nfunc (ls *LocalizationService) GetLocalizerFromRequest(r *http.Request) *i18n.Localizer {\n\tif ls == nil || ls.bundle == nil {\n\t\t// Fallback to a basic bundle if service is not properly initialized\n\t\tbundle := i18n.NewBundle(language.English)\n\t\tbundle.RegisterUnmarshalFunc(\"json\", json.Unmarshal)\n\t\treturn i18n.NewLocalizer(bundle, \"en\")\n\t}\n\tacceptLanguage := r.Header.Get(\"Accept-Language\")\n\treturn i18n.NewLocalizer(ls.bundle, acceptLanguage, \"en\")\n}\n\n// SimpleLocalizer wraps i18n.Localizer with a more convenient API\ntype SimpleLocalizer struct {\n\tLocalizer *i18n.Localizer\n}\n\n// T provides a concise way to localize messages\nfunc (sl *SimpleLocalizer) T(messageID string) string {\n\treturn sl.Localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: messageID})\n}\n\n// Get the language that is used by the localizer by retrieving a well-known string that is required to be present\nfunc (sl *SimpleLocalizer) GetLang() string {\n\t_, tag, err := sl.Localizer.LocalizeWithTag(&i18n.LocalizeConfig{MessageID: \"loading\"})\n\tif err != nil {\n\t\treturn \"en\"\n\t}\n\treturn tag.String()\n}\n\n// GetLocalizer creates a localizer based on the request's Accept-Language header or forcedLanguage option\nfunc GetLocalizer(r *http.Request) *SimpleLocalizer {\n\tvar localizer *i18n.Localizer\n\tif anubis.ForcedLanguage == \"\" {\n\t\tlocalizer = NewLocalizationService().GetLocalizerFromRequest(r)\n\t} else {\n\t\tlocalizer = NewLocalizationService().GetLocalizer(anubis.ForcedLanguage)\n\t}\n\treturn &SimpleLocalizer{Localizer: localizer}\n}\n"], ["/anubis/lib/thoth/asnchecker.go", "package thoth\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net/http\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis/internal\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/checker\"\n\tiptoasnv1 \"github.com/TecharoHQ/thoth-proto/gen/techaro/thoth/iptoasn/v1\"\n)\n\nfunc (c *Client) ASNCheckerFor(asns []uint32) checker.Impl {\n\tasnMap := map[uint32]struct{}{}\n\tvar sb strings.Builder\n\tfmt.Fprintln(&sb, \"ASNChecker\")\n\tfor _, asn := range asns {\n\t\tasnMap[asn] = struct{}{}\n\t\tfmt.Fprintln(&sb, \"AS\", asn)\n\t}\n\n\treturn &ASNChecker{\n\t\tiptoasn: c.IPToASN,\n\t\tasns: asnMap,\n\t\thash: internal.FastHash(sb.String()),\n\t}\n}\n\ntype ASNChecker struct {\n\tiptoasn iptoasnv1.IpToASNServiceClient\n\tasns map[uint32]struct{}\n\thash string\n}\n\nfunc (asnc *ASNChecker) Check(r *http.Request) (bool, error) {\n\tctx, cancel := context.WithTimeout(r.Context(), 500*time.Millisecond)\n\tdefer cancel()\n\n\tipInfo, err := asnc.iptoasn.Lookup(ctx, &iptoasnv1.LookupRequest{\n\t\tIpAddress: r.Header.Get(\"X-Real-Ip\"),\n\t})\n\tif err != nil {\n\t\tswitch {\n\t\tcase errors.Is(err, context.DeadlineExceeded):\n\t\t\tslog.Debug(\"error contacting thoth\", \"err\", err, \"actionable\", false)\n\t\t\treturn false, nil\n\t\tdefault:\n\t\t\tslog.Error(\"error contacting thoth, please contact support\", \"err\", err, \"actionable\", true)\n\t\t\treturn false, nil\n\t\t}\n\t}\n\n\t// If IP is not publicly announced, return false\n\tif !ipInfo.GetAnnounced() {\n\t\treturn false, nil\n\t}\n\n\t_, ok := asnc.asns[uint32(ipInfo.GetAsNumber())]\n\n\treturn ok, nil\n}\n\nfunc (asnc *ASNChecker) Hash() string {\n\treturn asnc.hash\n}\n"], ["/anubis/lib/store/bbolt/factory.go", "package bbolt\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n\t\"go.etcd.io/bbolt\"\n)\n\nvar (\n\tErrMissingPath = errors.New(\"bbolt: path is missing from config\")\n\tErrCantWriteToPath = errors.New(\"bbolt: can't write to path\")\n)\n\nfunc init() {\n\tstore.Register(\"bbolt\", Factory{})\n}\n\n// Factory builds new instances of the bbolt storage backend according to\n// configuration passed via a json.RawMessage.\ntype Factory struct{}\n\n// Build parses and validates the bbolt storage backend Config and creates\n// a new instance of it.\nfunc (Factory) Build(ctx context.Context, data json.RawMessage) (store.Interface, error) {\n\tvar config Config\n\tif err := json.Unmarshal([]byte(data), &config); err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\tif err := config.Valid(); err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\tbdb, err := bbolt.Open(config.Path, 0600, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't open bbolt database %s: %w\", config.Path, err)\n\t}\n\n\tresult := &Store{\n\t\tbdb: bdb,\n\t}\n\n\tgo result.cleanupThread(ctx)\n\n\treturn result, nil\n}\n\n// Valid parses and validates the bbolt store Config or returns\n// an error.\nfunc (Factory) Valid(data json.RawMessage) error {\n\tvar config Config\n\tif err := json.Unmarshal([]byte(data), &config); err != nil {\n\t\treturn fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\tif err := config.Valid(); err != nil {\n\t\treturn fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\treturn nil\n}\n\n// Config is the bbolt storage backend configuration.\ntype Config struct {\n\t// Path is the filesystem path of the database. The folder must be writable to Anubis.\n\tPath string `json:\"path\"`\n}\n\n// Valid validates the configuration including checking if its containing folder is writable.\nfunc (c Config) Valid() error {\n\tvar errs []error\n\n\tif c.Path == \"\" {\n\t\terrs = append(errs, ErrMissingPath)\n\t} else {\n\t\tdir := filepath.Dir(c.Path)\n\t\tif err := os.WriteFile(filepath.Join(dir, \".test-file\"), []byte(\"\"), 0600); err != nil {\n\t\t\terrs = append(errs, ErrCantWriteToPath)\n\t\t}\n\t\tos.Remove(filepath.Join(dir, \".test-file\"))\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn errors.Join(errs...)\n\t}\n\n\treturn nil\n}\n"], ["/anubis/lib/policy/celchecker.go", "package policy\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/TecharoHQ/anubis/internal\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/expressions\"\n\t\"github.com/google/cel-go/cel\"\n\t\"github.com/google/cel-go/common/types\"\n)\n\ntype CELChecker struct {\n\tprogram cel.Program\n\tsrc string\n}\n\nfunc NewCELChecker(cfg *config.ExpressionOrList) (*CELChecker, error) {\n\tenv, err := expressions.BotEnvironment()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tprogram, err := expressions.Compile(env, cfg.String())\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't compile CEL program: %w\", err)\n\t}\n\n\treturn &CELChecker{\n\t\tsrc: cfg.String(),\n\t\tprogram: program,\n\t}, nil\n}\n\nfunc (cc *CELChecker) Hash() string {\n\treturn internal.FastHash(cc.src)\n}\n\nfunc (cc *CELChecker) Check(r *http.Request) (bool, error) {\n\tresult, _, err := cc.program.ContextEval(r.Context(), &CELRequest{r})\n\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tif val, ok := result.(types.Bool); ok {\n\t\treturn bool(val), nil\n\t}\n\n\treturn false, nil\n}\n\ntype CELRequest struct {\n\t*http.Request\n}\n\nfunc (cr *CELRequest) Parent() cel.Activation { return nil }\n\nfunc (cr *CELRequest) ResolveName(name string) (any, bool) {\n\tswitch name {\n\tcase \"remoteAddress\":\n\t\treturn cr.Header.Get(\"X-Real-Ip\"), true\n\tcase \"host\":\n\t\treturn cr.Host, true\n\tcase \"method\":\n\t\treturn cr.Method, true\n\tcase \"userAgent\":\n\t\treturn cr.UserAgent(), true\n\tcase \"path\":\n\t\treturn cr.URL.Path, true\n\tcase \"query\":\n\t\treturn expressions.URLValues{Values: cr.URL.Query()}, true\n\tcase \"headers\":\n\t\treturn expressions.HTTPHeaders{Header: cr.Header}, true\n\tcase \"load_1m\":\n\t\treturn expressions.Load1(), true\n\tcase \"load_5m\":\n\t\treturn expressions.Load5(), true\n\tcase \"load_15m\":\n\t\treturn expressions.Load15(), true\n\tdefault:\n\t\treturn nil, false\n\t}\n}\n"], ["/anubis/lib/thoth/geoipchecker.go", "package thoth\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net/http\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis/lib/policy/checker\"\n\tiptoasnv1 \"github.com/TecharoHQ/thoth-proto/gen/techaro/thoth/iptoasn/v1\"\n)\n\nfunc (c *Client) GeoIPCheckerFor(countries []string) checker.Impl {\n\tcountryMap := map[string]struct{}{}\n\tvar sb strings.Builder\n\tfmt.Fprintln(&sb, \"GeoIPChecker\")\n\tfor _, cc := range countries {\n\t\tcountryMap[cc] = struct{}{}\n\t\tfmt.Fprintln(&sb, cc)\n\t}\n\n\treturn &GeoIPChecker{\n\t\tIPToASN: c.IPToASN,\n\t\tCountries: countryMap,\n\t\thash: sb.String(),\n\t}\n}\n\ntype GeoIPChecker struct {\n\tIPToASN iptoasnv1.IpToASNServiceClient\n\tCountries map[string]struct{}\n\thash string\n}\n\nfunc (gipc *GeoIPChecker) Check(r *http.Request) (bool, error) {\n\tctx, cancel := context.WithTimeout(r.Context(), 500*time.Millisecond)\n\tdefer cancel()\n\n\tipInfo, err := gipc.IPToASN.Lookup(ctx, &iptoasnv1.LookupRequest{\n\t\tIpAddress: r.Header.Get(\"X-Real-Ip\"),\n\t})\n\tif err != nil {\n\t\tswitch {\n\t\tcase errors.Is(err, context.DeadlineExceeded):\n\t\t\tslog.Debug(\"error contacting thoth\", \"err\", err, \"actionable\", false)\n\t\t\treturn false, nil\n\t\tdefault:\n\t\t\tslog.Error(\"error contacting thoth, please contact support\", \"err\", err, \"actionable\", true)\n\t\t\treturn false, nil\n\t\t}\n\t}\n\n\t// If IP is not publicly announced, return false\n\tif !ipInfo.GetAnnounced() {\n\t\treturn false, nil\n\t}\n\n\t_, ok := gipc.Countries[strings.ToLower(ipInfo.GetCountryCode())]\n\n\treturn ok, nil\n}\n\nfunc (gipc *GeoIPChecker) Hash() string {\n\treturn gipc.hash\n}\n"], ["/anubis/lib/store/valkey/valkey.go", "package valkey\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n\tvalkey \"github.com/redis/go-redis/v9\"\n)\n\ntype Store struct {\n\trdb *valkey.Client\n}\n\nfunc (s *Store) Delete(ctx context.Context, key string) error {\n\tn, err := s.rdb.Del(ctx, key).Result()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"can't delete from valkey: %w\", err)\n\t}\n\n\tswitch n {\n\tcase 0:\n\t\treturn fmt.Errorf(\"%w: %d key(s) deleted\", store.ErrNotFound, n)\n\tdefault:\n\t\treturn nil\n\t}\n}\n\nfunc (s *Store) Get(ctx context.Context, key string) ([]byte, error) {\n\tresult, err := s.rdb.Get(ctx, key).Result()\n\tif err != nil {\n\t\tif valkey.HasErrorPrefix(err, \"redis: nil\") {\n\t\t\treturn nil, fmt.Errorf(\"%w: %w\", store.ErrNotFound, err)\n\t\t}\n\n\t\treturn nil, fmt.Errorf(\"can't fetch from valkey: %w\", err)\n\t}\n\n\treturn []byte(result), nil\n}\n\nfunc (s *Store) Set(ctx context.Context, key string, value []byte, expiry time.Duration) error {\n\tif _, err := s.rdb.Set(ctx, key, string(value), expiry).Result(); err != nil {\n\t\treturn fmt.Errorf(\"can't set %q in valkey: %w\", key, err)\n\t}\n\n\treturn nil\n}\n"], ["/anubis/lib/policy/config/threshold.go", "package config\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com/TecharoHQ/anubis\"\n)\n\nvar (\n\tErrNoThresholdRulesDefined = errors.New(\"config: no thresholds defined\")\n\tErrThresholdMustHaveName = errors.New(\"config.Threshold: must set name\")\n\tErrThresholdMustHaveExpression = errors.New(\"config.Threshold: must set expression\")\n\tErrThresholdChallengeMustHaveChallenge = errors.New(\"config.Threshold: a threshold with the CHALLENGE action must have challenge set\")\n\tErrThresholdCannotHaveWeighAction = errors.New(\"config.Threshold: a threshold cannot have the WEIGH action\")\n\n\tDefaultThresholds = []Threshold{\n\t\t{\n\t\t\tName: \"legacy-anubis-behaviour\",\n\t\t\tExpression: &ExpressionOrList{\n\t\t\t\tExpression: \"weight > 0\",\n\t\t\t},\n\t\t\tAction: RuleChallenge,\n\t\t\tChallenge: &ChallengeRules{\n\t\t\t\tAlgorithm: \"fast\",\n\t\t\t\tDifficulty: anubis.DefaultDifficulty,\n\t\t\t\tReportAs: anubis.DefaultDifficulty,\n\t\t\t},\n\t\t},\n\t}\n)\n\ntype Threshold struct {\n\tName string `json:\"name\" yaml:\"name\"`\n\tExpression *ExpressionOrList `json:\"expression\" yaml:\"expression\"`\n\tAction Rule `json:\"action\" yaml:\"action\"`\n\tChallenge *ChallengeRules `json:\"challenge\" yaml:\"challenge\"`\n}\n\nfunc (t Threshold) Valid() error {\n\tvar errs []error\n\n\tif len(t.Name) == 0 {\n\t\terrs = append(errs, ErrThresholdMustHaveName)\n\t}\n\n\tif t.Expression == nil {\n\t\terrs = append(errs, ErrThresholdMustHaveExpression)\n\t}\n\n\tif t.Expression != nil {\n\t\tif err := t.Expression.Valid(); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\tif err := t.Action.Valid(); err != nil {\n\t\terrs = append(errs, err)\n\t}\n\n\tif t.Action == RuleWeigh {\n\t\terrs = append(errs, ErrThresholdCannotHaveWeighAction)\n\t}\n\n\tif t.Action == RuleChallenge && t.Challenge == nil {\n\t\terrs = append(errs, ErrThresholdChallengeMustHaveChallenge)\n\t}\n\n\tif t.Challenge != nil {\n\t\tif err := t.Challenge.Valid(); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"config: threshold entry for %q is not valid:\\n%w\", t.Name, errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n"], ["/anubis/web/index_templ.go", "// Code generated by templ - DO NOT EDIT.\n\n// templ: version: v0.3.906\npackage web\n\n//lint:file-ignore SA4006 This context is only used if a nested component is present.\n\nimport \"github.com/a-h/templ\"\nimport templruntime \"github.com/a-h/templ/runtime\"\n\nimport (\n\t\"fmt\"\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/TecharoHQ/anubis/lib/localization\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/xess\"\n)\n\nfunc base(title string, body templ.Component, impressum *config.Impressum, challenge any, ogTags map[string]string, localizer *localization.SimpleLocalizer) templ.Component {\n\treturn templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {\n\t\ttempl_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context\n\t\tif templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {\n\t\t\treturn templ_7745c5c3_CtxErr\n\t\t}\n\t\ttempl_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)\n\t\tif !templ_7745c5c3_IsBuffer {\n\t\t\tdefer func() {\n\t\t\t\ttempl_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)\n\t\t\t\tif templ_7745c5c3_Err == nil {\n\t\t\t\t\ttempl_7745c5c3_Err = templ_7745c5c3_BufErr\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\tctx = templ.InitializeContext(ctx)\n\t\ttempl_7745c5c3_Var1 := templ.GetChildren(ctx)\n\t\tif templ_7745c5c3_Var1 == nil {\n\t\t\ttempl_7745c5c3_Var1 = templ.NopComponent\n\t\t}\n\t\tctx = templ.ClearChildren(ctx)\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, \"\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var3 string\n\t\ttempl_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(title)\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 15, Col: 17}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 3, \"\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tfor key, value := range ogTags {\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, \"\")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, \"\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templ.JSONScript(\"anubis_version\", anubis.Version).Render(ctx, templ_7745c5c3_Buffer)\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tif challenge != nil {\n\t\t\ttempl_7745c5c3_Err = templ.JSONScript(\"anubis_challenge\", challenge).Render(ctx, templ_7745c5c3_Buffer)\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t}\n\t\ttempl_7745c5c3_Err = templ.JSONScript(\"anubis_base_prefix\", anubis.BasePrefix).Render(ctx, templ_7745c5c3_Buffer)\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var7 string\n\t\ttempl_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(title)\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 68, Col: 47}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 10, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = body.Render(ctx, templ_7745c5c3_Buffer)\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var8 string\n\t\ttempl_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"protected_by\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 73, Col: 36}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, \" Anubis \")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var9 string\n\t\ttempl_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"protected_from\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 73, Col: 127}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, \" Techaro. \")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var10 string\n\t\ttempl_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"made_with\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 75, Col: 40}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 14, \".

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var11 string\n\t\ttempl_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"mascot_design\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 77, Col: 39}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, \" \")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var12 string\n\t\ttempl_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"celphase\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 77, Col: 123}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, \".

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tif impressum != nil {\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, \"

\")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\ttempl_7745c5c3_Err = templ.Raw(impressum.Footer).Render(ctx, templ_7745c5c3_Buffer)\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 18, \"-- Imprint

\")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 20, \"
\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\treturn nil\n\t})\n}\n\nfunc index(localizer *localization.SimpleLocalizer) templ.Component {\n\treturn templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {\n\t\ttempl_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context\n\t\tif templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {\n\t\t\treturn templ_7745c5c3_CtxErr\n\t\t}\n\t\ttempl_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)\n\t\tif !templ_7745c5c3_IsBuffer {\n\t\t\tdefer func() {\n\t\t\t\ttempl_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)\n\t\t\t\tif templ_7745c5c3_Err == nil {\n\t\t\t\t\ttempl_7745c5c3_Err = templ_7745c5c3_BufErr\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\tctx = templ.InitializeContext(ctx)\n\t\ttempl_7745c5c3_Var14 := templ.GetChildren(ctx)\n\t\tif templ_7745c5c3_Var14 == nil {\n\t\t\ttempl_7745c5c3_Var14 = templ.NopComponent\n\t\t}\n\t\tctx = templ.ClearChildren(ctx)\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 21, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var17 string\n\t\ttempl_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"loading\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 95, Col: 41}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var17))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 24, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var19 string\n\t\ttempl_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"why_am_i_seeing\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 101, Col: 44}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var19))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 26, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var20 string\n\t\ttempl_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"ai_companies_explanation\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 103, Col: 45}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var20))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 27, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var21 string\n\t\ttempl_7745c5c3_Var21, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"anubis_compromise\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 106, Col: 38}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var21))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var22 string\n\t\ttempl_7745c5c3_Var22, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"hack_purpose\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 109, Col: 33}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var22))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var23 string\n\t\ttempl_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"jshelter_note\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 112, Col: 34}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var23))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 30, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var24 string\n\t\ttempl_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"version_info\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 114, Col: 35}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var24))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 31, \" \")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var25 string\n\t\ttempl_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinStringErrs(anubis.Version)\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 114, Col: 60}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var25))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 32, \".

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\treturn nil\n\t})\n}\n\nfunc errorPage(message, mail string, localizer *localization.SimpleLocalizer) templ.Component {\n\treturn templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {\n\t\ttempl_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context\n\t\tif templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {\n\t\t\treturn templ_7745c5c3_CtxErr\n\t\t}\n\t\ttempl_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)\n\t\tif !templ_7745c5c3_IsBuffer {\n\t\t\tdefer func() {\n\t\t\t\ttempl_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)\n\t\t\t\tif templ_7745c5c3_Err == nil {\n\t\t\t\t\ttempl_7745c5c3_Err = templ_7745c5c3_BufErr\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\tctx = templ.InitializeContext(ctx)\n\t\ttempl_7745c5c3_Var27 := templ.GetChildren(ctx)\n\t\tif templ_7745c5c3_Var27 == nil {\n\t\t\ttempl_7745c5c3_Var27 = templ.NopComponent\n\t\t}\n\t\tctx = templ.ClearChildren(ctx)\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 34, \"
\\\"Sad

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var29 string\n\t\ttempl_7745c5c3_Var29, templ_7745c5c3_Err = templ.JoinStringErrs(message)\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 128, Col: 14}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var29))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 36, \".

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tif mail != \"\" {\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 37, \"

\")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\tvar templ_7745c5c3_Var30 string\n\t\t\ttempl_7745c5c3_Var30, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"go_home\"))\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 131, Col: 40}\n\t\t\t}\n\t\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var30))\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 38, \" \")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\tvar templ_7745c5c3_Var31 string\n\t\t\ttempl_7745c5c3_Var31, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"contact_webmaster\"))\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 131, Col: 81}\n\t\t\t}\n\t\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var31))\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 39, \" \")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\tvar templ_7745c5c3_Var33 string\n\t\t\ttempl_7745c5c3_Var33, templ_7745c5c3_Err = templ.JoinStringErrs(mail)\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 133, Col: 11}\n\t\t\t}\n\t\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var33))\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 41, \"

\")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t} else {\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 42, \"

\")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\tvar templ_7745c5c3_Var34 string\n\t\t\ttempl_7745c5c3_Var34, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"go_home\"))\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 137, Col: 42}\n\t\t\t}\n\t\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var34))\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 43, \"

\")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 44, \"
\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\treturn nil\n\t})\n}\n\nfunc StaticHappy(localizer *localization.SimpleLocalizer) templ.Component {\n\treturn templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {\n\t\ttempl_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context\n\t\tif templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {\n\t\t\treturn templ_7745c5c3_CtxErr\n\t\t}\n\t\ttempl_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)\n\t\tif !templ_7745c5c3_IsBuffer {\n\t\t\tdefer func() {\n\t\t\t\ttempl_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)\n\t\t\t\tif templ_7745c5c3_Err == nil {\n\t\t\t\t\ttempl_7745c5c3_Err = templ_7745c5c3_BufErr\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\tctx = templ.InitializeContext(ctx)\n\t\ttempl_7745c5c3_Var35 := templ.GetChildren(ctx)\n\t\tif templ_7745c5c3_Var35 == nil {\n\t\t\ttempl_7745c5c3_Var35 = templ.NopComponent\n\t\t}\n\t\tctx = templ.ClearChildren(ctx)\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 45, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var37 string\n\t\ttempl_7745c5c3_Var37, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"static_check_endpoint\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 150, Col: 43}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var37))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 47, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\treturn nil\n\t})\n}\n\nfunc bench(localizer *localization.SimpleLocalizer) templ.Component {\n\treturn templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {\n\t\ttempl_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context\n\t\tif templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {\n\t\t\treturn templ_7745c5c3_CtxErr\n\t\t}\n\t\ttempl_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)\n\t\tif !templ_7745c5c3_IsBuffer {\n\t\t\tdefer func() {\n\t\t\t\ttempl_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)\n\t\t\t\tif templ_7745c5c3_Err == nil {\n\t\t\t\t\ttempl_7745c5c3_Err = templ_7745c5c3_BufErr\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\tctx = templ.InitializeContext(ctx)\n\t\ttempl_7745c5c3_Var38 := templ.GetChildren(ctx)\n\t\tif templ_7745c5c3_Var38 == nil {\n\t\t\ttempl_7745c5c3_Var38 = templ.NopComponent\n\t\t}\n\t\tctx = templ.ClearChildren(ctx)\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 48, \"
\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var39 string\n\t\ttempl_7745c5c3_Var39, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"time\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 161, Col: 51}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var39))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 49, \"\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var40 string\n\t\ttempl_7745c5c3_Var40, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"iters\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 162, Col: 50}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var40))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 50, \"
\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var41 string\n\t\ttempl_7745c5c3_Var41, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"time_a\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 165, Col: 53}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var41))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 51, \"\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var42 string\n\t\ttempl_7745c5c3_Var42, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"iters_a\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 166, Col: 52}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var42))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 52, \"\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var43 string\n\t\ttempl_7745c5c3_Var43, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"time_b\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 167, Col: 53}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var43))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 53, \"\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var44 string\n\t\ttempl_7745c5c3_Var44, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"iters_b\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 168, Col: 52}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var44))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 54, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var46 string\n\t\ttempl_7745c5c3_Var46, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"loading\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 178, Col: 66}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var46))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 56, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\treturn nil\n\t})\n}\n\nvar _ = templruntime.GeneratedTemplate\n"], ["/anubis/lib/policy/expressions/environment.go", "package expressions\n\nimport (\n\t\"math/rand/v2\"\n\t\"strings\"\n\n\t\"github.com/google/cel-go/cel\"\n\t\"github.com/google/cel-go/common/types\"\n\t\"github.com/google/cel-go/common/types/ref\"\n\t\"github.com/google/cel-go/common/types/traits\"\n\t\"github.com/google/cel-go/ext\"\n)\n\n// BotEnvironment creates a new CEL environment, this is the set of\n// variables and functions that are passed into the CEL scope so that\n// Anubis can fail loudly and early when something is invalid instead\n// of blowing up at runtime.\nfunc BotEnvironment() (*cel.Env, error) {\n\treturn New(\n\t\t// Variables exposed to CEL programs:\n\t\tcel.Variable(\"remoteAddress\", cel.StringType),\n\t\tcel.Variable(\"host\", cel.StringType),\n\t\tcel.Variable(\"method\", cel.StringType),\n\t\tcel.Variable(\"userAgent\", cel.StringType),\n\t\tcel.Variable(\"path\", cel.StringType),\n\t\tcel.Variable(\"query\", cel.MapType(cel.StringType, cel.StringType)),\n\t\tcel.Variable(\"headers\", cel.MapType(cel.StringType, cel.StringType)),\n\t\tcel.Variable(\"load_1m\", cel.DoubleType),\n\t\tcel.Variable(\"load_5m\", cel.DoubleType),\n\t\tcel.Variable(\"load_15m\", cel.DoubleType),\n\n\t\t// Bot-specific functions:\n\t\tcel.Function(\"missingHeader\",\n\t\t\tcel.Overload(\"missingHeader_map_string_string_string\",\n\t\t\t\t[]*cel.Type{cel.MapType(cel.StringType, cel.StringType), cel.StringType},\n\t\t\t\tcel.BoolType,\n\t\t\t\tcel.BinaryBinding(func(headers, key ref.Val) ref.Val {\n\t\t\t\t\t// Convert headers to a trait that supports Find\n\t\t\t\t\theadersMap, ok := headers.(traits.Indexer)\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn types.ValOrErr(headers, \"headers is not a map, but is %T\", headers)\n\t\t\t\t\t}\n\n\t\t\t\t\tkeyStr, ok := key.(types.String)\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn types.ValOrErr(key, \"key is not a string, but is %T\", key)\n\t\t\t\t\t}\n\n\t\t\t\t\tval := headersMap.Get(keyStr)\n\t\t\t\t\t// Check if the key is missing by testing for an error\n\t\t\t\t\tif types.IsError(val) {\n\t\t\t\t\t\treturn types.Bool(true) // header is missing\n\t\t\t\t\t}\n\t\t\t\t\treturn types.Bool(false) // header is present\n\t\t\t\t}),\n\t\t\t),\n\t\t),\n\n\t\tcel.Function(\"segments\",\n\t\t\tcel.Overload(\"segments_string_list_string\",\n\t\t\t\t[]*cel.Type{cel.StringType},\n\t\t\t\tcel.ListType(cel.StringType),\n\t\t\t\tcel.UnaryBinding(func(path ref.Val) ref.Val {\n\t\t\t\t\tpathStrType, ok := path.(types.String)\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn types.ValOrErr(path, \"path is not a string, but is %T\", path)\n\t\t\t\t\t}\n\n\t\t\t\t\tpathStr := string(pathStrType)\n\t\t\t\t\tif !strings.HasPrefix(pathStr, \"/\") {\n\t\t\t\t\t\treturn types.ValOrErr(path, \"path does not start with /\")\n\t\t\t\t\t}\n\n\t\t\t\t\tpathList := strings.Split(string(pathStr), \"/\")[1:]\n\n\t\t\t\t\treturn types.NewStringList(types.DefaultTypeAdapter, pathList)\n\t\t\t\t}),\n\t\t\t),\n\t\t),\n\t)\n}\n\n// NewThreshold creates a new CEL environment for threshold checking.\nfunc ThresholdEnvironment() (*cel.Env, error) {\n\treturn New(\n\t\tcel.Variable(\"weight\", cel.IntType),\n\t)\n}\n\nfunc New(opts ...cel.EnvOption) (*cel.Env, error) {\n\targs := []cel.EnvOption{\n\t\text.Strings(\n\t\t\text.StringsLocale(\"en_US\"),\n\t\t\text.StringsValidateFormatCalls(true),\n\t\t),\n\n\t\t// default all timestamps to UTC\n\t\tcel.DefaultUTCTimeZone(true),\n\n\t\t// Functions exposed to all CEL programs:\n\t\tcel.Function(\"randInt\",\n\t\t\tcel.Overload(\"randInt_int\",\n\t\t\t\t[]*cel.Type{cel.IntType},\n\t\t\t\tcel.IntType,\n\t\t\t\tcel.UnaryBinding(func(val ref.Val) ref.Val {\n\t\t\t\t\tn, ok := val.(types.Int)\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn types.ValOrErr(val, \"value is not an integer, but is %T\", val)\n\t\t\t\t\t}\n\n\t\t\t\t\treturn types.Int(rand.IntN(int(n)))\n\t\t\t\t}),\n\t\t\t),\n\t\t),\n\t}\n\n\targs = append(args, opts...)\n\treturn cel.NewEnv(args...)\n}\n\n// Compile takes CEL environment and syntax tree then emits an optimized\n// Program for execution.\nfunc Compile(env *cel.Env, src string) (cel.Program, error) {\n\tintermediate, iss := env.Compile(src)\n\tif iss != nil {\n\t\treturn nil, iss.Err()\n\t}\n\n\tast, iss := env.Check(intermediate)\n\tif iss != nil {\n\t\treturn nil, iss.Err()\n\t}\n\n\treturn env.Program(\n\t\tast,\n\t\tcel.EvalOptions(\n\t\t\t// optimize regular expressions right now instead of on the fly\n\t\t\tcel.OptOptimize,\n\t\t),\n\t)\n}\n"], ["/anubis/lib/store/memory/memory.go", "package memory\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis/decaymap\"\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n)\n\ntype factory struct{}\n\nfunc (factory) Build(ctx context.Context, _ json.RawMessage) (store.Interface, error) {\n\treturn New(ctx), nil\n}\n\nfunc (factory) Valid(json.RawMessage) error { return nil }\n\nfunc init() {\n\tstore.Register(\"memory\", factory{})\n}\n\ntype impl struct {\n\tstore *decaymap.Impl[string, []byte]\n}\n\nfunc (i *impl) Delete(_ context.Context, key string) error {\n\tif !i.store.Delete(key) {\n\t\treturn fmt.Errorf(\"%w: %q\", store.ErrNotFound, key)\n\t}\n\n\treturn nil\n}\n\nfunc (i *impl) Get(_ context.Context, key string) ([]byte, error) {\n\tresult, ok := i.store.Get(key)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"%w: %q\", store.ErrNotFound, key)\n\t}\n\n\treturn result, nil\n}\n\nfunc (i *impl) Set(_ context.Context, key string, value []byte, expiry time.Duration) error {\n\ti.store.Set(key, value, expiry)\n\treturn nil\n}\n\nfunc (i *impl) cleanupThread(ctx context.Context) {\n\tt := time.NewTicker(5 * time.Minute)\n\tdefer t.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase <-t.C:\n\t\t\ti.store.Cleanup()\n\t\t}\n\t}\n}\n\n// New creates a simple in-memory store. This will not scale to multiple Anubis instances.\nfunc New(ctx context.Context) store.Interface {\n\tresult := &impl{\n\t\tstore: decaymap.New[string, []byte](),\n\t}\n\n\tgo result.cleanupThread(ctx)\n\n\treturn result\n}\n"], ["/anubis/lib/policy/config/opengraph.go", "package config\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"time\"\n)\n\nvar (\n\tErrInvalidOpenGraphConfig = errors.New(\"config.OpenGraph: invalid OpenGraph configuration\")\n\tErrOpenGraphTTLDoesNotParse = errors.New(\"config.OpenGraph: ttl does not parse as a Duration, see https://pkg.go.dev/time#ParseDuration (formatted like 5m -> 5 minutes, 2h -> 2 hours, etc)\")\n\tErrOpenGraphMissingProperty = errors.New(\"config.OpenGraph: default opengraph tags missing a property\")\n)\n\ntype openGraphFileConfig struct {\n\tEnabled bool `json:\"enabled\" yaml:\"enabled\"`\n\tConsiderHost bool `json:\"considerHost\" yaml:\"enabled\"`\n\tTimeToLive string `json:\"ttl\" yaml:\"ttl\"`\n\tOverride map[string]string `json:\"override,omitempty\" yaml:\"override,omitempty\"`\n}\n\ntype OpenGraph struct {\n\tEnabled bool `json:\"enabled\" yaml:\"enabled\"`\n\tConsiderHost bool `json:\"considerHost\" yaml:\"enabled\"`\n\tOverride map[string]string `json:\"override,omitempty\" yaml:\"override,omitempty\"`\n\tTimeToLive time.Duration `json:\"ttl\" yaml:\"ttl\"`\n}\n\nfunc (og *openGraphFileConfig) Valid() error {\n\tvar errs []error\n\n\tif _, err := time.ParseDuration(og.TimeToLive); err != nil {\n\t\terrs = append(errs, fmt.Errorf(\"%w: ParseDuration(%q) returned: %w\", ErrOpenGraphTTLDoesNotParse, og.TimeToLive, err))\n\t}\n\n\tif len(og.Override) != 0 {\n\t\tfor _, tag := range []string{\n\t\t\t\"og:title\",\n\t\t} {\n\t\t\tif _, ok := og.Override[tag]; !ok {\n\t\t\t\terrs = append(errs, fmt.Errorf(\"%w: %s\", ErrOpenGraphMissingProperty, tag))\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn errors.Join(ErrInvalidOpenGraphConfig, errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n"], ["/anubis/lib/policy/config/store.go", "package config\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n\t_ \"github.com/TecharoHQ/anubis/lib/store/all\"\n)\n\nvar (\n\tErrNoStoreBackend = errors.New(\"config.Store: no backend defined\")\n\tErrUnknownStoreBackend = errors.New(\"config.Store: unknown backend\")\n)\n\ntype Store struct {\n\tBackend string `json:\"backend\"`\n\tParameters json.RawMessage `json:\"parameters\"`\n}\n\nfunc (s *Store) Valid() error {\n\tvar errs []error\n\n\tif len(s.Backend) == 0 {\n\t\terrs = append(errs, ErrNoStoreBackend)\n\t}\n\n\tfac, ok := store.Get(s.Backend)\n\tswitch ok {\n\tcase true:\n\t\tif err := fac.Valid(s.Parameters); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\tcase false:\n\t\terrs = append(errs, fmt.Errorf(\"%w: %q\", ErrUnknownStoreBackend, s.Backend))\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn errors.Join(errs...)\n\t}\n\n\treturn nil\n}\n"], ["/anubis/web/index.go", "package web\n\nimport (\n\t\"github.com/a-h/templ\"\n\n\t\"github.com/TecharoHQ/anubis/lib/localization\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n)\n\nfunc Base(title string, body templ.Component, impressum *config.Impressum, localizer *localization.SimpleLocalizer) templ.Component {\n\treturn base(title, body, impressum, nil, nil, localizer)\n}\n\nfunc BaseWithChallengeAndOGTags(title string, body templ.Component, impressum *config.Impressum, challenge string, rules *config.ChallengeRules, ogTags map[string]string, localizer *localization.SimpleLocalizer) (templ.Component, error) {\n\treturn base(title, body, impressum, struct {\n\t\tRules *config.ChallengeRules `json:\"rules\"`\n\t\tChallenge string `json:\"challenge\"`\n\t}{\n\t\tChallenge: challenge,\n\t\tRules: rules,\n\t}, ogTags, localizer), nil\n}\n\nfunc Index(localizer *localization.SimpleLocalizer) templ.Component {\n\treturn index(localizer)\n}\n\nfunc ErrorPage(msg, mail string, localizer *localization.SimpleLocalizer) templ.Component {\n\treturn errorPage(msg, mail, localizer)\n}\n\nfunc Bench(localizer *localization.SimpleLocalizer) templ.Component {\n\treturn bench(localizer)\n}\n"], ["/anubis/lib/thoth/thothmock/iptoasn.go", "package thothmock\n\nimport (\n\t\"context\"\n\t\"net/netip\"\n\n\tiptoasnv1 \"github.com/TecharoHQ/thoth-proto/gen/techaro/thoth/iptoasn/v1\"\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/status\"\n)\n\nfunc MockIpToASNService() *IpToASNService {\n\tresponses := map[string]*iptoasnv1.LookupResponse{\n\t\t\"127.0.0.1\": {Announced: false},\n\t\t\"::1\": {Announced: false},\n\t\t\"10.10.10.10\": {\n\t\t\tAnnounced: true,\n\t\t\tAsNumber: 13335,\n\t\t\tCidr: []string{\"1.1.1.0/24\"},\n\t\t\tCountryCode: \"US\",\n\t\t\tDescription: \"Cloudflare\",\n\t\t},\n\t\t\"2.2.2.2\": {\n\t\t\tAnnounced: true,\n\t\t\tAsNumber: 420,\n\t\t\tCidr: []string{\"2.2.2.0/24\"},\n\t\t\tCountryCode: \"CA\",\n\t\t\tDescription: \"test canada\",\n\t\t},\n\t\t\"1.1.1.1\": {\n\t\t\tAnnounced: true,\n\t\t\tAsNumber: 13335,\n\t\t\tCidr: []string{\"1.1.1.0/24\"},\n\t\t\tCountryCode: \"US\",\n\t\t\tDescription: \"Cloudflare\",\n\t\t},\n\t}\n\n\treturn &IpToASNService{Responses: responses}\n}\n\ntype IpToASNService struct {\n\tiptoasnv1.UnimplementedIpToASNServiceServer\n\tResponses map[string]*iptoasnv1.LookupResponse\n}\n\nfunc (ip2asn *IpToASNService) Lookup(ctx context.Context, lr *iptoasnv1.LookupRequest, opts ...grpc.CallOption) (*iptoasnv1.LookupResponse, error) {\n\tif _, err := netip.ParseAddr(lr.GetIpAddress()); err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, ok := ip2asn.Responses[lr.GetIpAddress()]\n\tif !ok {\n\t\treturn nil, status.Error(codes.NotFound, \"IP address not found in mock\")\n\t}\n\n\treturn resp, nil\n}\n"], ["/anubis/lib/store/interface.go", "package store\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"time\"\n)\n\nvar (\n\t// ErrNotFound is returned when the store implementation cannot find the value\n\t// for a given key.\n\tErrNotFound = errors.New(\"store: key not found\")\n\n\t// ErrCantDecode is returned when a store adaptor cannot decode the store format\n\t// to a value used by the code.\n\tErrCantDecode = errors.New(\"store: can't decode value\")\n\n\t// ErrCantEncode is returned when a store adaptor cannot encode the value into\n\t// the format that the store uses.\n\tErrCantEncode = errors.New(\"store: can't encode value\")\n\n\t// ErrBadConfig is returned when a store adaptor's configuration is invalid.\n\tErrBadConfig = errors.New(\"store: configuration is invalid\")\n)\n\n// Interface defines the calls that Anubis uses for storage in a local or remote\n// datastore. This can be implemented with an in-memory, on-disk, or in-database\n// storage backend.\ntype Interface interface {\n\t// Delete removes a value from the store by key.\n\tDelete(ctx context.Context, key string) error\n\n\t// Get returns the value of a key assuming that value exists and has not expired.\n\tGet(ctx context.Context, key string) ([]byte, error)\n\n\t// Set puts a value into the store that expires according to its expiry.\n\tSet(ctx context.Context, key string, value []byte, expiry time.Duration) error\n}\n\nfunc z[T any]() T { return *new(T) }\n\ntype JSON[T any] struct {\n\tUnderlying Interface\n\tPrefix string\n}\n\nfunc (j *JSON[T]) Delete(ctx context.Context, key string) error {\n\tif j.Prefix != \"\" {\n\t\tkey = j.Prefix + key\n\t}\n\n\treturn j.Underlying.Delete(ctx, key)\n}\n\nfunc (j *JSON[T]) Get(ctx context.Context, key string) (T, error) {\n\tif j.Prefix != \"\" {\n\t\tkey = j.Prefix + key\n\t}\n\n\tdata, err := j.Underlying.Get(ctx, key)\n\tif err != nil {\n\t\treturn z[T](), err\n\t}\n\n\tvar result T\n\tif err := json.Unmarshal(data, &result); err != nil {\n\t\treturn z[T](), fmt.Errorf(\"%w: %w\", ErrCantDecode, err)\n\t}\n\n\treturn result, nil\n}\n\nfunc (j *JSON[T]) Set(ctx context.Context, key string, value T, expiry time.Duration) error {\n\tif j.Prefix != \"\" {\n\t\tkey = j.Prefix + key\n\t}\n\n\tdata, err := json.Marshal(value)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%w: %w\", ErrCantEncode, err)\n\t}\n\n\tif err := j.Underlying.Set(ctx, key, data, expiry); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n"], ["/anubis/internal/gzip.go", "package internal\n\nimport (\n\t\"compress/gzip\"\n\t\"net/http\"\n\t\"strings\"\n)\n\nfunc GzipMiddleware(level int, next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif !strings.Contains(r.Header.Get(\"Accept-Encoding\"), \"gzip\") {\n\t\t\tnext.ServeHTTP(w, r)\n\t\t\treturn\n\t\t}\n\n\t\tw.Header().Set(\"Content-Encoding\", \"gzip\")\n\t\tgz, err := gzip.NewWriterLevel(w, level)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tdefer gz.Close()\n\n\t\tgrw := gzipResponseWriter{ResponseWriter: w, sink: gz}\n\t\tnext.ServeHTTP(grw, r)\n\t})\n}\n\ntype gzipResponseWriter struct {\n\thttp.ResponseWriter\n\tsink *gzip.Writer\n}\n\nfunc (w gzipResponseWriter) Write(b []byte) (int, error) {\n\treturn w.sink.Write(b)\n}\n"], ["/anubis/lib/policy/thresholds.go", "package policy\n\nimport (\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/expressions\"\n\t\"github.com/google/cel-go/cel\"\n)\n\ntype Threshold struct {\n\tconfig.Threshold\n\tProgram cel.Program\n}\n\nfunc ParsedThresholdFromConfig(t config.Threshold) (*Threshold, error) {\n\tresult := &Threshold{\n\t\tThreshold: t,\n\t}\n\n\tenv, err := expressions.ThresholdEnvironment()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tprogram, err := expressions.Compile(env, t.Expression.String())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult.Program = program\n\n\treturn result, nil\n}\n\ntype ThresholdRequest struct {\n\tWeight int\n}\n\nfunc (tr *ThresholdRequest) Parent() cel.Activation { return nil }\n\nfunc (tr *ThresholdRequest) ResolveName(name string) (any, bool) {\n\tswitch name {\n\tcase \"weight\":\n\t\treturn tr.Weight, true\n\tdefault:\n\t\treturn nil, false\n\t}\n}\n"], ["/anubis/internal/log.go", "package internal\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"log/slog\"\n\t\"net/http\"\n\t\"os\"\n\t\"strings\"\n)\n\nfunc InitSlog(level string) {\n\tvar programLevel slog.Level\n\tif err := (&programLevel).UnmarshalText([]byte(level)); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"invalid log level %s: %v, using info\\n\", level, err)\n\t\tprogramLevel = slog.LevelInfo\n\t}\n\n\tleveler := &slog.LevelVar{}\n\tleveler.Set(programLevel)\n\n\th := slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{\n\t\tAddSource: true,\n\t\tLevel: leveler,\n\t})\n\tslog.SetDefault(slog.New(h))\n}\n\nfunc GetRequestLogger(r *http.Request) *slog.Logger {\n\treturn slog.With(\n\t\t\"user_agent\", r.UserAgent(),\n\t\t\"accept_language\", r.Header.Get(\"Accept-Language\"),\n\t\t\"priority\", r.Header.Get(\"Priority\"),\n\t\t\"x-forwarded-for\",\n\t\tr.Header.Get(\"X-Forwarded-For\"),\n\t\t\"x-real-ip\", r.Header.Get(\"X-Real-Ip\"),\n\t)\n}\n\n// ErrorLogFilter is used to suppress \"context canceled\" logs from the http server when a request is canceled (e.g., when a client disconnects).\ntype ErrorLogFilter struct {\n\tUnwrap *log.Logger\n}\n\nfunc (elf *ErrorLogFilter) Write(p []byte) (n int, err error) {\n\tlogMessage := string(p)\n\tif strings.Contains(logMessage, \"context canceled\") {\n\t\treturn len(p), nil // Suppress the log by doing nothing\n\t}\n\tif elf.Unwrap != nil {\n\t\treturn elf.Unwrap.Writer().Write(p)\n\t}\n\treturn len(p), nil\n}\n\nfunc GetFilteredHTTPLogger() *log.Logger {\n\tstdErrLogger := log.New(os.Stderr, \"\", log.LstdFlags) // essentially what the default logger is.\n\treturn log.New(&ErrorLogFilter{Unwrap: stdErrLogger}, \"\", 0)\n}\n"], ["/anubis/lib/policy/config/asn.go", "package config\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\nvar (\n\tErrPrivateASN = errors.New(\"bot.ASNs: you have specified a private use ASN\")\n)\n\ntype ASNs struct {\n\tMatch []uint32 `json:\"match\"`\n}\n\nfunc (a *ASNs) Valid() error {\n\tvar errs []error\n\n\tfor _, asn := range a.Match {\n\t\tif isPrivateASN(asn) {\n\t\t\terrs = append(errs, fmt.Errorf(\"%w: %d is private (see RFC 6996)\", ErrPrivateASN, asn))\n\t\t}\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"bot.ASNs: invalid ASN settings: %w\", errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n\n// isPrivateASN checks if an ASN is in the private use area.\n//\n// Based on RFC 6996 and IANA allocations.\nfunc isPrivateASN(asn uint32) bool {\n\tswitch {\n\tcase asn >= 64512 && asn <= 65534:\n\t\treturn true\n\tcase asn >= 4200000000 && asn <= 4294967294:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n"], ["/anubis/internal/dnsbl/dnsbl.go", "package dnsbl\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net\"\n\t\"strings\"\n)\n\n//go:generate go tool golang.org/x/tools/cmd/stringer -type=DroneBLResponse\n\ntype DroneBLResponse byte\n\nconst (\n\tAllGood DroneBLResponse = 0\n\tIRCDrone DroneBLResponse = 3\n\tBottler DroneBLResponse = 5\n\tUnknownSpambotOrDrone DroneBLResponse = 6\n\tDDOSDrone DroneBLResponse = 7\n\tSOCKSProxy DroneBLResponse = 8\n\tHTTPProxy DroneBLResponse = 9\n\tProxyChain DroneBLResponse = 10\n\tOpenProxy DroneBLResponse = 11\n\tOpenDNSResolver DroneBLResponse = 12\n\tBruteForceAttackers DroneBLResponse = 13\n\tOpenWingateProxy DroneBLResponse = 14\n\tCompromisedRouter DroneBLResponse = 15\n\tAutoRootingWorms DroneBLResponse = 16\n\tAutoDetectedBotIP DroneBLResponse = 17\n\tUnknown DroneBLResponse = 255\n)\n\nfunc Reverse(ip net.IP) string {\n\tif ip.To4() != nil {\n\t\treturn reverse4(ip)\n\t}\n\n\treturn reverse6(ip)\n}\n\nfunc reverse4(ip net.IP) string {\n\tsplitAddress := strings.Split(ip.String(), \".\")\n\n\t// swap first and last octet\n\tsplitAddress[0], splitAddress[3] = splitAddress[3], splitAddress[0]\n\t// swap middle octets\n\tsplitAddress[1], splitAddress[2] = splitAddress[2], splitAddress[1]\n\n\treturn strings.Join(splitAddress, \".\")\n}\n\nfunc reverse6(ip net.IP) string {\n\tipBytes := []byte(ip)\n\tvar sb strings.Builder\n\n\tfor i := len(ipBytes) - 1; i >= 0; i-- {\n\t\t// Split the byte into two nibbles\n\t\thighNibble := ipBytes[i] >> 4\n\t\tlowNibble := ipBytes[i] & 0x0F\n\n\t\t// Append the nibbles in reversed order\n\t\tsb.WriteString(fmt.Sprintf(\"%x.%x.\", lowNibble, highNibble))\n\t}\n\n\treturn sb.String()[:len(sb.String())-1]\n}\n\nfunc Lookup(ipStr string) (DroneBLResponse, error) {\n\tip := net.ParseIP(ipStr)\n\tif ip == nil {\n\t\treturn Unknown, errors.New(\"dnsbl: input is not an IP address\")\n\t}\n\n\trevIP := Reverse(ip) + \".dnsbl.dronebl.org\"\n\n\tips, err := net.LookupIP(revIP)\n\tif err != nil {\n\t\tvar dnserr *net.DNSError\n\t\tif errors.As(err, &dnserr) {\n\t\t\tif dnserr.IsNotFound {\n\t\t\t\treturn AllGood, nil\n\t\t\t}\n\t\t}\n\n\t\treturn Unknown, err\n\t}\n\n\tif len(ips) != 0 {\n\t\tfor _, ip := range ips {\n\t\t\treturn DroneBLResponse(ip.To4()[3]), nil\n\t\t}\n\t}\n\n\treturn UnknownSpambotOrDrone, nil\n}\n"], ["/anubis/lib/policy/bot.go", "package policy\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/TecharoHQ/anubis/internal\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/checker\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n)\n\ntype Bot struct {\n\tRules checker.Impl\n\tChallenge *config.ChallengeRules\n\tWeight *config.Weight\n\tName string\n\tAction config.Rule\n}\n\nfunc (b Bot) Hash() string {\n\treturn internal.FastHash(fmt.Sprintf(\"%s::%s\", b.Name, b.Rules.Hash()))\n}\n"], ["/anubis/anubis.go", "// Package anubis contains the version number of Anubis.\npackage anubis\n\nimport \"time\"\n\n// Version is the current version of Anubis.\n//\n// This variable is set at build time using the -X linker flag. If not set,\n// it defaults to \"devel\".\nvar Version = \"devel\"\n\n// CookieName is the name of the cookie that Anubis uses in order to validate\n// access.\nvar CookieName = \"techaro.lol-anubis-auth\"\n\n// TestCookieName is the name of the cookie that Anubis uses in order to check\n// if cookies are enabled on the client's browser.\nvar TestCookieName = \"techaro.lol-anubis-cookie-verification\"\n\n// CookieDefaultExpirationTime is the amount of time before the cookie/JWT expires.\nconst CookieDefaultExpirationTime = 7 * 24 * time.Hour\n\n// BasePrefix is a global prefix for all Anubis endpoints. Can be emptied to remove the prefix entirely.\nvar BasePrefix = \"\"\n\n// StaticPath is the location where all static Anubis assets are located.\nconst StaticPath = \"/.within.website/x/cmd/anubis/\"\n\n// APIPrefix is the location where all Anubis API endpoints are located.\nconst APIPrefix = \"/.within.website/x/cmd/anubis/api/\"\n\n// DefaultDifficulty is the default \"difficulty\" (number of leading zeroes)\n// that must be met by the client in order to pass the challenge.\nconst DefaultDifficulty = 4\n\n// ForcedLanguage is the language being used instead of the one of the request's Accept-Language header\n// if being set.\nvar ForcedLanguage = \"\"\n"], ["/anubis/lib/policy/config/impressum.go", "package config\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n)\n\nvar ErrMissingValue = errors.New(\"config: missing value\")\n\ntype Impressum struct {\n\tFooter string `json:\"footer\" yaml:\"footer\"`\n\tPage ImpressumPage `json:\"page\" yaml:\"page\"`\n}\n\nfunc (i Impressum) Render(_ context.Context, w io.Writer) error {\n\tif _, err := fmt.Fprint(w, i.Footer); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (i Impressum) Valid() error {\n\tvar errs []error\n\n\tif len(i.Footer) == 0 {\n\t\terrs = append(errs, fmt.Errorf(\"%w: impressum footer must be defined\", ErrMissingValue))\n\t}\n\n\tif err := i.Page.Valid(); err != nil {\n\t\terrs = append(errs, err)\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn errors.Join(errs...)\n\t}\n\n\treturn nil\n}\n\ntype ImpressumPage struct {\n\tTitle string `json:\"title\" yaml:\"title\"`\n\tBody string `json:\"body\" yaml:\"body\"`\n}\n\nfunc (ip ImpressumPage) Render(_ context.Context, w io.Writer) error {\n\tif _, err := fmt.Fprint(w, ip.Body); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (ip ImpressumPage) Valid() error {\n\tvar errs []error\n\n\tif len(ip.Title) == 0 {\n\t\terrs = append(errs, fmt.Errorf(\"%w: impressum page title must be defined\", ErrMissingValue))\n\t}\n\n\tif len(ip.Body) == 0 {\n\t\terrs = append(errs, fmt.Errorf(\"%w: impressum body title must be defined\", ErrMissingValue))\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn errors.Join(errs...)\n\t}\n\n\treturn nil\n}\n"], ["/anubis/lib/policy/config/expressionorlist.go", "package config\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"slices\"\n\t\"strings\"\n)\n\nvar (\n\tErrExpressionOrListMustBeStringOrObject = errors.New(\"config: this must be a string or an object\")\n\tErrExpressionEmpty = errors.New(\"config: this expression is empty\")\n\tErrExpressionCantHaveBoth = errors.New(\"config: expression block can't contain multiple expression types\")\n)\n\ntype ExpressionOrList struct {\n\tExpression string `json:\"-\" yaml:\"-\"`\n\tAll []string `json:\"all,omitempty\" yaml:\"all,omitempty\"`\n\tAny []string `json:\"any,omitempty\" yaml:\"any,omitempty\"`\n}\n\nfunc (eol ExpressionOrList) String() string {\n\tswitch {\n\tcase len(eol.Expression) != 0:\n\t\treturn eol.Expression\n\tcase len(eol.All) != 0:\n\t\tvar sb strings.Builder\n\t\tfor i, pred := range eol.All {\n\t\t\tif i != 0 {\n\t\t\t\tfmt.Fprintf(&sb, \" && \")\n\t\t\t}\n\t\t\tfmt.Fprintf(&sb, \"( %s )\", pred)\n\t\t}\n\t\treturn sb.String()\n\tcase len(eol.Any) != 0:\n\t\tvar sb strings.Builder\n\t\tfor i, pred := range eol.Any {\n\t\t\tif i != 0 {\n\t\t\t\tfmt.Fprintf(&sb, \" || \")\n\t\t\t}\n\t\t\tfmt.Fprintf(&sb, \"( %s )\", pred)\n\t\t}\n\t\treturn sb.String()\n\t}\n\tpanic(\"this should not happen\")\n}\n\nfunc (eol ExpressionOrList) Equal(rhs *ExpressionOrList) bool {\n\tif eol.Expression != rhs.Expression {\n\t\treturn false\n\t}\n\n\tif !slices.Equal(eol.All, rhs.All) {\n\t\treturn false\n\t}\n\n\tif !slices.Equal(eol.Any, rhs.Any) {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\nfunc (eol *ExpressionOrList) MarshalYAML() (any, error) {\n\tswitch {\n\tcase len(eol.All) == 1 && len(eol.Any) == 0:\n\t\teol.Expression = eol.All[0]\n\t\teol.All = nil\n\tcase len(eol.Any) == 1 && len(eol.All) == 0:\n\t\teol.Expression = eol.Any[0]\n\t\teol.Any = nil\n\t}\n\n\tif eol.Expression != \"\" {\n\t\treturn eol.Expression, nil\n\t}\n\n\ttype RawExpressionOrList ExpressionOrList\n\treturn RawExpressionOrList(*eol), nil\n}\n\nfunc (eol *ExpressionOrList) MarshalJSON() ([]byte, error) {\n\tswitch {\n\tcase len(eol.All) == 1 && len(eol.Any) == 0:\n\t\teol.Expression = eol.All[0]\n\t\teol.All = nil\n\tcase len(eol.Any) == 1 && len(eol.All) == 0:\n\t\teol.Expression = eol.Any[0]\n\t\teol.Any = nil\n\t}\n\n\tif eol.Expression != \"\" {\n\t\treturn json.Marshal(string(eol.Expression))\n\t}\n\n\ttype RawExpressionOrList ExpressionOrList\n\tval := RawExpressionOrList(*eol)\n\treturn json.Marshal(val)\n}\n\nfunc (eol *ExpressionOrList) UnmarshalJSON(data []byte) error {\n\tswitch string(data[0]) {\n\tcase `\"`: // string\n\t\treturn json.Unmarshal(data, &eol.Expression)\n\tcase \"{\": // object\n\t\ttype RawExpressionOrList ExpressionOrList\n\t\tvar val RawExpressionOrList\n\t\tif err := json.Unmarshal(data, &val); err != nil {\n\t\t\treturn err\n\t\t}\n\t\teol.All = val.All\n\t\teol.Any = val.Any\n\n\t\treturn nil\n\t}\n\n\treturn ErrExpressionOrListMustBeStringOrObject\n}\n\nfunc (eol *ExpressionOrList) Valid() error {\n\tif eol.Expression == \"\" && len(eol.All) == 0 && len(eol.Any) == 0 {\n\t\treturn ErrExpressionEmpty\n\t}\n\tif len(eol.All) != 0 && len(eol.Any) != 0 {\n\t\treturn ErrExpressionCantHaveBoth\n\t}\n\n\treturn nil\n}\n"], ["/anubis/internal/ogtags/cache.go", "package ogtags\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"log/slog\"\n\t\"net/url\"\n\t\"syscall\"\n)\n\n// GetOGTags is the main function that retrieves Open Graph tags for a URL\nfunc (c *OGTagCache) GetOGTags(ctx context.Context, url *url.URL, originalHost string) (map[string]string, error) {\n\tif url == nil {\n\t\treturn nil, errors.New(\"nil URL provided, cannot fetch OG tags\")\n\t}\n\n\tif len(c.ogOverride) != 0 {\n\t\treturn c.ogOverride, nil\n\t}\n\n\ttarget := c.getTarget(url)\n\tcacheKey := c.generateCacheKey(target, originalHost)\n\n\t// Check cache first\n\tif cachedTags := c.checkCache(ctx, cacheKey); cachedTags != nil {\n\t\treturn cachedTags, nil\n\t}\n\n\t// Fetch HTML content, passing the original host\n\tdoc, err := c.fetchHTMLDocumentWithCache(ctx, target, originalHost, cacheKey)\n\tif errors.Is(err, syscall.ECONNREFUSED) {\n\t\tslog.Debug(\"Connection refused, returning empty tags\")\n\t\treturn nil, nil\n\t} else if errors.Is(err, ErrOgHandled) {\n\t\t// Error was handled in fetchHTMLDocument, return empty tags\n\t\treturn nil, nil\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Extract OG tags\n\togTags := c.extractOGTags(doc)\n\n\t// Store in cache\n\tc.cache.Set(ctx, cacheKey, ogTags, c.ogTimeToLive)\n\n\treturn ogTags, nil\n}\n\nfunc (c *OGTagCache) generateCacheKey(target string, originalHost string) string {\n\tvar cacheKey string\n\n\tif c.ogCacheConsiderHost {\n\t\tcacheKey = target + \"|\" + originalHost\n\t} else {\n\t\tcacheKey = target\n\t}\n\treturn cacheKey\n}\n\n// checkCache checks if we have the tags cached and returns them if so\nfunc (c *OGTagCache) checkCache(ctx context.Context, cacheKey string) map[string]string {\n\tif cachedTags, err := c.cache.Get(ctx, cacheKey); err == nil {\n\t\tslog.Debug(\"cache hit\", \"tags\", cachedTags)\n\t\treturn cachedTags\n\t}\n\tslog.Debug(\"cache miss\", \"url\", cacheKey)\n\treturn nil\n}\n"], ["/anubis/utils/cmd/backoff-retry/main.go", "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"os\"\n\t\"os/exec\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar (\n\tstartWait = flag.Duration(\"start-wait\", 250*time.Millisecond, \"amount of time to start with exponential backoff\")\n\ttryCount = flag.Int(\"try-count\", 5, \"number of retries\")\n)\n\nfunc main() {\n\tflag.Parse()\n\n\tcmdStr := strings.Join(flag.Args(), \" \")\n\twait := *startWait\n\n\tfor i := range make([]struct{}, *tryCount) {\n\t\tslog.Info(\"executing\", \"try\", i+1, \"wait\", wait, \"cmd\", cmdStr)\n\n\t\tcmd := exec.Command(\"sh\", \"-c\", cmdStr)\n\t\tcmd.Stdin = nil\n\t\tcmd.Stdout = os.Stdout\n\t\tcmd.Stderr = os.Stderr\n\n\t\tif err := cmd.Run(); err != nil {\n\t\t\ttime.Sleep(wait)\n\t\t\twait = wait * 2\n\t\t} else {\n\t\t\tos.Exit(0)\n\t\t}\n\t}\n\n\tfmt.Printf(\"giving up after %d tries\\n\", *tryCount)\n\tos.Exit(1)\n}\n"], ["/anubis/internal/ogtags/parse.go", "package ogtags\n\nimport (\n\t\"strings\"\n\n\t\"golang.org/x/net/html\"\n)\n\n// extractOGTags traverses the HTML document and extracts approved Open Graph tags\nfunc (c *OGTagCache) extractOGTags(doc *html.Node) map[string]string {\n\togTags := make(map[string]string)\n\n\tvar traverseNodes func(*html.Node)\n\ttraverseNodes = func(n *html.Node) {\n\t\tif isOGMetaTag(n) {\n\t\t\tproperty, content := c.extractMetaTagInfo(n)\n\t\t\tif property != \"\" {\n\t\t\t\togTags[property] = content\n\t\t\t}\n\t\t}\n\t\tfor child := n.FirstChild; child != nil; child = child.NextSibling {\n\t\t\ttraverseNodes(child)\n\t\t}\n\t}\n\n\ttraverseNodes(doc)\n\treturn ogTags\n}\n\n// isOGMetaTag checks if a node is *any* meta tag\nfunc isOGMetaTag(n *html.Node) bool {\n\tif n == nil {\n\t\treturn false\n\t}\n\treturn n.Type == html.ElementNode && n.Data == \"meta\"\n}\n\n// extractMetaTagInfo extracts property and content from a meta tag\nfunc (c *OGTagCache) extractMetaTagInfo(n *html.Node) (property, content string) {\n\tvar propertyKey string\n\n\t// Single pass through attributes, using range to avoid bounds checking\n\tfor _, attr := range n.Attr {\n\t\tswitch attr.Key {\n\t\tcase \"property\", \"name\":\n\t\t\tpropertyKey = attr.Val\n\t\tcase \"content\":\n\t\t\tcontent = attr.Val\n\t\t}\n\t\t// Early exit if we have both\n\t\tif propertyKey != \"\" && content != \"\" {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif propertyKey == \"\" {\n\t\treturn \"\", content\n\t}\n\n\t// Check prefixes first (more common case)\n\tfor _, prefix := range c.approvedPrefixes {\n\t\tif strings.HasPrefix(propertyKey, prefix) {\n\t\t\treturn propertyKey, content\n\t\t}\n\t}\n\n\t// Check exact matches\n\tfor _, tag := range c.approvedTags {\n\t\tif propertyKey == tag {\n\t\t\treturn propertyKey, content\n\t\t}\n\t}\n\n\treturn \"\", content\n}\n"], ["/anubis/lib/policy/checker/checker.go", "// Package checker defines the Checker interface and a helper utility to avoid import cycles.\npackage checker\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"strings\"\n\n\t\"github.com/TecharoHQ/anubis/internal\"\n)\n\ntype Impl interface {\n\tCheck(*http.Request) (bool, error)\n\tHash() string\n}\n\ntype List []Impl\n\nfunc (l List) Check(r *http.Request) (bool, error) {\n\tfor _, c := range l {\n\t\tok, err := c.Check(r)\n\t\tif err != nil {\n\t\t\treturn ok, err\n\t\t}\n\t\tif ok {\n\t\t\treturn ok, nil\n\t\t}\n\t}\n\n\treturn false, nil\n}\n\nfunc (l List) Hash() string {\n\tvar sb strings.Builder\n\n\tfor _, c := range l {\n\t\tfmt.Fprintln(&sb, c.Hash())\n\t}\n\n\treturn internal.FastHash(sb.String())\n}\n"], ["/anubis/lib/policy/config/geoip.go", "package config\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"regexp\"\n\t\"strings\"\n)\n\nvar (\n\tcountryCodeRegexp = regexp.MustCompile(`^[a-zA-Z]{2}$`)\n\n\tErrNotCountryCode = errors.New(\"config.Bot: invalid country code\")\n)\n\ntype GeoIP struct {\n\tCountries []string `json:\"countries\"`\n}\n\nfunc (g *GeoIP) Valid() error {\n\tvar errs []error\n\n\tfor i, cc := range g.Countries {\n\t\tif !countryCodeRegexp.MatchString(cc) {\n\t\t\terrs = append(errs, fmt.Errorf(\"%w: %s\", ErrNotCountryCode, cc))\n\t\t}\n\n\t\tg.Countries[i] = strings.ToLower(cc)\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"bot.GeoIP: invalid GeoIP settings: %w\", errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n"], ["/anubis/lib/policy/expressions/loadavg.go", "package expressions\n\nimport (\n\t\"context\"\n\t\"log/slog\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/shirou/gopsutil/v4/load\"\n)\n\ntype loadAvg struct {\n\tlock sync.RWMutex\n\tdata *load.AvgStat\n}\n\nfunc (l *loadAvg) updateThread(ctx context.Context) {\n\tticker := time.NewTicker(15 * time.Second)\n\tdefer ticker.Stop()\n\n\tl.update()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tl.update()\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (l *loadAvg) update() {\n\tl.lock.Lock()\n\tdefer l.lock.Unlock()\n\n\tvar err error\n\tl.data, err = load.Avg()\n\tif err != nil {\n\t\tslog.Debug(\"can't get load average\", \"err\", err)\n\t}\n}\n\nvar (\n\tglobalLoadAvg *loadAvg\n)\n\nfunc init() {\n\tglobalLoadAvg = &loadAvg{}\n\tgo globalLoadAvg.updateThread(context.Background())\n}\n\nfunc Load1() float64 {\n\tglobalLoadAvg.lock.RLock()\n\tdefer globalLoadAvg.lock.RUnlock()\n\treturn globalLoadAvg.data.Load1\n}\n\nfunc Load5() float64 {\n\tglobalLoadAvg.lock.RLock()\n\tdefer globalLoadAvg.lock.RUnlock()\n\treturn globalLoadAvg.data.Load5\n}\n\nfunc Load15() float64 {\n\tglobalLoadAvg.lock.RLock()\n\tdefer globalLoadAvg.lock.RUnlock()\n\treturn globalLoadAvg.data.Load15\n}\n"], ["/anubis/lib/policy/checkresult.go", "package policy\n\nimport (\n\t\"log/slog\"\n\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n)\n\ntype CheckResult struct {\n\tName string\n\tRule config.Rule\n\tWeight int\n}\n\nfunc (cr CheckResult) LogValue() slog.Value {\n\treturn slog.GroupValue(\n\t\tslog.String(\"name\", cr.Name),\n\t\tslog.String(\"rule\", string(cr.Rule)),\n\t\tslog.Int(\"weight\", cr.Weight),\n\t)\n}\n"], ["/anubis/internal/dnsbl/droneblresponse_string.go", "// Code generated by \"stringer -type=DroneBLResponse\"; DO NOT EDIT.\n\npackage dnsbl\n\nimport \"strconv\"\n\nfunc _() {\n\t// An \"invalid array index\" compiler error signifies that the constant values have changed.\n\t// Re-run the stringer command to generate them again.\n\tvar x [1]struct{}\n\t_ = x[AllGood-0]\n\t_ = x[IRCDrone-3]\n\t_ = x[Bottler-5]\n\t_ = x[UnknownSpambotOrDrone-6]\n\t_ = x[DDOSDrone-7]\n\t_ = x[SOCKSProxy-8]\n\t_ = x[HTTPProxy-9]\n\t_ = x[ProxyChain-10]\n\t_ = x[OpenProxy-11]\n\t_ = x[OpenDNSResolver-12]\n\t_ = x[BruteForceAttackers-13]\n\t_ = x[OpenWingateProxy-14]\n\t_ = x[CompromisedRouter-15]\n\t_ = x[AutoRootingWorms-16]\n\t_ = x[AutoDetectedBotIP-17]\n\t_ = x[Unknown-255]\n}\n\nconst (\n\t_DroneBLResponse_name_0 = \"AllGood\"\n\t_DroneBLResponse_name_1 = \"IRCDrone\"\n\t_DroneBLResponse_name_2 = \"BottlerUnknownSpambotOrDroneDDOSDroneSOCKSProxyHTTPProxyProxyChainOpenProxyOpenDNSResolverBruteForceAttackersOpenWingateProxyCompromisedRouterAutoRootingWormsAutoDetectedBotIP\"\n\t_DroneBLResponse_name_3 = \"Unknown\"\n)\n\nvar (\n\t_DroneBLResponse_index_2 = [...]uint8{0, 7, 28, 37, 47, 56, 66, 75, 90, 109, 125, 142, 158, 175}\n)\n\nfunc (i DroneBLResponse) String() string {\n\tswitch {\n\tcase i == 0:\n\t\treturn _DroneBLResponse_name_0\n\tcase i == 3:\n\t\treturn _DroneBLResponse_name_1\n\tcase 5 <= i && i <= 17:\n\t\ti -= 5\n\t\treturn _DroneBLResponse_name_2[_DroneBLResponse_index_2[i]:_DroneBLResponse_index_2[i+1]]\n\tcase i == 255:\n\t\treturn _DroneBLResponse_name_3\n\tdefault:\n\t\treturn \"DroneBLResponse(\" + strconv.FormatInt(int64(i), 10) + \")\"\n\t}\n}\n"], ["/anubis/internal/ja4h.go", "package internal\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/lum8rjack/go-ja4h\"\n)\n\nfunc JA4H(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tr.Header.Add(\"X-Http-Fingerprint-JA4H\", ja4h.JA4H(r))\n\t\tnext.ServeHTTP(w, r)\n\t})\n}\n"], ["/anubis/lib/thoth/auth.go", "package thoth\n\nimport (\n\t\"context\"\n\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/metadata\"\n)\n\nfunc authUnaryClientInterceptor(token string) grpc.UnaryClientInterceptor {\n\treturn func(\n\t\tctx context.Context,\n\t\tmethod string,\n\t\treq interface{},\n\t\treply interface{},\n\t\tcc *grpc.ClientConn,\n\t\tinvoker grpc.UnaryInvoker,\n\t\topts ...grpc.CallOption,\n\t) error {\n\t\tmd := metadata.Pairs(\"authorization\", \"Bearer \"+token)\n\t\tctx = metadata.NewOutgoingContext(ctx, md)\n\t\treturn invoker(ctx, method, req, reply, cc, opts...)\n\t}\n}\n\nfunc authStreamClientInterceptor(token string) grpc.StreamClientInterceptor {\n\treturn func(\n\t\tctx context.Context,\n\t\tdesc *grpc.StreamDesc,\n\t\tcc *grpc.ClientConn,\n\t\tmethod string,\n\t\tstreamer grpc.Streamer,\n\t\topts ...grpc.CallOption,\n\t) (grpc.ClientStream, error) {\n\t\tmd := metadata.Pairs(\"authorization\", \"Bearer \"+token)\n\t\tctx = metadata.NewOutgoingContext(ctx, md)\n\t\treturn streamer(ctx, desc, cc, method, opts...)\n\t}\n}\n"], ["/anubis/lib/challenge/error.go", "package challenge\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net/http\"\n)\n\nvar (\n\tErrFailed = errors.New(\"challenge: user failed challenge\")\n\tErrMissingField = errors.New(\"challenge: missing field\")\n\tErrInvalidFormat = errors.New(\"challenge: field has invalid format\")\n)\n\nfunc NewError(verb, publicReason string, privateReason error) *Error {\n\treturn &Error{\n\t\tVerb: verb,\n\t\tPublicReason: publicReason,\n\t\tPrivateReason: privateReason,\n\t\tStatusCode: http.StatusForbidden,\n\t}\n}\n\ntype Error struct {\n\tPrivateReason error\n\tVerb string\n\tPublicReason string\n\tStatusCode int\n}\n\nfunc (e *Error) Error() string {\n\treturn fmt.Sprintf(\"challenge: error when processing challenge: %s: %v\", e.Verb, e.PrivateReason)\n}\n\nfunc (e *Error) Unwrap() error {\n\treturn e.PrivateReason\n}\n"], ["/anubis/lib/policy/expressions/url_values.go", "package expressions\n\nimport (\n\t\"errors\"\n\t\"net/url\"\n\t\"reflect\"\n\t\"strings\"\n\n\t\"github.com/google/cel-go/common/types\"\n\t\"github.com/google/cel-go/common/types/ref\"\n\t\"github.com/google/cel-go/common/types/traits\"\n)\n\nvar ErrNotImplemented = errors.New(\"expressions: not implemented\")\n\n// URLValues is a type wrapper to expose url.Values into CEL programs.\ntype URLValues struct {\n\turl.Values\n}\n\nfunc (u URLValues) ConvertToNative(typeDesc reflect.Type) (any, error) {\n\treturn nil, ErrNotImplemented\n}\n\nfunc (u URLValues) ConvertToType(typeVal ref.Type) ref.Val {\n\tswitch typeVal {\n\tcase types.MapType:\n\t\treturn u\n\tcase types.TypeType:\n\t\treturn types.MapType\n\t}\n\n\treturn types.NewErr(\"can't convert from %q to %q\", types.MapType, typeVal)\n}\n\nfunc (u URLValues) Equal(other ref.Val) ref.Val {\n\treturn types.Bool(false) // We don't want to compare header maps\n}\n\nfunc (u URLValues) Type() ref.Type {\n\treturn types.MapType\n}\n\nfunc (u URLValues) Value() any { return u }\n\nfunc (u URLValues) Find(key ref.Val) (ref.Val, bool) {\n\tk, ok := key.(types.String)\n\tif !ok {\n\t\treturn nil, false\n\t}\n\n\tif _, ok := u.Values[string(k)]; !ok {\n\t\treturn nil, false\n\t}\n\n\treturn types.String(strings.Join(u.Values[string(k)], \",\")), true\n}\n\nfunc (u URLValues) Contains(key ref.Val) ref.Val {\n\t_, ok := u.Find(key)\n\treturn types.Bool(ok)\n}\n\nfunc (u URLValues) Get(key ref.Val) ref.Val {\n\tresult, ok := u.Find(key)\n\tif !ok {\n\t\treturn types.ValOrErr(result, \"no such key: %v\", key)\n\t}\n\treturn result\n}\n\nfunc (u URLValues) Iterator() traits.Iterator { panic(\"TODO(Xe): implement me\") }\n\nfunc (u URLValues) IsZeroValue() bool {\n\treturn len(u.Values) == 0\n}\n\nfunc (u URLValues) Size() ref.Val { return types.Int(len(u.Values)) }\n"], ["/anubis/lib/policy/expressions/http_headers.go", "package expressions\n\nimport (\n\t\"net/http\"\n\t\"reflect\"\n\t\"strings\"\n\n\t\"github.com/google/cel-go/common/types\"\n\t\"github.com/google/cel-go/common/types/ref\"\n\t\"github.com/google/cel-go/common/types/traits\"\n)\n\n// HTTPHeaders is a type wrapper to expose HTTP headers into CEL programs.\ntype HTTPHeaders struct {\n\thttp.Header\n}\n\nfunc (h HTTPHeaders) ConvertToNative(typeDesc reflect.Type) (any, error) {\n\treturn nil, ErrNotImplemented\n}\n\nfunc (h HTTPHeaders) ConvertToType(typeVal ref.Type) ref.Val {\n\tswitch typeVal {\n\tcase types.MapType:\n\t\treturn h\n\tcase types.TypeType:\n\t\treturn types.MapType\n\t}\n\n\treturn types.NewErr(\"can't convert from %q to %q\", types.MapType, typeVal)\n}\n\nfunc (h HTTPHeaders) Equal(other ref.Val) ref.Val {\n\treturn types.Bool(false) // We don't want to compare header maps\n}\n\nfunc (h HTTPHeaders) Type() ref.Type {\n\treturn types.MapType\n}\n\nfunc (h HTTPHeaders) Value() any { return h }\n\nfunc (h HTTPHeaders) Find(key ref.Val) (ref.Val, bool) {\n\tk, ok := key.(types.String)\n\tif !ok {\n\t\treturn nil, false\n\t}\n\n\tif _, ok := h.Header[string(k)]; !ok {\n\t\treturn nil, false\n\t}\n\n\treturn types.String(strings.Join(h.Header.Values(string(k)), \",\")), true\n}\n\nfunc (h HTTPHeaders) Contains(key ref.Val) ref.Val {\n\t_, ok := h.Find(key)\n\treturn types.Bool(ok)\n}\n\nfunc (h HTTPHeaders) Get(key ref.Val) ref.Val {\n\tresult, ok := h.Find(key)\n\tif !ok {\n\t\treturn types.ValOrErr(result, \"no such key: %v\", key)\n\t}\n\treturn result\n}\n\nfunc (h HTTPHeaders) Iterator() traits.Iterator { panic(\"TODO(Xe): implement me\") }\n\nfunc (h HTTPHeaders) IsZeroValue() bool {\n\treturn len(h.Header) == 0\n}\n\nfunc (h HTTPHeaders) Size() ref.Val { return types.Int(len(h.Header)) }\n"], ["/anubis/decaymap/decaymap.go", "package decaymap\n\nimport (\n\t\"sync\"\n\t\"time\"\n)\n\nfunc Zilch[T any]() T {\n\tvar zero T\n\treturn zero\n}\n\n// Impl is a lazy key->value map. It's a wrapper around a map and a mutex. If values exceed their time-to-live, they are pruned at Get time.\ntype Impl[K comparable, V any] struct {\n\tdata map[K]decayMapEntry[V]\n\tlock sync.RWMutex\n}\n\ntype decayMapEntry[V any] struct {\n\tValue V\n\texpiry time.Time\n}\n\n// New creates a new DecayMap of key type K and value type V.\n//\n// Key types must be comparable to work with maps.\nfunc New[K comparable, V any]() *Impl[K, V] {\n\treturn &Impl[K, V]{\n\t\tdata: make(map[K]decayMapEntry[V]),\n\t}\n}\n\n// expire forcibly expires a key by setting its time-to-live one second in the past.\nfunc (m *Impl[K, V]) expire(key K) bool {\n\tm.lock.RLock()\n\tval, ok := m.data[key]\n\tm.lock.RUnlock()\n\n\tif !ok {\n\t\treturn false\n\t}\n\n\tm.lock.Lock()\n\tval.expiry = time.Now().Add(-1 * time.Second)\n\tm.data[key] = val\n\tm.lock.Unlock()\n\n\treturn true\n}\n\n// Delete a value from the DecayMap by key.\n//\n// If the value does not exist, return false. Return true after\n// deletion.\nfunc (m *Impl[K, V]) Delete(key K) bool {\n\tm.lock.RLock()\n\t_, ok := m.data[key]\n\tm.lock.RUnlock()\n\n\tif !ok {\n\t\treturn false\n\t}\n\n\tm.lock.Lock()\n\tdelete(m.data, key)\n\tm.lock.Unlock()\n\n\treturn true\n}\n\n// Get gets a value from the DecayMap by key.\n//\n// If a value has expired, forcibly delete it if it was not updated.\nfunc (m *Impl[K, V]) Get(key K) (V, bool) {\n\tm.lock.RLock()\n\tvalue, ok := m.data[key]\n\tm.lock.RUnlock()\n\n\tif !ok {\n\t\treturn Zilch[V](), false\n\t}\n\n\tif time.Now().After(value.expiry) {\n\t\tm.lock.Lock()\n\t\t// Since previously reading m.data[key], the value may have been updated.\n\t\t// Delete the entry only if the expiry time is still the same.\n\t\tif m.data[key].expiry.Equal(value.expiry) {\n\t\t\tdelete(m.data, key)\n\t\t}\n\t\tm.lock.Unlock()\n\n\t\treturn Zilch[V](), false\n\t}\n\n\treturn value.Value, true\n}\n\n// Set sets a key value pair in the map.\nfunc (m *Impl[K, V]) Set(key K, value V, ttl time.Duration) {\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\n\tm.data[key] = decayMapEntry[V]{\n\t\tValue: value,\n\t\texpiry: time.Now().Add(ttl),\n\t}\n}\n\n// Cleanup removes all expired entries from the DecayMap.\nfunc (m *Impl[K, V]) Cleanup() {\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\n\tnow := time.Now()\n\tfor key, entry := range m.data {\n\t\tif now.After(entry.expiry) {\n\t\t\tdelete(m.data, key)\n\t\t}\n\t}\n}\n\n// Len returns the number of entries in the DecayMap.\nfunc (m *Impl[K, V]) Len() int {\n\tm.lock.RLock()\n\tdefer m.lock.RUnlock()\n\treturn len(m.data)\n}\n"], ["/anubis/internal/hash.go", "package internal\n\nimport (\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"strconv\"\n\n\t\"github.com/cespare/xxhash/v2\"\n)\n\n// SHA256sum computes a cryptographic hash. Still used for proof-of-work challenges\n// where we need the security properties of a cryptographic hash function.\nfunc SHA256sum(text string) string {\n\thash := sha256.New()\n\thash.Write([]byte(text))\n\treturn hex.EncodeToString(hash.Sum(nil))\n}\n\n// FastHash is a high-performance non-cryptographic hash function suitable for\n// internal caching, policy rule identification, and other performance-critical\n// use cases where cryptographic security is not required.\nfunc FastHash(text string) string {\n\th := xxhash.Sum64String(text)\n\treturn strconv.FormatUint(h, 16)\n}\n"], ["/anubis/lib/challenge/metrics.go", "package challenge\n\nimport (\n\t\"math\"\n\n\t\"github.com/prometheus/client_golang/prometheus\"\n\t\"github.com/prometheus/client_golang/prometheus/promauto\"\n)\n\nvar TimeTaken = promauto.NewHistogramVec(prometheus.HistogramOpts{\n\tName: \"anubis_time_taken\",\n\tHelp: \"The time taken for a browser to generate a response (milliseconds)\",\n\tBuckets: prometheus.ExponentialBucketsRange(1, math.Pow(2, 20), 20),\n}, []string{\"method\"})\n"], ["/anubis/lib/store/all/all.go", "// Package all is a meta-package that imports all store implementations.\n//\n// This is a HACK to make tests work consistently.\npackage all\n\nimport (\n\t_ \"github.com/TecharoHQ/anubis/lib/store/bbolt\"\n\t_ \"github.com/TecharoHQ/anubis/lib/store/memory\"\n\t_ \"github.com/TecharoHQ/anubis/lib/store/valkey\"\n)\n"], ["/anubis/internal/health.go", "package internal\n\nimport (\n\t\"context\"\n\n\t\"google.golang.org/grpc/health\"\n\thealthv1 \"google.golang.org/grpc/health/grpc_health_v1\"\n)\n\nvar HealthSrv = health.NewServer()\n\nfunc SetHealth(svc string, status healthv1.HealthCheckResponse_ServingStatus) {\n\tHealthSrv.SetServingStatus(svc, status)\n}\n\nfunc GetHealth(svc string) (healthv1.HealthCheckResponse_ServingStatus, bool) {\n\tst, err := HealthSrv.Check(context.Background(), &healthv1.HealthCheckRequest{\n\t\tService: svc,\n\t})\n\tif err != nil {\n\t\treturn healthv1.HealthCheckResponse_UNKNOWN, false\n\t}\n\n\treturn st.GetStatus(), true\n}\n"], ["/anubis/lib/thoth/thothmock/withthothmock.go", "package thothmock\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/TecharoHQ/anubis/lib/thoth\"\n)\n\nfunc WithMockThoth(t *testing.T) context.Context {\n\tt.Helper()\n\n\tthothCli := &thoth.Client{}\n\tthothCli.WithIPToASNService(MockIpToASNService())\n\tctx := thoth.With(t.Context(), thothCli)\n\treturn ctx\n}\n"], ["/anubis/lib/store/registry.go", "package store\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"sort\"\n\t\"sync\"\n)\n\nvar (\n\tregistry map[string]Factory = map[string]Factory{}\n\tregLock sync.RWMutex\n)\n\ntype Factory interface {\n\tBuild(ctx context.Context, config json.RawMessage) (Interface, error)\n\tValid(config json.RawMessage) error\n}\n\nfunc Register(name string, impl Factory) {\n\tregLock.Lock()\n\tdefer regLock.Unlock()\n\n\tregistry[name] = impl\n}\n\nfunc Get(name string) (Factory, bool) {\n\tregLock.RLock()\n\tdefer regLock.RUnlock()\n\tresult, ok := registry[name]\n\treturn result, ok\n}\n\nfunc Methods() []string {\n\tregLock.RLock()\n\tdefer regLock.RUnlock()\n\tvar result []string\n\tfor method := range registry {\n\t\tresult = append(result, method)\n\t}\n\tsort.Strings(result)\n\treturn result\n}\n"], ["/anubis/internal/unbreakdocker.go", "package internal\n\nimport (\n\t\"os\"\n\t\"os/exec\"\n)\n\nfunc UnbreakDocker() {\n\t// XXX(Xe): This is bad code. Do not do this.\n\t//\n\t// I have to do this because I'm running from inside the context of a dev\n\t// container. This dev container runs in a different docker network than\n\t// the valkey test container runs in. In order to let my dev container\n\t// connect to the test container, they need to share a network in common.\n\t// The easiest network to use for this is the default \"bridge\" network.\n\t//\n\t// This is a horrifying monstrosity, but the part that scares me the most\n\t// is the fact that it works.\n\tif hostname, err := os.Hostname(); err == nil {\n\t\texec.Command(\"docker\", \"network\", \"connect\", \"bridge\", hostname).Run()\n\t}\n}\n"], ["/anubis/data/embed.go", "package data\n\nimport \"embed\"\n\nvar (\n\t//go:embed botPolicies.yaml botPolicies.json all:apps all:bots all:clients all:common all:crawlers all:meta\n\tBotPolicies embed.FS\n)\n"], ["/anubis/web/embed.go", "package web\n\nimport \"embed\"\n\n//go:generate go tool github.com/a-h/templ/cmd/templ generate\n\nvar (\n\t//go:embed static\n\tStatic embed.FS\n)\n"], ["/anubis/lib/thoth/context.go", "package thoth\n\nimport \"context\"\n\ntype ctxKey struct{}\n\nfunc With(ctx context.Context, cli *Client) context.Context {\n\treturn context.WithValue(ctx, ctxKey{}, cli)\n}\n\nfunc FromContext(ctx context.Context) (*Client, bool) {\n\tcli, ok := ctx.Value(ctxKey{}).(*Client)\n\treturn cli, ok\n}\n"], ["/anubis/lib/challenge/challenge.go", "package challenge\n\nimport \"time\"\n\n// Challenge is the metadata about a single challenge issuance.\ntype Challenge struct {\n\tID string `json:\"id\"` // UUID identifying the challenge\n\tRandomData string `json:\"randomData\"` // The random data the client processes\n\tIssuedAt time.Time `json:\"issuedAt\"` // When the challenge was issued\n\tMetadata map[string]string `json:\"metadata\"` // Challenge metadata such as IP address and user agent\n}\n"], ["/anubis/internal/mimetype.go", "package internal\n\nimport \"mime\"\n\nfunc init() {\n\tmime.AddExtensionType(\".mjs\", \"text/javascript\")\n}\n"], ["/anubis/lib/policy/config/weight.go", "package config\n\ntype Weight struct {\n\tAdjust int `json:\"adjust\" yaml:\"adjust\"`\n}\n"]], "task_instance_info": {"created_time": "2025-08-20 20:50:29", "created_task_model": "DeepSeek-R1", "function_skeleton": "func LoadPoliciesOrDefault (ctx context.Context, fname string, defaultDifficulty int) (*policy.ParsedConfig, error) {}", "code_description": "This code segment functions to: Load configuration settings from either a specified file or default resources, parse and validate security challenge parameters against available implementations, and handle errors related to file access or policy integrity checks."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```go\n[TASK_BEGIN]\nfunc LoadPoliciesOrDefault(ctx context.Context, fname string, defaultDifficulty int) (*policy.ParsedConfig, error) {\n\tif _, err := os.Stat(fname); err != nil {\n\t\tif errors.Is(err, os.ErrNotExist) {\n\t\t\tslog.DebugContext(ctx, \"policy file not found, using default configuration\", \"file\", fname)\n\t\t\treturn &policy.ParsedConfig{\n\t\t\t\tChallengePolicy: policy.ChallengePolicy{\n\t\t\t\t\tDifficulty: defaultDifficulty,\n\t\t\t\t},\n\t\t\t\tStore: data.NewMemoryStore(),\n\t\t\t\tOpenGraph: config.OpenGraph{},\n\t\t\t}, nil\n\t\t}\n\t\treturn nil, fmt.Errorf(\"lib: checking policy file: %w\", err)\n\t}\n\n\tcfg, err := policy.ParsePolicy(ctx, fname)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"lib: parsing policy: %w\", err)\n\t}\n\t\n\tif cfg.ChallengePolicy.Difficulty == 0 {\n\t\tcfg.ChallengePolicy.Difficulty = defaultDifficulty\n\t}\n\treturn cfg, nil\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 20-51-17"}, "editdistance_info": {"edit_distance": 24.6612, "calculate_time": "2025-08-20 20:51:17", "true_code_clean": "func LoadPoliciesOrDefault(ctx context.Context, fname string, defaultDifficulty int) (*policy.ParsedConfig, error) {\n\tvar fin io.ReadCloser\n\tvar err error\n\tif fname != \"\" {\n\t\tfin, err = os.Open(fname)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"can't parse policy file %s: %w\", fname, err)\n\t\t}\n\t} else {\n\t\tfname = \"(data)/botPolicies.yaml\"\n\t\tfin, err = data.BotPolicies.Open(\"botPolicies.yaml\")\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"[unexpected] can't parse builtin policy file %s: %w\", fname, err)\n\t\t}\n\t}\n\tdefer func(fin io.ReadCloser) {\n\t\terr := fin.Close()\n\t\tif err != nil {\n\t\t\tslog.Error(\"failed to close policy file\", \"file\", fname, \"err\", err)\n\t\t}\n\t}(fin)\n\tanubisPolicy, err := policy.ParseConfig(ctx, fin, fname, defaultDifficulty)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't parse policy file %s: %w\", fname, err)\n\t}\n\tvar validationErrs []error\n\tfor _, b := range anubisPolicy.Bots {\n\t\tif _, ok := challenge.Get(b.Challenge.Algorithm); !ok {\n\t\t\tvalidationErrs = append(validationErrs, fmt.Errorf(\"%w %s\", policy.ErrChallengeRuleHasWrongAlgorithm, b.Challenge.Algorithm))\n\t\t}\n\t}\n\tif len(validationErrs) != 0 {\n\t\treturn nil, fmt.Errorf(\"can't do final validation of Anubis config: %w\", errors.Join(validationErrs...))\n\t}\n\treturn anubisPolicy, err\n}", "predict_code_clean": "func LoadPoliciesOrDefault(ctx context.Context, fname string, defaultDifficulty int) (*policy.ParsedConfig, error) {\n\tif _, err := os.Stat(fname); err != nil {\n\t\tif errors.Is(err, os.ErrNotExist) {\n\t\t\tslog.DebugContext(ctx, \"policy file not found, using default configuration\", \"file\", fname)\n\t\t\treturn &policy.ParsedConfig{\n\t\t\t\tChallengePolicy: policy.ChallengePolicy{\n\t\t\t\t\tDifficulty: defaultDifficulty,\n\t\t\t\t},\n\t\t\t\tStore: data.NewMemoryStore(),\n\t\t\t\tOpenGraph: config.OpenGraph{},\n\t\t\t}, nil\n\t\t}\n\t\treturn nil, fmt.Errorf(\"lib: checking policy file: %w\", err)\n\t}\n\tcfg, err := policy.ParsePolicy(ctx, fname)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"lib: parsing policy: %w\", err)\n\t}\n\tif cfg.ChallengePolicy.Difficulty == 0 {\n\t\tcfg.ChallengePolicy.Difficulty = defaultDifficulty\n\t}\n\treturn cfg, nil\n}"}} {"repo_name": "anubis", "file_name": "/anubis/lib/anubis.go", "inference_info": {"prefix_code": "package lib\n\nimport (\n\t\"context\"\n\t\"crypto/ed25519\"\n\t\"crypto/rand\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"slices\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/golang-jwt/jwt/v5\"\n\t\"github.com/google/cel-go/common/types\"\n\t\"github.com/google/uuid\"\n\n\t\"github.com/prometheus/client_golang/prometheus\"\n\t\"github.com/prometheus/client_golang/prometheus/promauto\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/TecharoHQ/anubis/decaymap\"\n\t\"github.com/TecharoHQ/anubis/internal\"\n\t\"github.com/TecharoHQ/anubis/internal/dnsbl\"\n\t\"github.com/TecharoHQ/anubis/internal/ogtags\"\n\t\"github.com/TecharoHQ/anubis/lib/challenge\"\n\t\"github.com/TecharoHQ/anubis/lib/localization\"\n\t\"github.com/TecharoHQ/anubis/lib/policy\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/checker\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n\n\t// challenge implementations\n\t_ \"github.com/TecharoHQ/anubis/lib/challenge/metarefresh\"\n\t_ \"github.com/TecharoHQ/anubis/lib/challenge/proofofwork\"\n)\n\nvar (\n\tchallengesIssued = promauto.NewCounterVec(prometheus.CounterOpts{\n\t\tName: \"anubis_challenges_issued\",\n\t\tHelp: \"The total number of challenges issued\",\n\t}, []string{\"method\"})\n\n\tchallengesValidated = promauto.NewCounterVec(prometheus.CounterOpts{\n\t\tName: \"anubis_challenges_validated\",\n\t\tHelp: \"The total number of challenges validated\",\n\t}, []string{\"method\"})\n\n\tdroneBLHits = promauto.NewCounterVec(prometheus.CounterOpts{\n\t\tName: \"anubis_dronebl_hits\",\n\t\tHelp: \"The total number of hits from DroneBL\",\n\t}, []string{\"status\"})\n\n\tfailedValidations = promauto.NewCounterVec(prometheus.CounterOpts{\n\t\tName: \"anubis_failed_validations\",\n\t\tHelp: \"The total number of failed validations\",\n\t}, []string{\"method\"})\n\n\trequestsProxied = promauto.NewCounterVec(prometheus.CounterOpts{\n\t\tName: \"anubis_proxied_requests_total\",\n\t\tHelp: \"Number of requests proxied through Anubis to upstream targets\",\n\t}, []string{\"host\"})\n)\n\ntype Server struct {\n\tnext http.Handler\n\tmux *http.ServeMux\n\tpolicy *policy.ParsedConfig\n\tOGTags *ogtags.OGTagCache\n\ted25519Priv ed25519.PrivateKey\n\ths512Secret []byte\n\topts Options\n\tstore store.Interface\n}\n\nfunc (s *Server) getTokenKeyfunc() jwt.Keyfunc {\n\t// return ED25519 key if HS512 is not set\n\tif len(s.hs512Secret) == 0 {\n\t\treturn func(token *jwt.Token) (interface{}, error) {\n\t\t\treturn s.ed25519Priv.Public().(ed25519.PublicKey), nil\n\t\t}\n\t} else {\n\t\treturn func(token *jwt.Token) (interface{}, error) {\n\t\t\treturn s.hs512Secret, nil\n\t\t}\n\t}\n}\n\nfunc (s *Server) challengeFor(r *http.Request) (*challenge.Challenge, error) {\n\tckies := r.CookiesNamed(anubis.TestCookieName)\n\n\tif len(ckies) == 0 {\n\t\treturn s.issueChallenge(r.Context(), r)\n\t}\n\n\tj := store.JSON[challenge.Challenge]{Underlying: s.store}\n\n\tckie := ckies[0]\n\tchall, err := j.Get(r.Context(), \"challenge:\"+ckie.Value)\n\tif err != nil {\n\t\tif errors.Is(err, store.ErrNotFound) {\n\t\t\treturn s.issueChallenge(r.Context(), r)\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\treturn &chall, nil\n}\n\nfunc (s *Server) issueChallenge(ctx context.Context, r *http.Request) (*challenge.Challenge, error) {\n\tid, err := uuid.NewV7()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar randomData = make([]byte, 256)\n\tif _, err := rand.Read(randomData); err != nil {\n\t\treturn nil, err\n\t}\n\n\tchall := challenge.Challenge{\n\t\tID: id.String(),\n\t\tRandomData: fmt.Sprintf(\"%x\", randomData),\n\t\tIssuedAt: time.Now(),\n\t\tMetadata: map[string]string{\n\t\t\t\"User-Agent\": r.Header.Get(\"User-Agent\"),\n\t\t\t\"X-Real-Ip\": r.Header.Get(\"X-Real-Ip\"),\n\t\t},\n\t}\n\n\tj := store.JSON[challenge.Challenge]{Underlying: s.store}\n\tif err := j.Set(ctx, \"challenge:\"+id.String(), chall, 30*time.Minute); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &chall, err\n}\n\nfunc (s *Server) maybeReverseProxyHttpStatusOnly(w http.ResponseWriter, r *http.Request) {\n\ts.maybeReverseProxy(w, r, true)\n}\n\nfunc (s *Server) maybeReverseProxyOrPage(w http.ResponseWriter, r *http.Request) {\n\ts.maybeReverseProxy(w, r, false)\n}\n\nfunc (s *Server) maybeReverseProxy(w http.ResponseWriter, r *http.Request, httpStatusOnly bool) {\n\tlg := internal.GetRequestLogger(r)\n\n\t// Adjust cookie path if base prefix is not empty\n\tcookiePath := \"/\"\n\tif anubis.BasePrefix != \"\" {\n\t\tcookiePath = strings.TrimSuffix(anubis.BasePrefix, \"/\") + \"/\"\n\t}\n\n\tcr, rule, err := s.check(r)\n\tif err != nil {\n\t\tlg.Error(\"check failed\", \"err\", err)\n\t\tlocalizer := localization.GetLocalizer(r)\n\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s \\\"maybeReverseProxy\\\"\", localizer.T(\"internal_server_error\")))\n\t\treturn\n\t}\n\n\tr.Header.Add(\"X-Anubis-Rule\", cr.Name)\n\tr.Header.Add(\"X-Anubis-Action\", string(cr.Rule))\n\tlg = lg.With(\"check_result\", cr)\n\tpolicy.Applications.WithLabelValues(cr.Name, string(cr.Rule)).Add(1)\n\n\tip := r.Header.Get(\"X-Real-Ip\")\n\n\tif s.handleDNSBL(w, r, ip, lg) {\n\t\treturn\n\t}\n\n\tif s.checkRules(w, r, cr, lg, rule) {\n\t\treturn\n\t}\n\n\tckie, err := r.Cookie(anubis.CookieName)\n\tif err != nil {\n\t\tlg.Debug(\"cookie not found\", \"path\", r.URL.Path)\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.RenderIndex(w, r, rule, httpStatusOnly)\n\t\treturn\n\t}\n\n\tif err := ckie.Valid(); err != nil {\n\t\tlg.Debug(\"cookie is invalid\", \"err\", err)\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.RenderIndex(w, r, rule, httpStatusOnly)\n\t\treturn\n\t}\n\n\tif time.Now().After(ckie.Expires) && !ckie.Expires.IsZero() {\n\t\tlg.Debug(\"cookie expired\", \"path\", r.URL.Path)\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.RenderIndex(w, r, rule, httpStatusOnly)\n\t\treturn\n\t}\n\n\ttoken, err := jwt.ParseWithClaims(ckie.Value, jwt.MapClaims{}, s.getTokenKeyfunc(), jwt.WithExpirationRequired(), jwt.WithStrictDecoding())\n\n\tif err != nil || !token.Valid {\n\t\tlg.Debug(\"invalid token\", \"path\", r.URL.Path, \"err\", err)\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.RenderIndex(w, r, rule, httpStatusOnly)\n\t\treturn\n\t}\n\n\tclaims, ok := token.Claims.(jwt.MapClaims)\n\tif !ok {\n\t\tlg.Debug(\"invalid token claims type\", \"path\", r.URL.Path)\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.RenderIndex(w, r, rule, httpStatusOnly)\n\t\treturn\n\t}\n\n\tpolicyRule, ok := claims[\"policyRule\"].(string)\n\tif !ok {\n\t\tlg.Debug(\"policyRule claim is not a string\")\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.RenderIndex(w, r, rule, httpStatusOnly)\n\t\treturn\n\t}\n\n\tif policyRule != rule.Hash() {\n\t\tlg.Debug(\"user originally passed with a different rule, issuing new challenge\", \"old\", policyRule, \"new\", rule.Name)\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.RenderIndex(w, r, rule, httpStatusOnly)\n\t\treturn\n\t}\n\n\tr.Header.Add(\"X-Anubis-Status\", \"PASS\")\n\ts.ServeHTTPNext(w, r)\n}\n\nfunc (s *Server) checkRules(w http.ResponseWriter, r *http.Request, cr policy.CheckResult, lg *slog.Logger, rule *policy.Bot) bool {\n\t// Adjust cookie path if base prefix is not empty\n\tcookiePath := \"/\"\n\tif anubis.BasePrefix != \"\" {\n\t\tcookiePath = strings.TrimSuffix(anubis.BasePrefix, \"/\") + \"/\"\n\t}\n\n\tlocalizer := localization.GetLocalizer(r)\n\n\tswitch cr.Rule {\n\tcase config.RuleAllow:\n\t\tlg.Debug(\"allowing traffic to origin (explicit)\")\n\t\ts.ServeHTTPNext(w, r)\n\t\treturn true\n\tcase config.RuleDeny:\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\tlg.Info(\"explicit deny\")\n\t\tif rule == nil {\n\t\t\tlg.Error(\"rule is nil, cannot calculate checksum\")\n\t\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s \\\"maybeReverseProxy.RuleDeny\\\"\", localizer.T(\"internal_server_error\")))\n\t\t\treturn true\n\t\t}\n\t\thash := rule.Hash()\n\n\t\tlg.Debug(\"rule hash\", \"hash\", hash)\n\t\ts.respondWithStatus(w, r, fmt.Sprintf(\"%s %s\", localizer.T(\"access_denied\"), hash), s.policy.StatusCodes.Deny)\n\t\treturn true\n\tcase config.RuleChallenge:\n\t\tlg.Debug(\"challenge requested\")\n\tcase config.RuleBenchmark:\n\t\tlg.Debug(\"serving benchmark page\")\n\t\ts.RenderBench(w, r)\n\t\treturn true\n\tdefault:\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\tslog.Error(\"CONFIG ERROR: unknown rule\", \"rule\", cr.Rule)\n\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s \\\"maybeReverseProxy.Rules\\\"\", localizer.T(\"internal_server_error\")))\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (s *Server) handleDNSBL(w http.ResponseWriter, r *http.Request, ip string, lg *slog.Logger) bool {\n\tdb := &store.JSON[dnsbl.DroneBLResponse]{Underlying: s.store, Prefix: \"dronebl:\"}\n\tif s.policy.DNSBL && ip != \"\" {\n\t\tresp, err := db.Get(r.Context(), ip)\n\t\tif err != nil {\n\t\t\tlg.Debug(\"looking up ip in dnsbl\")\n\t\t\tresp, err := dnsbl.Lookup(ip)\n\t\t\tif err != nil {\n\t\t\t\tlg.Error(\"can't look up ip in dnsbl\", \"err\", err)\n\t\t\t}\n\t\t\tdb.Set(r.Context(), ip, resp, 24*time.Hour)\n\t\t\tdroneBLHits.WithLabelValues(resp.String()).Inc()\n\t\t}\n\n\t\tif resp != dnsbl.AllGood {\n\t\t\tlg.Info(\"DNSBL hit\", \"status\", resp.String())\n\t\t\tlocalizer := localization.GetLocalizer(r)\n\t\t\ts.respondWithStatus(w, r, fmt.Sprintf(\"%s: %s, %s https://dronebl.org/lookup?ip=%s\",\n\t\t\t\tlocalizer.T(\"dronebl_entry\"),\n\t\t\t\tresp.String(),\n\t\t\t\tlocalizer.T(\"see_dronebl_lookup\"),\n\t\t\t\tip), s.policy.StatusCodes.Deny)\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n", "suffix_code": "\n\nfunc (s *Server) PassChallenge(w http.ResponseWriter, r *http.Request) {\n\tlg := internal.GetRequestLogger(r)\n\tlocalizer := localization.GetLocalizer(r)\n\n\tredir := r.FormValue(\"redir\")\n\tredirURL, err := url.ParseRequestURI(redir)\n\tif err != nil {\n\t\tlg.Error(\"invalid redirect\", \"err\", err)\n\t\ts.respondWithStatus(w, r, localizer.T(\"invalid_redirect\"), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tswitch redirURL.Scheme {\n\tcase \"\", \"http\", \"https\":\n\t\t// allowed\n\tdefault:\n\t\tlg.Error(\"XSS attempt blocked, invalid redirect scheme\", \"scheme\", redirURL.Scheme)\n\t\ts.respondWithStatus(w, r, localizer.T(\"invalid_redirect\"), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// Adjust cookie path if base prefix is not empty\n\tcookiePath := \"/\"\n\tif anubis.BasePrefix != \"\" {\n\t\tcookiePath = strings.TrimSuffix(anubis.BasePrefix, \"/\") + \"/\"\n\t}\n\n\tif _, err := r.Cookie(anubis.TestCookieName); errors.Is(err, http.ErrNoCookie) {\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.ClearCookie(w, CookieOpts{Name: anubis.TestCookieName, Host: r.Host})\n\t\tlg.Warn(\"user has cookies disabled, this is not an anubis bug\")\n\t\ts.respondWithError(w, r, localizer.T(\"cookies_disabled\"))\n\t\treturn\n\t}\n\n\t// used by the path checker rule\n\tr.URL = redirURL\n\n\turlParsed, err := r.URL.Parse(redir)\n\tif err != nil {\n\t\ts.respondWithError(w, r, localizer.T(\"redirect_not_parseable\"))\n\t\treturn\n\t}\n\tif (len(urlParsed.Host) > 0 && len(s.opts.RedirectDomains) != 0 && !slices.Contains(s.opts.RedirectDomains, urlParsed.Host)) || urlParsed.Host != r.URL.Host {\n\t\ts.respondWithError(w, r, localizer.T(\"redirect_domain_not_allowed\"))\n\t\treturn\n\t}\n\n\tcr, rule, err := s.check(r)\n\tif err != nil {\n\t\tlg.Error(\"check failed\", \"err\", err)\n\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s \\\"passChallenge\\\"\", localizer.T(\"internal_server_error\")))\n\t\treturn\n\t}\n\tlg = lg.With(\"check_result\", cr)\n\n\timpl, ok := challenge.Get(rule.Challenge.Algorithm)\n\tif !ok {\n\t\tlg.Error(\"check failed\", \"err\", err)\n\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s: %s\", localizer.T(\"internal_server_error\"), rule.Challenge.Algorithm))\n\t\treturn\n\t}\n\n\tchall, err := s.challengeFor(r)\n\tif err != nil {\n\t\tlg.Error(\"check failed\", \"err\", err)\n\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s: %s\", localizer.T(\"internal_server_error\"), rule.Challenge.Algorithm))\n\t\treturn\n\t}\n\n\tin := &challenge.ValidateInput{\n\t\tChallenge: chall,\n\t\tRule: rule,\n\t\tStore: s.store,\n\t}\n\n\tif err := impl.Validate(r, lg, in); err != nil {\n\t\tfailedValidations.WithLabelValues(rule.Challenge.Algorithm).Inc()\n\t\tvar cerr *challenge.Error\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\tlg.Debug(\"challenge validate call failed\", \"err\", err)\n\n\t\tswitch {\n\t\tcase errors.As(err, &cerr):\n\t\t\tswitch {\n\t\t\tcase errors.Is(err, challenge.ErrFailed):\n\t\t\t\ts.respondWithStatus(w, r, cerr.PublicReason, cerr.StatusCode)\n\t\t\tcase errors.Is(err, challenge.ErrInvalidFormat), errors.Is(err, challenge.ErrMissingField):\n\t\t\t\ts.respondWithError(w, r, cerr.PublicReason)\n\t\t\t}\n\t\t}\n\t}\n\n\t// generate JWT cookie\n\ttokenString, err := s.signJWT(jwt.MapClaims{\n\t\t\"challenge\": chall.ID,\n\t\t\"method\": rule.Challenge.Algorithm,\n\t\t\"policyRule\": rule.Hash(),\n\t\t\"action\": string(cr.Rule),\n\t})\n\tif err != nil {\n\t\tlg.Error(\"failed to sign JWT\", \"err\", err)\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.respondWithError(w, r, localizer.T(\"failed_to_sign_jwt\"))\n\t\treturn\n\t}\n\n\ts.SetCookie(w, CookieOpts{Path: cookiePath, Host: r.Host, Value: tokenString})\n\n\tchallengesValidated.WithLabelValues(rule.Challenge.Algorithm).Inc()\n\tlg.Debug(\"challenge passed, redirecting to app\")\n\thttp.Redirect(w, r, redir, http.StatusFound)\n}\n\nfunc cr(name string, rule config.Rule, weight int) policy.CheckResult {\n\treturn policy.CheckResult{\n\t\tName: name,\n\t\tRule: rule,\n\t\tWeight: weight,\n\t}\n}\n\n// Check evaluates the list of rules, and returns the result\nfunc (s *Server) check(r *http.Request) (policy.CheckResult, *policy.Bot, error) {\n\thost := r.Header.Get(\"X-Real-Ip\")\n\tif host == \"\" {\n\t\treturn decaymap.Zilch[policy.CheckResult](), nil, fmt.Errorf(\"[misconfiguration] X-Real-Ip header is not set\")\n\t}\n\n\taddr := net.ParseIP(host)\n\tif addr == nil {\n\t\treturn decaymap.Zilch[policy.CheckResult](), nil, fmt.Errorf(\"[misconfiguration] %q is not an IP address\", host)\n\t}\n\n\tweight := 0\n\n\tfor _, b := range s.policy.Bots {\n\t\tmatch, err := b.Rules.Check(r)\n\t\tif err != nil {\n\t\t\treturn decaymap.Zilch[policy.CheckResult](), nil, fmt.Errorf(\"can't run check %s: %w\", b.Name, err)\n\t\t}\n\n\t\tif match {\n\t\t\tswitch b.Action {\n\t\t\tcase config.RuleDeny, config.RuleAllow, config.RuleBenchmark, config.RuleChallenge:\n\t\t\t\treturn cr(\"bot/\"+b.Name, b.Action, weight), &b, nil\n\t\t\tcase config.RuleWeigh:\n\t\t\t\tslog.Debug(\"adjusting weight\", \"name\", b.Name, \"delta\", b.Weight.Adjust)\n\t\t\t\tweight += b.Weight.Adjust\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, t := range s.policy.Thresholds {\n\t\tresult, _, err := t.Program.ContextEval(r.Context(), &policy.ThresholdRequest{Weight: weight})\n\t\tif err != nil {\n\t\t\tslog.Error(\"error when evaluating threshold expression\", \"expression\", t.Expression.String(), \"err\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tvar matches bool\n\n\t\tif val, ok := result.(types.Bool); ok {\n\t\t\tmatches = bool(val)\n\t\t}\n\n\t\tif matches {\n\t\t\treturn cr(\"threshold/\"+t.Name, t.Action, weight), &policy.Bot{\n\t\t\t\tChallenge: t.Challenge,\n\t\t\t\tRules: &checker.List{},\n\t\t\t}, nil\n\t\t}\n\t}\n\n\treturn cr(\"default/allow\", config.RuleAllow, weight), &policy.Bot{\n\t\tChallenge: &config.ChallengeRules{\n\t\t\tDifficulty: s.policy.DefaultDifficulty,\n\t\t\tReportAs: s.policy.DefaultDifficulty,\n\t\t\tAlgorithm: config.DefaultAlgorithm,\n\t\t},\n\t\tRules: &checker.List{},\n\t}, nil\n}\n", "middle_code": "func (s *Server) MakeChallenge(w http.ResponseWriter, r *http.Request) {\n\tlg := internal.GetRequestLogger(r)\n\tlocalizer := localization.GetLocalizer(r)\n\tredir := r.FormValue(\"redir\")\n\tif redir == \"\" {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tencoder := json.NewEncoder(w)\n\t\tlg.Error(\"invalid invocation of MakeChallenge\", \"redir\", redir)\n\t\tencoder.Encode(struct {\n\t\t\tError string `json:\"error\"`\n\t\t}{\n\t\t\tError: localizer.T(\"invalid_invocation\"),\n\t\t})\n\t\treturn\n\t}\n\tr.URL.Path = redir\n\tencoder := json.NewEncoder(w)\n\tcr, rule, err := s.check(r)\n\tif err != nil {\n\t\tlg.Error(\"check failed\", \"err\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\terr := encoder.Encode(struct {\n\t\t\tError string `json:\"error\"`\n\t\t}{\n\t\t\tError: fmt.Sprintf(\"%s \\\"makeChallenge\\\"\", localizer.T(\"internal_server_error\")),\n\t\t})\n\t\tif err != nil {\n\t\t\tlg.Error(\"failed to encode error response\", \"err\", err)\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t}\n\t\treturn\n\t}\n\tlg = lg.With(\"check_result\", cr)\n\tchall, err := s.challengeFor(r)\n\tif err != nil {\n\t\tlg.Error(\"failed to fetch or issue challenge\", \"err\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\terr := encoder.Encode(struct {\n\t\t\tError string `json:\"error\"`\n\t\t}{\n\t\t\tError: fmt.Sprintf(\"%s \\\"makeChallenge\\\"\", localizer.T(\"internal_server_error\")),\n\t\t})\n\t\tif err != nil {\n\t\t\tlg.Error(\"failed to encode error response\", \"err\", err)\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t}\n\t\treturn\n\t}\n\ts.SetCookie(w, CookieOpts{Host: r.Host, Name: anubis.TestCookieName, Value: chall.ID})\n\terr = encoder.Encode(struct {\n\t\tRules *config.ChallengeRules `json:\"rules\"`\n\t\tChallenge string `json:\"challenge\"`\n\t}{\n\t\tChallenge: chall.RandomData,\n\t\tRules: rule.Challenge,\n\t})\n\tif err != nil {\n\t\tlg.Error(\"failed to encode challenge\", \"err\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\tlg.Debug(\"made challenge\", \"challenge\", chall, \"rules\", rule.Challenge, \"cr\", cr)\n\tchallengesIssued.WithLabelValues(\"api\").Inc()\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "go", "sub_task_type": null}, "context_code": [["/anubis/lib/http.go", "package lib\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"net/http\"\n\t\"regexp\"\n\t\"slices\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/TecharoHQ/anubis/internal\"\n\t\"github.com/TecharoHQ/anubis/lib/challenge\"\n\t\"github.com/TecharoHQ/anubis/lib/localization\"\n\t\"github.com/TecharoHQ/anubis/lib/policy\"\n\t\"github.com/TecharoHQ/anubis/web\"\n\t\"github.com/a-h/templ\"\n\t\"github.com/golang-jwt/jwt/v5\"\n\t\"golang.org/x/net/publicsuffix\"\n)\n\nvar domainMatchRegexp = regexp.MustCompile(`^((xn--)?[a-z0-9]+(-[a-z0-9]+)*\\.)+[a-z]{2,}$`)\n\ntype CookieOpts struct {\n\tValue string\n\tHost string\n\tPath string\n\tName string\n\tExpiry time.Duration\n}\n\nfunc (s *Server) SetCookie(w http.ResponseWriter, cookieOpts CookieOpts) {\n\tvar domain = s.opts.CookieDomain\n\tvar name = anubis.CookieName\n\tvar path = \"/\"\n\tif cookieOpts.Name != \"\" {\n\t\tname = cookieOpts.Name\n\t}\n\tif cookieOpts.Path != \"\" {\n\t\tpath = cookieOpts.Path\n\t}\n\tif s.opts.CookieDynamicDomain && domainMatchRegexp.MatchString(cookieOpts.Host) {\n\t\tif etld, err := publicsuffix.EffectiveTLDPlusOne(cookieOpts.Host); err == nil {\n\t\t\tdomain = etld\n\t\t}\n\t}\n\n\tif cookieOpts.Expiry == 0 {\n\t\tcookieOpts.Expiry = s.opts.CookieExpiration\n\t}\n\n\thttp.SetCookie(w, &http.Cookie{\n\t\tName: name,\n\t\tValue: cookieOpts.Value,\n\t\tExpires: time.Now().Add(cookieOpts.Expiry),\n\t\tSameSite: http.SameSiteNoneMode,\n\t\tDomain: domain,\n\t\tSecure: s.opts.CookieSecure,\n\t\tPartitioned: s.opts.CookiePartitioned,\n\t\tPath: path,\n\t})\n}\n\nfunc (s *Server) ClearCookie(w http.ResponseWriter, cookieOpts CookieOpts) {\n\tvar domain = s.opts.CookieDomain\n\tvar name = anubis.CookieName\n\tvar path = \"/\"\n\tif cookieOpts.Name != \"\" {\n\t\tname = cookieOpts.Name\n\t}\n\tif cookieOpts.Path != \"\" {\n\t\tpath = cookieOpts.Path\n\t}\n\tif s.opts.CookieDynamicDomain && domainMatchRegexp.MatchString(cookieOpts.Host) {\n\t\tif etld, err := publicsuffix.EffectiveTLDPlusOne(cookieOpts.Host); err == nil {\n\t\t\tdomain = etld\n\t\t}\n\t}\n\n\thttp.SetCookie(w, &http.Cookie{\n\t\tName: name,\n\t\tValue: \"\",\n\t\tMaxAge: -1,\n\t\tExpires: time.Now().Add(-1 * time.Minute),\n\t\tSameSite: http.SameSiteNoneMode,\n\t\tPartitioned: s.opts.CookiePartitioned,\n\t\tDomain: domain,\n\t\tSecure: s.opts.CookieSecure,\n\t\tPath: path,\n\t})\n}\n\n// https://github.com/oauth2-proxy/oauth2-proxy/blob/master/pkg/upstream/http.go#L124\ntype UnixRoundTripper struct {\n\tTransport *http.Transport\n}\n\n// set bare minimum stuff\nfunc (t UnixRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {\n\treq = req.Clone(req.Context())\n\tif req.Host == \"\" {\n\t\treq.Host = \"localhost\"\n\t}\n\treq.URL.Host = req.Host // proxy error: no Host in request URL\n\treq.URL.Scheme = \"http\" // make http.Transport happy and avoid an infinite recursion\n\treturn t.Transport.RoundTrip(req)\n}\n\nfunc randomChance(n int) bool {\n\treturn rand.Intn(n) == 0\n}\n\nfunc (s *Server) RenderIndex(w http.ResponseWriter, r *http.Request, rule *policy.Bot, returnHTTPStatusOnly bool) {\n\tlocalizer := localization.GetLocalizer(r)\n\n\tif returnHTTPStatusOnly {\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\tw.Write([]byte(localizer.T(\"authorization_required\")))\n\t\treturn\n\t}\n\n\tlg := internal.GetRequestLogger(r)\n\n\tif !strings.Contains(r.Header.Get(\"Accept-Encoding\"), \"gzip\") && randomChance(64) {\n\t\tlg.Error(\"client was given a challenge but does not in fact support gzip compression\")\n\t\ts.respondWithError(w, r, localizer.T(\"client_error_browser\"))\n\t}\n\n\tchallengesIssued.WithLabelValues(\"embedded\").Add(1)\n\tchall, err := s.challengeFor(r)\n\tif err != nil {\n\t\tlg.Error(\"can't get challenge\", \"err\", \"err\")\n\t\ts.ClearCookie(w, CookieOpts{Name: anubis.TestCookieName, Host: r.Host})\n\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s: %s\", localizer.T(\"internal_server_error\"), rule.Challenge.Algorithm))\n\t\treturn\n\t}\n\n\tvar ogTags map[string]string = nil\n\tif s.opts.OpenGraph.Enabled {\n\t\tvar err error\n\t\togTags, err = s.OGTags.GetOGTags(r.Context(), r.URL, r.Host)\n\t\tif err != nil {\n\t\t\tlg.Error(\"failed to get OG tags\", \"err\", err)\n\t\t}\n\t}\n\n\ts.SetCookie(w, CookieOpts{\n\t\tValue: chall.ID,\n\t\tHost: r.Host,\n\t\tPath: \"/\",\n\t\tName: anubis.TestCookieName,\n\t\tExpiry: 30 * time.Minute,\n\t})\n\n\timpl, ok := challenge.Get(rule.Challenge.Algorithm)\n\tif !ok {\n\t\tlg.Error(\"check failed\", \"err\", \"can't get algorithm\", \"algorithm\", rule.Challenge.Algorithm)\n\t\ts.ClearCookie(w, CookieOpts{Name: anubis.TestCookieName, Host: r.Host})\n\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s: %s\", localizer.T(\"internal_server_error\"), rule.Challenge.Algorithm))\n\t\treturn\n\t}\n\n\tin := &challenge.IssueInput{\n\t\tImpressum: s.policy.Impressum,\n\t\tRule: rule,\n\t\tChallenge: chall,\n\t\tOGTags: ogTags,\n\t\tStore: s.store,\n\t}\n\n\tcomponent, err := impl.Issue(r, lg, in)\n\tif err != nil {\n\t\tlg.Error(\"[unexpected] render failed, please open an issue\", \"err\", err) // This is likely a bug in the template. Should never be triggered as CI tests for this.\n\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s \\\"RenderIndex\\\"\", localizer.T(\"internal_server_error\")))\n\t\treturn\n\t}\n\n\thandler := internal.GzipMiddleware(1, internal.NoStoreCache(templ.Handler(\n\t\tcomponent,\n\t\ttempl.WithStatus(s.opts.Policy.StatusCodes.Challenge),\n\t)))\n\thandler.ServeHTTP(w, r)\n}\n\nfunc (s *Server) RenderBench(w http.ResponseWriter, r *http.Request) {\n\tlocalizer := localization.GetLocalizer(r)\n\n\ttempl.Handler(\n\t\tweb.Base(localizer.T(\"benchmarking_anubis\"), web.Bench(localizer), s.policy.Impressum, localizer),\n\t).ServeHTTP(w, r)\n}\n\nfunc (s *Server) respondWithError(w http.ResponseWriter, r *http.Request, message string) {\n\ts.respondWithStatus(w, r, message, http.StatusInternalServerError)\n}\n\nfunc (s *Server) respondWithStatus(w http.ResponseWriter, r *http.Request, msg string, status int) {\n\tlocalizer := localization.GetLocalizer(r)\n\n\ttempl.Handler(web.Base(localizer.T(\"oh_noes\"), web.ErrorPage(msg, s.opts.WebmasterEmail, localizer), s.policy.Impressum, localizer), templ.WithStatus(status)).ServeHTTP(w, r)\n}\n\nfunc (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\ts.mux.ServeHTTP(w, r)\n}\n\nfunc (s *Server) stripBasePrefixFromRequest(r *http.Request) *http.Request {\n\tif !s.opts.StripBasePrefix || s.opts.BasePrefix == \"\" {\n\t\treturn r\n\t}\n\n\tbasePrefix := strings.TrimSuffix(s.opts.BasePrefix, \"/\")\n\tpath := r.URL.Path\n\n\tif !strings.HasPrefix(path, basePrefix) {\n\t\treturn r\n\t}\n\n\ttrimmedPath := strings.TrimPrefix(path, basePrefix)\n\tif trimmedPath == \"\" {\n\t\ttrimmedPath = \"/\"\n\t}\n\n\t// Clone the request and URL\n\treqCopy := r.Clone(r.Context())\n\turlCopy := *r.URL\n\turlCopy.Path = trimmedPath\n\treqCopy.URL = &urlCopy\n\n\treturn reqCopy\n}\n\nfunc (s *Server) ServeHTTPNext(w http.ResponseWriter, r *http.Request) {\n\tif s.next == nil {\n\t\tlocalizer := localization.GetLocalizer(r)\n\n\t\tredir := r.FormValue(\"redir\")\n\t\turlParsed, err := r.URL.Parse(redir)\n\t\tif err != nil {\n\t\t\ts.respondWithStatus(w, r, localizer.T(\"redirect_not_parseable\"), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tif (len(urlParsed.Host) > 0 && len(s.opts.RedirectDomains) != 0 && !slices.Contains(s.opts.RedirectDomains, urlParsed.Host)) || urlParsed.Host != r.URL.Host {\n\t\t\ts.respondWithStatus(w, r, localizer.T(\"redirect_domain_not_allowed\"), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tif redir != \"\" {\n\t\t\thttp.Redirect(w, r, redir, http.StatusFound)\n\t\t\treturn\n\t\t}\n\n\t\ttempl.Handler(\n\t\t\tweb.Base(localizer.T(\"you_are_not_a_bot\"), web.StaticHappy(localizer), s.policy.Impressum, localizer),\n\t\t).ServeHTTP(w, r)\n\t} else {\n\t\trequestsProxied.WithLabelValues(r.Host).Inc()\n\t\tr = s.stripBasePrefixFromRequest(r)\n\t\ts.next.ServeHTTP(w, r)\n\t}\n}\n\nfunc (s *Server) signJWT(claims jwt.MapClaims) (string, error) {\n\tclaims[\"iat\"] = time.Now().Unix()\n\tclaims[\"nbf\"] = time.Now().Add(-1 * time.Minute).Unix()\n\tclaims[\"exp\"] = time.Now().Add(s.opts.CookieExpiration).Unix()\n\n\tif len(s.hs512Secret) == 0 {\n\t\treturn jwt.NewWithClaims(jwt.SigningMethodEdDSA, claims).SignedString(s.ed25519Priv)\n\t} else {\n\t\treturn jwt.NewWithClaims(jwt.SigningMethodHS512, claims).SignedString(s.hs512Secret)\n\t}\n}\n"], ["/anubis/lib/config.go", "package lib\n\nimport (\n\t\"context\"\n\t\"crypto/ed25519\"\n\t\"crypto/rand\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log/slog\"\n\t\"net/http\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/TecharoHQ/anubis/data\"\n\t\"github.com/TecharoHQ/anubis/internal\"\n\t\"github.com/TecharoHQ/anubis/internal/ogtags\"\n\t\"github.com/TecharoHQ/anubis/lib/challenge\"\n\t\"github.com/TecharoHQ/anubis/lib/localization\"\n\t\"github.com/TecharoHQ/anubis/lib/policy\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/web\"\n\t\"github.com/TecharoHQ/anubis/xess\"\n\t\"github.com/a-h/templ\"\n)\n\ntype Options struct {\n\tNext http.Handler\n\tPolicy *policy.ParsedConfig\n\tTarget string\n\tCookieDynamicDomain bool\n\tCookieDomain string\n\tCookieExpiration time.Duration\n\tCookiePartitioned bool\n\tBasePrefix string\n\tWebmasterEmail string\n\tRedirectDomains []string\n\tED25519PrivateKey ed25519.PrivateKey\n\tHS512Secret []byte\n\tStripBasePrefix bool\n\tOpenGraph config.OpenGraph\n\tServeRobotsTXT bool\n\tCookieSecure bool\n}\n\nfunc LoadPoliciesOrDefault(ctx context.Context, fname string, defaultDifficulty int) (*policy.ParsedConfig, error) {\n\tvar fin io.ReadCloser\n\tvar err error\n\n\tif fname != \"\" {\n\t\tfin, err = os.Open(fname)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"can't parse policy file %s: %w\", fname, err)\n\t\t}\n\t} else {\n\t\tfname = \"(data)/botPolicies.yaml\"\n\t\tfin, err = data.BotPolicies.Open(\"botPolicies.yaml\")\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"[unexpected] can't parse builtin policy file %s: %w\", fname, err)\n\t\t}\n\t}\n\n\tdefer func(fin io.ReadCloser) {\n\t\terr := fin.Close()\n\t\tif err != nil {\n\t\t\tslog.Error(\"failed to close policy file\", \"file\", fname, \"err\", err)\n\t\t}\n\t}(fin)\n\n\tanubisPolicy, err := policy.ParseConfig(ctx, fin, fname, defaultDifficulty)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't parse policy file %s: %w\", fname, err)\n\t}\n\tvar validationErrs []error\n\n\tfor _, b := range anubisPolicy.Bots {\n\t\tif _, ok := challenge.Get(b.Challenge.Algorithm); !ok {\n\t\t\tvalidationErrs = append(validationErrs, fmt.Errorf(\"%w %s\", policy.ErrChallengeRuleHasWrongAlgorithm, b.Challenge.Algorithm))\n\t\t}\n\t}\n\n\tif len(validationErrs) != 0 {\n\t\treturn nil, fmt.Errorf(\"can't do final validation of Anubis config: %w\", errors.Join(validationErrs...))\n\t}\n\n\treturn anubisPolicy, err\n}\n\nfunc New(opts Options) (*Server, error) {\n\tif opts.ED25519PrivateKey == nil && opts.HS512Secret == nil {\n\t\tslog.Debug(\"opts.PrivateKey not set, generating a new one\")\n\t\t_, priv, err := ed25519.GenerateKey(rand.Reader)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"lib: can't generate private key: %v\", err)\n\t\t}\n\t\topts.ED25519PrivateKey = priv\n\t}\n\n\tanubis.BasePrefix = opts.BasePrefix\n\n\tresult := &Server{\n\t\tnext: opts.Next,\n\t\ted25519Priv: opts.ED25519PrivateKey,\n\t\ths512Secret: opts.HS512Secret,\n\t\tpolicy: opts.Policy,\n\t\topts: opts,\n\t\tOGTags: ogtags.NewOGTagCache(opts.Target, opts.Policy.OpenGraph, opts.Policy.Store),\n\t\tstore: opts.Policy.Store,\n\t}\n\n\tmux := http.NewServeMux()\n\txess.Mount(mux)\n\n\t// Helper to add global prefix\n\tregisterWithPrefix := func(pattern string, handler http.Handler, method string) {\n\t\tif method != \"\" {\n\t\t\tmethod = method + \" \" // methods must end with a space to register with them\n\t\t}\n\n\t\t// Ensure there's no double slash when concatenating BasePrefix and pattern\n\t\tbasePrefix := strings.TrimSuffix(anubis.BasePrefix, \"/\")\n\t\tprefix := method + basePrefix\n\n\t\t// If pattern doesn't start with a slash, add one\n\t\tif !strings.HasPrefix(pattern, \"/\") {\n\t\t\tpattern = \"/\" + pattern\n\t\t}\n\n\t\tmux.Handle(prefix+pattern, handler)\n\t}\n\n\t// Ensure there's no double slash when concatenating BasePrefix and StaticPath\n\tstripPrefix := strings.TrimSuffix(anubis.BasePrefix, \"/\") + anubis.StaticPath\n\tregisterWithPrefix(anubis.StaticPath, internal.UnchangingCache(internal.NoBrowsing(http.StripPrefix(stripPrefix, http.FileServerFS(web.Static)))), \"\")\n\n\tif opts.ServeRobotsTXT {\n\t\tregisterWithPrefix(\"/robots.txt\", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\thttp.ServeFileFS(w, r, web.Static, \"static/robots.txt\")\n\t\t}), \"GET\")\n\t\tregisterWithPrefix(\"/.well-known/robots.txt\", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\thttp.ServeFileFS(w, r, web.Static, \"static/robots.txt\")\n\t\t}), \"GET\")\n\t}\n\n\tif opts.Policy.Impressum != nil {\n\t\tregisterWithPrefix(anubis.APIPrefix+\"imprint\", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\ttempl.Handler(\n\t\t\t\tweb.Base(opts.Policy.Impressum.Page.Title, opts.Policy.Impressum.Page, opts.Policy.Impressum, localization.GetLocalizer(r)),\n\t\t\t).ServeHTTP(w, r)\n\t\t}), \"GET\")\n\t}\n\n\tregisterWithPrefix(anubis.APIPrefix+\"pass-challenge\", http.HandlerFunc(result.PassChallenge), \"GET\")\n\tregisterWithPrefix(anubis.APIPrefix+\"check\", http.HandlerFunc(result.maybeReverseProxyHttpStatusOnly), \"\")\n\tregisterWithPrefix(\"/\", http.HandlerFunc(result.maybeReverseProxyOrPage), \"\")\n\n\t//goland:noinspection GoBoolExpressions\n\tif anubis.Version == \"devel\" {\n\t\t// make-challenge is only used in tests. Only enable while version is devel\n\t\tregisterWithPrefix(anubis.APIPrefix+\"make-challenge\", http.HandlerFunc(result.MakeChallenge), \"POST\")\n\t}\n\n\tfor _, implKind := range challenge.Methods() {\n\t\timpl, _ := challenge.Get(implKind)\n\t\timpl.Setup(mux)\n\t}\n\n\tresult.mux = mux\n\n\treturn result, nil\n}\n"], ["/anubis/cmd/anubis/main.go", "package main\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"crypto/ed25519\"\n\t\"crypto/rand\"\n\t\"crypto/tls\"\n\t\"embed\"\n\t\"encoding/hex\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io/fs\"\n\t\"log\"\n\t\"log/slog\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/http/httputil\"\n\t\"net/url\"\n\t\"os\"\n\t\"os/signal\"\n\t\"path/filepath\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/TecharoHQ/anubis/data\"\n\t\"github.com/TecharoHQ/anubis/internal\"\n\tlibanubis \"github.com/TecharoHQ/anubis/lib\"\n\tbotPolicy \"github.com/TecharoHQ/anubis/lib/policy\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/lib/thoth\"\n\t\"github.com/TecharoHQ/anubis/web\"\n\t\"github.com/facebookgo/flagenv\"\n\t_ \"github.com/joho/godotenv/autoload\"\n\t\"github.com/prometheus/client_golang/prometheus/promhttp\"\n\thealthv1 \"google.golang.org/grpc/health/grpc_health_v1\"\n)\n\nvar (\n\tbasePrefix = flag.String(\"base-prefix\", \"\", \"base prefix (root URL) the application is served under e.g. /myapp\")\n\tbind = flag.String(\"bind\", \":8923\", \"network address to bind HTTP to\")\n\tbindNetwork = flag.String(\"bind-network\", \"tcp\", \"network family to bind HTTP to, e.g. unix, tcp\")\n\tchallengeDifficulty = flag.Int(\"difficulty\", anubis.DefaultDifficulty, \"difficulty of the challenge\")\n\tcookieDomain = flag.String(\"cookie-domain\", \"\", \"if set, the top-level domain that the Anubis cookie will be valid for\")\n\tcookieDynamicDomain = flag.Bool(\"cookie-dynamic-domain\", false, \"if set, automatically set the cookie Domain value based on the request domain\")\n\tcookieExpiration = flag.Duration(\"cookie-expiration-time\", anubis.CookieDefaultExpirationTime, \"The amount of time the authorization cookie is valid for\")\n\tcookiePrefix = flag.String(\"cookie-prefix\", \"techaro.lol-anubis\", \"prefix for browser cookies created by Anubis\")\n\tcookiePartitioned = flag.Bool(\"cookie-partitioned\", false, \"if true, sets the partitioned flag on Anubis cookies, enabling CHIPS support\")\n\tforcedLanguage = flag.String(\"forced-language\", \"\", \"if set, this language is being used instead of the one from the request's Accept-Language header\")\n\ths512Secret = flag.String(\"hs512-secret\", \"\", \"secret used to sign JWTs, uses ed25519 if not set\")\n\tcookieSecure = flag.Bool(\"cookie-secure\", true, \"if true, sets the secure flag on Anubis cookies\")\n\ted25519PrivateKeyHex = flag.String(\"ed25519-private-key-hex\", \"\", \"private key used to sign JWTs, if not set a random one will be assigned\")\n\ted25519PrivateKeyHexFile = flag.String(\"ed25519-private-key-hex-file\", \"\", \"file name containing value for ed25519-private-key-hex\")\n\tmetricsBind = flag.String(\"metrics-bind\", \":9090\", \"network address to bind metrics to\")\n\tmetricsBindNetwork = flag.String(\"metrics-bind-network\", \"tcp\", \"network family for the metrics server to bind to\")\n\tsocketMode = flag.String(\"socket-mode\", \"0770\", \"socket mode (permissions) for unix domain sockets.\")\n\trobotsTxt = flag.Bool(\"serve-robots-txt\", false, \"serve a robots.txt file that disallows all robots\")\n\tpolicyFname = flag.String(\"policy-fname\", \"\", \"full path to anubis policy document (defaults to a sensible built-in policy)\")\n\tredirectDomains = flag.String(\"redirect-domains\", \"\", \"list of domains separated by commas which anubis is allowed to redirect to. Leaving this unset allows any domain.\")\n\tslogLevel = flag.String(\"slog-level\", \"INFO\", \"logging level (see https://pkg.go.dev/log/slog#hdr-Levels)\")\n\tstripBasePrefix = flag.Bool(\"strip-base-prefix\", false, \"if true, strips the base prefix from requests forwarded to the target server\")\n\ttarget = flag.String(\"target\", \"http://localhost:3923\", \"target to reverse proxy to, set to an empty string to disable proxying when only using auth request\")\n\ttargetSNI = flag.String(\"target-sni\", \"\", \"if set, the value of the TLS handshake hostname when forwarding requests to the target\")\n\ttargetHost = flag.String(\"target-host\", \"\", \"if set, the value of the Host header when forwarding requests to the target\")\n\ttargetInsecureSkipVerify = flag.Bool(\"target-insecure-skip-verify\", false, \"if true, skips TLS validation for the backend\")\n\thealthcheck = flag.Bool(\"healthcheck\", false, \"run a health check against Anubis\")\n\tuseRemoteAddress = flag.Bool(\"use-remote-address\", false, \"read the client's IP address from the network request, useful for debugging and running Anubis on bare metal\")\n\tdebugBenchmarkJS = flag.Bool(\"debug-benchmark-js\", false, \"respond to every request with a challenge for benchmarking hashrate\")\n\togPassthrough = flag.Bool(\"og-passthrough\", false, \"enable Open Graph tag passthrough\")\n\togTimeToLive = flag.Duration(\"og-expiry-time\", 24*time.Hour, \"Open Graph tag cache expiration time\")\n\togCacheConsiderHost = flag.Bool(\"og-cache-consider-host\", false, \"enable or disable the use of the host in the Open Graph tag cache\")\n\textractResources = flag.String(\"extract-resources\", \"\", \"if set, extract the static resources to the specified folder\")\n\twebmasterEmail = flag.String(\"webmaster-email\", \"\", \"if set, displays webmaster's email on the reject page for appeals\")\n\tversionFlag = flag.Bool(\"version\", false, \"print Anubis version\")\n\txffStripPrivate = flag.Bool(\"xff-strip-private\", true, \"if set, strip private addresses from X-Forwarded-For\")\n\n\tthothInsecure = flag.Bool(\"thoth-insecure\", false, \"if set, connect to Thoth over plain HTTP/2, don't enable this unless support told you to\")\n\tthothURL = flag.String(\"thoth-url\", \"\", \"if set, URL for Thoth, the IP reputation database for Anubis\")\n\tthothToken = flag.String(\"thoth-token\", \"\", \"if set, API token for Thoth, the IP reputation database for Anubis\")\n)\n\nfunc keyFromHex(value string) (ed25519.PrivateKey, error) {\n\tkeyBytes, err := hex.DecodeString(value)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"supplied key is not hex-encoded: %w\", err)\n\t}\n\n\tif len(keyBytes) != ed25519.SeedSize {\n\t\treturn nil, fmt.Errorf(\"supplied key is not %d bytes long, got %d bytes\", ed25519.SeedSize, len(keyBytes))\n\t}\n\n\treturn ed25519.NewKeyFromSeed(keyBytes), nil\n}\n\nfunc doHealthCheck() error {\n\tresp, err := http.Get(\"http://localhost\" + *metricsBind + \"/healthz\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to fetch metrics: %w\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn fmt.Errorf(\"unexpected status code: %d\", resp.StatusCode)\n\t}\n\n\treturn nil\n}\n\n// parseBindNetFromAddr determine bind network and address based on the given network and address.\nfunc parseBindNetFromAddr(address string) (string, string) {\n\tdefaultScheme := \"http://\"\n\tif !strings.Contains(address, \"://\") {\n\t\tif strings.HasPrefix(address, \":\") {\n\t\t\taddress = defaultScheme + \"localhost\" + address\n\t\t} else {\n\t\t\taddress = defaultScheme + address\n\t\t}\n\t}\n\n\tbindUri, err := url.Parse(address)\n\tif err != nil {\n\t\tlog.Fatal(fmt.Errorf(\"failed to parse bind URL: %w\", err))\n\t}\n\n\tswitch bindUri.Scheme {\n\tcase \"unix\":\n\t\treturn \"unix\", bindUri.Path\n\tcase \"tcp\", \"http\", \"https\":\n\t\treturn \"tcp\", bindUri.Host\n\tdefault:\n\t\tlog.Fatal(fmt.Errorf(\"unsupported network scheme %s in address %s\", bindUri.Scheme, address))\n\t}\n\treturn \"\", address\n}\n\nfunc setupListener(network string, address string) (net.Listener, string) {\n\tformattedAddress := \"\"\n\n\tif network == \"\" {\n\t\t// keep compatibility\n\t\tnetwork, address = parseBindNetFromAddr(address)\n\t}\n\n\tswitch network {\n\tcase \"unix\":\n\t\tformattedAddress = \"unix:\" + address\n\tcase \"tcp\":\n\t\tif strings.HasPrefix(address, \":\") { // assume it's just a port e.g. :4259\n\t\t\tformattedAddress = \"http://localhost\" + address\n\t\t} else {\n\t\t\tformattedAddress = \"http://\" + address\n\t\t}\n\tdefault:\n\t\tformattedAddress = fmt.Sprintf(`(%s) %s`, network, address)\n\t}\n\n\tlistener, err := net.Listen(network, address)\n\tif err != nil {\n\t\tlog.Fatal(fmt.Errorf(\"failed to bind to %s: %w\", formattedAddress, err))\n\t}\n\n\t// additional permission handling for unix sockets\n\tif network == \"unix\" {\n\t\tmode, err := strconv.ParseUint(*socketMode, 8, 0)\n\t\tif err != nil {\n\t\t\tlistener.Close()\n\t\t\tlog.Fatal(fmt.Errorf(\"could not parse socket mode %s: %w\", *socketMode, err))\n\t\t}\n\n\t\terr = os.Chmod(address, os.FileMode(mode))\n\t\tif err != nil {\n\t\t\terr := listener.Close()\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"failed to close listener: %v\", err)\n\t\t\t}\n\t\t\tlog.Fatal(fmt.Errorf(\"could not change socket mode: %w\", err))\n\t\t}\n\t}\n\n\treturn listener, formattedAddress\n}\n\nfunc makeReverseProxy(target string, targetSNI string, targetHost string, insecureSkipVerify bool) (http.Handler, error) {\n\ttargetUri, err := url.Parse(target)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to parse target URL: %w\", err)\n\t}\n\n\ttransport := http.DefaultTransport.(*http.Transport).Clone()\n\n\t// https://github.com/oauth2-proxy/oauth2-proxy/blob/4e2100a2879ef06aea1411790327019c1a09217c/pkg/upstream/http.go#L124\n\tif targetUri.Scheme == \"unix\" {\n\t\t// clean path up so we don't use the socket path in proxied requests\n\t\taddr := targetUri.Path\n\t\ttargetUri.Path = \"\"\n\t\t// tell transport how to dial unix sockets\n\t\ttransport.DialContext = func(ctx context.Context, _, _ string) (net.Conn, error) {\n\t\t\tdialer := net.Dialer{}\n\t\t\treturn dialer.DialContext(ctx, \"unix\", addr)\n\t\t}\n\t\t// tell transport how to handle the unix url scheme\n\t\ttransport.RegisterProtocol(\"unix\", libanubis.UnixRoundTripper{Transport: transport})\n\t}\n\n\tif insecureSkipVerify || targetSNI != \"\" {\n\t\ttransport.TLSClientConfig = &tls.Config{}\n\t\tif insecureSkipVerify {\n\t\t\tslog.Warn(\"TARGET_INSECURE_SKIP_VERIFY is set to true, TLS certificate validation will not be performed\", \"target\", target)\n\t\t\ttransport.TLSClientConfig.InsecureSkipVerify = true\n\t\t}\n\t\tif targetSNI != \"\" {\n\t\t\ttransport.TLSClientConfig.ServerName = targetSNI\n\t\t}\n\t}\n\n\trp := httputil.NewSingleHostReverseProxy(targetUri)\n\trp.Transport = transport\n\n\tif targetHost != \"\" {\n\t\toriginalDirector := rp.Director\n\t\trp.Director = func(req *http.Request) {\n\t\t\toriginalDirector(req)\n\t\t\treq.Host = targetHost\n\t\t}\n\t}\n\n\treturn rp, nil\n}\n\nfunc main() {\n\tflagenv.Parse()\n\tflag.Parse()\n\n\tif *versionFlag {\n\t\tfmt.Println(\"Anubis\", anubis.Version)\n\t\treturn\n\t}\n\n\tinternal.InitSlog(*slogLevel)\n\tinternal.SetHealth(\"anubis\", healthv1.HealthCheckResponse_NOT_SERVING)\n\n\tif *healthcheck {\n\t\tlog.Println(\"running healthcheck\")\n\t\tif err := doHealthCheck(); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\treturn\n\t}\n\n\tif *extractResources != \"\" {\n\t\tif err := extractEmbedFS(data.BotPolicies, \".\", *extractResources); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tif err := extractEmbedFS(web.Static, \"static\", *extractResources); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Printf(\"Extracted embedded static files to %s\\n\", *extractResources)\n\t\treturn\n\t}\n\n\t// install signal handler\n\tctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)\n\tdefer stop()\n\n\twg := new(sync.WaitGroup)\n\n\tif *metricsBind != \"\" {\n\t\twg.Add(1)\n\t\tgo metricsServer(ctx, wg.Done)\n\t}\n\n\tvar rp http.Handler\n\t// when using anubis via Systemd and environment variables, then it is not possible to set targe to an empty string but only to space\n\tif strings.TrimSpace(*target) != \"\" {\n\t\tvar err error\n\t\trp, err = makeReverseProxy(*target, *targetSNI, *targetHost, *targetInsecureSkipVerify)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"can't make reverse proxy: %v\", err)\n\t\t}\n\t}\n\n\tif *cookieDomain != \"\" && *cookieDynamicDomain {\n\t\tlog.Fatalf(\"you can't set COOKIE_DOMAIN and COOKIE_DYNAMIC_DOMAIN at the same time\")\n\t}\n\n\t// Thoth configuration\n\tswitch {\n\tcase *thothURL != \"\" && *thothToken == \"\":\n\t\tslog.Warn(\"THOTH_URL is set but no THOTH_TOKEN is set\")\n\tcase *thothURL == \"\" && *thothToken != \"\":\n\t\tslog.Warn(\"THOTH_TOKEN is set but no THOTH_URL is set\")\n\tcase *thothURL != \"\" && *thothToken != \"\":\n\t\tslog.Debug(\"connecting to Thoth\")\n\t\tthothClient, err := thoth.New(ctx, *thothURL, *thothToken, *thothInsecure)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"can't dial thoth at %s: %v\", *thothURL, err)\n\t\t}\n\n\t\tctx = thoth.With(ctx, thothClient)\n\t}\n\n\tpolicy, err := libanubis.LoadPoliciesOrDefault(ctx, *policyFname, *challengeDifficulty)\n\tif err != nil {\n\t\tlog.Fatalf(\"can't parse policy file: %v\", err)\n\t}\n\n\truleErrorIDs := make(map[string]string)\n\tfor _, rule := range policy.Bots {\n\t\tif rule.Action != config.RuleDeny {\n\t\t\tcontinue\n\t\t}\n\n\t\thash := rule.Hash()\n\t\truleErrorIDs[rule.Name] = hash\n\t}\n\n\t// replace the bot policy rules with a single rule that always benchmarks\n\tif *debugBenchmarkJS {\n\t\tpolicy.Bots = []botPolicy.Bot{{\n\t\t\tName: \"\",\n\t\t\tRules: botPolicy.NewHeaderExistsChecker(\"User-Agent\"),\n\t\t\tAction: config.RuleBenchmark,\n\t\t}}\n\t}\n\tif *basePrefix != \"\" && !strings.HasPrefix(*basePrefix, \"/\") {\n\t\tlog.Fatalf(\"[misconfiguration] base-prefix must start with a slash, eg: /%s\", *basePrefix)\n\t} else if strings.HasSuffix(*basePrefix, \"/\") {\n\t\tlog.Fatalf(\"[misconfiguration] base-prefix must not end with a slash\")\n\t}\n\tif *stripBasePrefix && *basePrefix == \"\" {\n\t\tlog.Fatalf(\"[misconfiguration] strip-base-prefix is set to true, but base-prefix is not set, \" +\n\t\t\t\"this may result in unexpected behavior\")\n\t}\n\n\tvar ed25519Priv ed25519.PrivateKey\n\tif *hs512Secret != \"\" && (*ed25519PrivateKeyHex != \"\" || *ed25519PrivateKeyHexFile != \"\") {\n\t\tlog.Fatal(\"do not specify both HS512 and ED25519 secrets\")\n\t} else if *hs512Secret != \"\" {\n\t\ted25519Priv = ed25519.PrivateKey(*hs512Secret)\n\t} else if *ed25519PrivateKeyHex != \"\" && *ed25519PrivateKeyHexFile != \"\" {\n\t\tlog.Fatal(\"do not specify both ED25519_PRIVATE_KEY_HEX and ED25519_PRIVATE_KEY_HEX_FILE\")\n\t} else if *ed25519PrivateKeyHex != \"\" {\n\t\ted25519Priv, err = keyFromHex(*ed25519PrivateKeyHex)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to parse and validate ED25519_PRIVATE_KEY_HEX: %v\", err)\n\t\t}\n\t} else if *ed25519PrivateKeyHexFile != \"\" {\n\t\thexFile, err := os.ReadFile(*ed25519PrivateKeyHexFile)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to read ED25519_PRIVATE_KEY_HEX_FILE %s: %v\", *ed25519PrivateKeyHexFile, err)\n\t\t}\n\n\t\ted25519Priv, err = keyFromHex(string(bytes.TrimSpace(hexFile)))\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to parse and validate content of ED25519_PRIVATE_KEY_HEX_FILE: %v\", err)\n\t\t}\n\t} else {\n\t\t_, ed25519Priv, err = ed25519.GenerateKey(rand.Reader)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to generate ed25519 key: %v\", err)\n\t\t}\n\n\t\tslog.Warn(\"generating random key, Anubis will have strange behavior when multiple instances are behind the same load balancer target, for more information: see https://anubis.techaro.lol/docs/admin/installation#key-generation\")\n\t}\n\n\tvar redirectDomainsList []string\n\tif *redirectDomains != \"\" {\n\t\tdomains := strings.Split(*redirectDomains, \",\")\n\t\tfor _, domain := range domains {\n\t\t\t_, err = url.Parse(domain)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"cannot parse redirect-domain %q: %s\", domain, err.Error())\n\t\t\t}\n\t\t\tredirectDomainsList = append(redirectDomainsList, strings.TrimSpace(domain))\n\t\t}\n\t} else {\n\t\tslog.Warn(\"REDIRECT_DOMAINS is not set, Anubis will only redirect to the same domain a request is coming from, see https://anubis.techaro.lol/docs/admin/configuration/redirect-domains\")\n\t}\n\n\tanubis.CookieName = *cookiePrefix + \"-auth\"\n\tanubis.TestCookieName = *cookiePrefix + \"-cookie-verification\"\n\tanubis.ForcedLanguage = *forcedLanguage\n\n\t// If OpenGraph configuration values are not set in the config file, use the\n\t// values from flags / envvars.\n\tif !policy.OpenGraph.Enabled {\n\t\tpolicy.OpenGraph.Enabled = *ogPassthrough\n\t\tpolicy.OpenGraph.ConsiderHost = *ogCacheConsiderHost\n\t\tpolicy.OpenGraph.TimeToLive = *ogTimeToLive\n\t\tpolicy.OpenGraph.Override = map[string]string{}\n\t}\n\n\ts, err := libanubis.New(libanubis.Options{\n\t\tBasePrefix: *basePrefix,\n\t\tStripBasePrefix: *stripBasePrefix,\n\t\tNext: rp,\n\t\tPolicy: policy,\n\t\tServeRobotsTXT: *robotsTxt,\n\t\tED25519PrivateKey: ed25519Priv,\n\t\tHS512Secret: []byte(*hs512Secret),\n\t\tCookieDomain: *cookieDomain,\n\t\tCookieDynamicDomain: *cookieDynamicDomain,\n\t\tCookieExpiration: *cookieExpiration,\n\t\tCookiePartitioned: *cookiePartitioned,\n\t\tRedirectDomains: redirectDomainsList,\n\t\tTarget: *target,\n\t\tWebmasterEmail: *webmasterEmail,\n\t\tOpenGraph: policy.OpenGraph,\n\t\tCookieSecure: *cookieSecure,\n\t})\n\tif err != nil {\n\t\tlog.Fatalf(\"can't construct libanubis.Server: %v\", err)\n\t}\n\n\tvar h http.Handler\n\th = s\n\th = internal.RemoteXRealIP(*useRemoteAddress, *bindNetwork, h)\n\th = internal.XForwardedForToXRealIP(h)\n\th = internal.XForwardedForUpdate(*xffStripPrivate, h)\n\th = internal.JA4H(h)\n\n\tsrv := http.Server{Handler: h, ErrorLog: internal.GetFilteredHTTPLogger()}\n\tlistener, listenerUrl := setupListener(*bindNetwork, *bind)\n\tslog.Info(\n\t\t\"listening\",\n\t\t\"url\", listenerUrl,\n\t\t\"difficulty\", *challengeDifficulty,\n\t\t\"serveRobotsTXT\", *robotsTxt,\n\t\t\"target\", *target,\n\t\t\"version\", anubis.Version,\n\t\t\"use-remote-address\", *useRemoteAddress,\n\t\t\"debug-benchmark-js\", *debugBenchmarkJS,\n\t\t\"og-passthrough\", *ogPassthrough,\n\t\t\"og-expiry-time\", *ogTimeToLive,\n\t\t\"base-prefix\", *basePrefix,\n\t\t\"cookie-expiration-time\", *cookieExpiration,\n\t\t\"rule-error-ids\", ruleErrorIDs,\n\t)\n\n\tgo func() {\n\t\t<-ctx.Done()\n\t\tc, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\t\tdefer cancel()\n\t\tif err := srv.Shutdown(c); err != nil {\n\t\t\tlog.Printf(\"cannot shut down: %v\", err)\n\t\t}\n\t}()\n\n\tinternal.SetHealth(\"anubis\", healthv1.HealthCheckResponse_SERVING)\n\n\tif err := srv.Serve(listener); !errors.Is(err, http.ErrServerClosed) {\n\t\tlog.Fatal(err)\n\t}\n\twg.Wait()\n}\n\nfunc metricsServer(ctx context.Context, done func()) {\n\tdefer done()\n\n\tmux := http.NewServeMux()\n\tmux.Handle(\"/metrics\", promhttp.Handler())\n\tmux.HandleFunc(\"/healthz\", func(w http.ResponseWriter, r *http.Request) {\n\t\tst, ok := internal.GetHealth(\"anubis\")\n\t\tif !ok {\n\t\t\tslog.Error(\"health service anubis does not exist, file a bug\")\n\t\t}\n\n\t\tswitch st {\n\t\tcase healthv1.HealthCheckResponse_NOT_SERVING:\n\t\t\thttp.Error(w, \"NOT OK\", http.StatusInternalServerError)\n\t\t\treturn\n\t\tcase healthv1.HealthCheckResponse_SERVING:\n\t\t\tfmt.Fprintln(w, \"OK\")\n\t\t\treturn\n\t\tdefault:\n\t\t\thttp.Error(w, \"UNKNOWN\", http.StatusFailedDependency)\n\t\t\treturn\n\t\t}\n\t})\n\n\tsrv := http.Server{Handler: mux, ErrorLog: internal.GetFilteredHTTPLogger()}\n\tlistener, metricsUrl := setupListener(*metricsBindNetwork, *metricsBind)\n\tslog.Debug(\"listening for metrics\", \"url\", metricsUrl)\n\n\tgo func() {\n\t\t<-ctx.Done()\n\t\tc, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\t\tdefer cancel()\n\t\tif err := srv.Shutdown(c); err != nil {\n\t\t\tlog.Printf(\"cannot shut down: %v\", err)\n\t\t}\n\t}()\n\n\tif err := srv.Serve(listener); !errors.Is(err, http.ErrServerClosed) {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc extractEmbedFS(fsys embed.FS, root string, destDir string) error {\n\treturn fs.WalkDir(fsys, root, func(path string, d fs.DirEntry, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\trelPath, err := filepath.Rel(root, path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdestPath := filepath.Join(destDir, root, relPath)\n\n\t\tif d.IsDir() {\n\t\t\treturn os.MkdirAll(destPath, 0o700)\n\t\t}\n\n\t\tembeddedData, err := fs.ReadFile(fsys, path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn os.WriteFile(destPath, embeddedData, 0o644)\n\t})\n}\n"], ["/anubis/lib/challenge/proofofwork/proofofwork.go", "package proofofwork\n\nimport (\n\t\"crypto/subtle\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net/http\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com/TecharoHQ/anubis/internal\"\n\tchall \"github.com/TecharoHQ/anubis/lib/challenge\"\n\t\"github.com/TecharoHQ/anubis/lib/localization\"\n\t\"github.com/TecharoHQ/anubis/web\"\n\t\"github.com/a-h/templ\"\n)\n\nfunc init() {\n\tchall.Register(\"fast\", &Impl{Algorithm: \"fast\"})\n\tchall.Register(\"slow\", &Impl{Algorithm: \"slow\"})\n}\n\ntype Impl struct {\n\tAlgorithm string\n}\n\nfunc (i *Impl) Setup(mux *http.ServeMux) {\n\t/* no implementation required */\n}\n\nfunc (i *Impl) Issue(r *http.Request, lg *slog.Logger, in *chall.IssueInput) (templ.Component, error) {\n\tloc := localization.GetLocalizer(r)\n\tcomponent, err := web.BaseWithChallengeAndOGTags(loc.T(\"making_sure_not_bot\"), web.Index(loc), in.Impressum, in.Challenge.RandomData, in.Rule.Challenge, in.OGTags, loc)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't render page: %w\", err)\n\t}\n\n\treturn component, nil\n}\n\nfunc (i *Impl) Validate(r *http.Request, lg *slog.Logger, in *chall.ValidateInput) error {\n\trule := in.Rule\n\tchallenge := in.Challenge.RandomData\n\n\tnonceStr := r.FormValue(\"nonce\")\n\tif nonceStr == \"\" {\n\t\treturn chall.NewError(\"validate\", \"invalid response\", fmt.Errorf(\"%w nonce\", chall.ErrMissingField))\n\t}\n\n\tnonce, err := strconv.Atoi(nonceStr)\n\tif err != nil {\n\t\treturn chall.NewError(\"validate\", \"invalid response\", fmt.Errorf(\"%w: nonce: %w\", chall.ErrInvalidFormat, err))\n\n\t}\n\n\telapsedTimeStr := r.FormValue(\"elapsedTime\")\n\tif elapsedTimeStr == \"\" {\n\t\treturn chall.NewError(\"validate\", \"invalid response\", fmt.Errorf(\"%w elapsedTime\", chall.ErrMissingField))\n\t}\n\n\telapsedTime, err := strconv.ParseFloat(elapsedTimeStr, 64)\n\tif err != nil {\n\t\treturn chall.NewError(\"validate\", \"invalid response\", fmt.Errorf(\"%w: elapsedTime: %w\", chall.ErrInvalidFormat, err))\n\t}\n\n\tresponse := r.FormValue(\"response\")\n\tif response == \"\" {\n\t\treturn chall.NewError(\"validate\", \"invalid response\", fmt.Errorf(\"%w response\", chall.ErrMissingField))\n\t}\n\n\tcalcString := fmt.Sprintf(\"%s%d\", challenge, nonce)\n\tcalculated := internal.SHA256sum(calcString)\n\n\tif subtle.ConstantTimeCompare([]byte(response), []byte(calculated)) != 1 {\n\t\treturn chall.NewError(\"validate\", \"invalid response\", fmt.Errorf(\"%w: wanted response %s but got %s\", chall.ErrFailed, calculated, response))\n\t}\n\n\t// compare the leading zeroes\n\tif !strings.HasPrefix(response, strings.Repeat(\"0\", rule.Challenge.Difficulty)) {\n\t\treturn chall.NewError(\"validate\", \"invalid response\", fmt.Errorf(\"%w: wanted %d leading zeros but got %s\", chall.ErrFailed, rule.Challenge.Difficulty, response))\n\t}\n\n\tlg.Debug(\"challenge took\", \"elapsedTime\", elapsedTime)\n\tchall.TimeTaken.WithLabelValues(i.Algorithm).Observe(elapsedTime)\n\n\treturn nil\n}\n"], ["/anubis/lib/policy/policy.go", "package policy\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log/slog\"\n\t\"sync/atomic\"\n\n\t\"github.com/TecharoHQ/anubis/lib/policy/checker\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n\t\"github.com/TecharoHQ/anubis/lib/thoth\"\n\t\"github.com/prometheus/client_golang/prometheus\"\n\t\"github.com/prometheus/client_golang/prometheus/promauto\"\n\n\t_ \"github.com/TecharoHQ/anubis/lib/store/all\"\n)\n\nvar (\n\tApplications = promauto.NewCounterVec(prometheus.CounterOpts{\n\t\tName: \"anubis_policy_results\",\n\t\tHelp: \"The results of each policy rule\",\n\t}, []string{\"rule\", \"action\"})\n\n\tErrChallengeRuleHasWrongAlgorithm = errors.New(\"config.Bot.ChallengeRules: algorithm is invalid\")\n\twarnedAboutThresholds = &atomic.Bool{}\n)\n\ntype ParsedConfig struct {\n\torig *config.Config\n\n\tBots []Bot\n\tThresholds []*Threshold\n\tDNSBL bool\n\tImpressum *config.Impressum\n\tOpenGraph config.OpenGraph\n\tDefaultDifficulty int\n\tStatusCodes config.StatusCodes\n\tStore store.Interface\n}\n\nfunc newParsedConfig(orig *config.Config) *ParsedConfig {\n\treturn &ParsedConfig{\n\t\torig: orig,\n\t\tOpenGraph: orig.OpenGraph,\n\t\tStatusCodes: orig.StatusCodes,\n\t}\n}\n\nfunc ParseConfig(ctx context.Context, fin io.Reader, fname string, defaultDifficulty int) (*ParsedConfig, error) {\n\tc, err := config.Load(fin, fname)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar validationErrs []error\n\n\ttc, hasThothClient := thoth.FromContext(ctx)\n\n\tresult := newParsedConfig(c)\n\tresult.DefaultDifficulty = defaultDifficulty\n\n\tfor _, b := range c.Bots {\n\t\tif berr := b.Valid(); berr != nil {\n\t\t\tvalidationErrs = append(validationErrs, berr)\n\t\t\tcontinue\n\t\t}\n\n\t\tparsedBot := Bot{\n\t\t\tName: b.Name,\n\t\t\tAction: b.Action,\n\t\t}\n\n\t\tcl := checker.List{}\n\n\t\tif len(b.RemoteAddr) > 0 {\n\t\t\tc, err := NewRemoteAddrChecker(b.RemoteAddr)\n\t\t\tif err != nil {\n\t\t\t\tvalidationErrs = append(validationErrs, fmt.Errorf(\"while processing rule %s remote addr set: %w\", b.Name, err))\n\t\t\t} else {\n\t\t\t\tcl = append(cl, c)\n\t\t\t}\n\t\t}\n\n\t\tif b.UserAgentRegex != nil {\n\t\t\tc, err := NewUserAgentChecker(*b.UserAgentRegex)\n\t\t\tif err != nil {\n\t\t\t\tvalidationErrs = append(validationErrs, fmt.Errorf(\"while processing rule %s user agent regex: %w\", b.Name, err))\n\t\t\t} else {\n\t\t\t\tcl = append(cl, c)\n\t\t\t}\n\t\t}\n\n\t\tif b.PathRegex != nil {\n\t\t\tc, err := NewPathChecker(*b.PathRegex)\n\t\t\tif err != nil {\n\t\t\t\tvalidationErrs = append(validationErrs, fmt.Errorf(\"while processing rule %s path regex: %w\", b.Name, err))\n\t\t\t} else {\n\t\t\t\tcl = append(cl, c)\n\t\t\t}\n\t\t}\n\n\t\tif len(b.HeadersRegex) > 0 {\n\t\t\tc, err := NewHeadersChecker(b.HeadersRegex)\n\t\t\tif err != nil {\n\t\t\t\tvalidationErrs = append(validationErrs, fmt.Errorf(\"while processing rule %s headers regex map: %w\", b.Name, err))\n\t\t\t} else {\n\t\t\t\tcl = append(cl, c)\n\t\t\t}\n\t\t}\n\n\t\tif b.Expression != nil {\n\t\t\tc, err := NewCELChecker(b.Expression)\n\t\t\tif err != nil {\n\t\t\t\tvalidationErrs = append(validationErrs, fmt.Errorf(\"while processing rule %s expressions: %w\", b.Name, err))\n\t\t\t} else {\n\t\t\t\tcl = append(cl, c)\n\t\t\t}\n\t\t}\n\n\t\tif b.ASNs != nil {\n\t\t\tif !hasThothClient {\n\t\t\t\tslog.Warn(\"You have specified a Thoth specific check but you have no Thoth client configured. Please read https://anubis.techaro.lol/docs/admin/thoth for more information\", \"check\", \"asn\", \"settings\", b.ASNs)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tcl = append(cl, tc.ASNCheckerFor(b.ASNs.Match))\n\t\t}\n\n\t\tif b.GeoIP != nil {\n\t\t\tif !hasThothClient {\n\t\t\t\tslog.Warn(\"You have specified a Thoth specific check but you have no Thoth client configured. Please read https://anubis.techaro.lol/docs/admin/thoth for more information\", \"check\", \"geoip\", \"settings\", b.GeoIP)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tcl = append(cl, tc.GeoIPCheckerFor(b.GeoIP.Countries))\n\t\t}\n\n\t\tif b.Challenge == nil {\n\t\t\tparsedBot.Challenge = &config.ChallengeRules{\n\t\t\t\tDifficulty: defaultDifficulty,\n\t\t\t\tReportAs: defaultDifficulty,\n\t\t\t\tAlgorithm: \"fast\",\n\t\t\t}\n\t\t} else {\n\t\t\tparsedBot.Challenge = b.Challenge\n\t\t\tif parsedBot.Challenge.Algorithm == \"\" {\n\t\t\t\tparsedBot.Challenge.Algorithm = config.DefaultAlgorithm\n\t\t\t}\n\t\t}\n\n\t\tif b.Weight != nil {\n\t\t\tparsedBot.Weight = b.Weight\n\t\t}\n\n\t\tresult.Impressum = c.Impressum\n\n\t\tparsedBot.Rules = cl\n\n\t\tresult.Bots = append(result.Bots, parsedBot)\n\t}\n\n\tfor _, t := range c.Thresholds {\n\t\tif t.Name == \"legacy-anubis-behaviour\" && t.Expression.String() == \"true\" {\n\t\t\tif !warnedAboutThresholds.Load() {\n\t\t\t\tslog.Warn(\"configuration file does not contain thresholds, see docs for details on how to upgrade\", \"fname\", fname, \"docs_url\", \"https://anubis.techaro.lol/docs/admin/configuration/thresholds/\")\n\t\t\t\twarnedAboutThresholds.Store(true)\n\t\t\t}\n\n\t\t\tt.Challenge.Difficulty = defaultDifficulty\n\t\t\tt.Challenge.ReportAs = defaultDifficulty\n\t\t}\n\n\t\tthreshold, err := ParsedThresholdFromConfig(t)\n\t\tif err != nil {\n\t\t\tvalidationErrs = append(validationErrs, fmt.Errorf(\"can't compile threshold config for %s: %w\", t.Name, err))\n\t\t\tcontinue\n\t\t}\n\n\t\tresult.Thresholds = append(result.Thresholds, threshold)\n\t}\n\n\tstFac, ok := store.Get(c.Store.Backend)\n\tswitch ok {\n\tcase true:\n\t\tstore, err := stFac.Build(ctx, c.Store.Parameters)\n\t\tif err != nil {\n\t\t\tvalidationErrs = append(validationErrs, err)\n\t\t} else {\n\t\t\tresult.Store = store\n\t\t}\n\tcase false:\n\t\tvalidationErrs = append(validationErrs, config.ErrUnknownStoreBackend)\n\t}\n\n\tif len(validationErrs) > 0 {\n\t\treturn nil, fmt.Errorf(\"errors validating policy config JSON %s: %w\", fname, errors.Join(validationErrs...))\n\t}\n\n\tresult.DNSBL = c.DNSBL\n\n\treturn result, nil\n}\n"], ["/anubis/internal/headers.go", "package internal\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/netip\"\n\t\"strings\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/sebest/xff\"\n)\n\n// TODO: move into config\ntype XFFComputePreferences struct {\n\tStripPrivate bool\n\tStripLoopback bool\n\tStripCGNAT bool\n\tStripLLU bool\n\tFlatten bool\n}\n\nvar CGNat = netip.MustParsePrefix(\"100.64.0.0/10\")\n\n// UnchangingCache sets the Cache-Control header to cache a response for 1 year if\n// and only if the application is compiled in \"release\" mode by Docker.\nfunc UnchangingCache(next http.Handler) http.Handler {\n\t//goland:noinspection GoBoolExpressions\n\tif anubis.Version == \"devel\" {\n\t\treturn next\n\t}\n\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Cache-Control\", \"public, max-age=31536000\")\n\t\tnext.ServeHTTP(w, r)\n\t})\n}\n\n// RemoteXRealIP sets the X-Real-Ip header to the request's real IP if\n// the setting is enabled by the user.\nfunc RemoteXRealIP(useRemoteAddress bool, bindNetwork string, next http.Handler) http.Handler {\n\tif !useRemoteAddress {\n\t\tslog.Debug(\"skipping middleware, useRemoteAddress is empty\")\n\t\treturn next\n\t}\n\n\tif bindNetwork == \"unix\" {\n\t\t// For local sockets there is no real remote address but the localhost\n\t\t// address should be sensible.\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tr.Header.Set(\"X-Real-Ip\", \"127.0.0.1\")\n\t\t\tnext.ServeHTTP(w, r)\n\t\t})\n\t}\n\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\thost, _, err := net.SplitHostPort(r.RemoteAddr)\n\t\tif err != nil {\n\t\t\tpanic(err) // this should never happen\n\t\t}\n\t\tr.Header.Set(\"X-Real-Ip\", host)\n\t\tnext.ServeHTTP(w, r)\n\t})\n}\n\n// XForwardedForToXRealIP sets the X-Real-Ip header based on the contents\n// of the X-Forwarded-For header.\nfunc XForwardedForToXRealIP(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif xffHeader := r.Header.Get(\"X-Forwarded-For\"); r.Header.Get(\"X-Real-Ip\") == \"\" && xffHeader != \"\" {\n\t\t\tip := xff.Parse(xffHeader)\n\t\t\tslog.Debug(\"setting x-real-ip\", \"val\", ip)\n\t\t\tr.Header.Set(\"X-Real-Ip\", ip)\n\t\t}\n\n\t\tnext.ServeHTTP(w, r)\n\t})\n}\n\n// XForwardedForUpdate sets or updates the X-Forwarded-For header, adding\n// the known remote address to an existing chain if present\nfunc XForwardedForUpdate(stripPrivate bool, next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tdefer next.ServeHTTP(w, r)\n\n\t\tpref := XFFComputePreferences{\n\t\t\tStripPrivate: stripPrivate,\n\t\t\tStripLoopback: true,\n\t\t\tStripCGNAT: true,\n\t\t\tFlatten: true,\n\t\t\tStripLLU: true,\n\t\t}\n\n\t\tremoteAddr := r.RemoteAddr\n\t\torigXFFHeader := r.Header.Get(\"X-Forwarded-For\")\n\n\t\tif remoteAddr == \"@\" {\n\t\t\t// remote is a unix socket\n\t\t\t// do not touch chain\n\t\t\treturn\n\t\t}\n\n\t\txffHeaderString, err := computeXFFHeader(remoteAddr, origXFFHeader, pref)\n\t\tif err != nil {\n\t\t\tslog.Debug(\"computing X-Forwarded-For header failed\", \"err\", err)\n\t\t\treturn\n\t\t}\n\n\t\tif len(xffHeaderString) == 0 {\n\t\t\tr.Header.Del(\"X-Forwarded-For\")\n\t\t} else {\n\t\t\tr.Header.Set(\"X-Forwarded-For\", xffHeaderString)\n\t\t}\n\t})\n}\n\nvar (\n\tErrCantSplitHostParse = errors.New(\"internal: unable to net.SplitHostParse\")\n\tErrCantParseRemoteIP = errors.New(\"internal: unable to parse remote IP\")\n)\n\nfunc computeXFFHeader(remoteAddr string, origXFFHeader string, pref XFFComputePreferences) (string, error) {\n\tremoteIP, _, err := net.SplitHostPort(remoteAddr)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"%w: %w\", ErrCantSplitHostParse, err)\n\t}\n\tparsedRemoteIP, err := netip.ParseAddr(remoteIP)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"%w: %w\", ErrCantParseRemoteIP, err)\n\t}\n\n\torigForwardedList := make([]string, 0, 4)\n\tif origXFFHeader != \"\" {\n\t\torigForwardedList = strings.Split(origXFFHeader, \",\")\n\t\tfor i := range origForwardedList {\n\t\t\torigForwardedList[i] = strings.TrimSpace(origForwardedList[i])\n\t\t}\n\t}\n\torigForwardedList = append(origForwardedList, parsedRemoteIP.String())\n\tforwardedList := make([]string, 0, len(origForwardedList))\n\t// this behavior is equivalent to\n\t// ingress-nginx \"compute-full-forwarded-for\"\n\t// https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/configmap/#compute-full-forwarded-for\n\t//\n\t// this would be the correct place to strip and/or flatten this list\n\t//\n\t// strip - iterate backwards and eliminate configured trusted IPs\n\t// flatten - only return the last element to avoid spoofing confusion\n\t//\n\t// many applications handle this in different ways, but\n\t// generally they'd be expected to do these two things on\n\t// their own end to find the first non-spoofed IP\n\tfor i := len(origForwardedList) - 1; i >= 0; i-- {\n\t\tsegmentIP, err := netip.ParseAddr(origForwardedList[i])\n\t\tif err != nil {\n\t\t\t// can't assess this element, so the remainder of the chain\n\t\t\t// can't be trusted. not a fatal error, since anyone can\n\t\t\t// spoof an XFF header\n\t\t\tslog.Debug(\"failed to parse XFF segment\", \"err\", err)\n\t\t\tbreak\n\t\t}\n\t\tif pref.StripPrivate && segmentIP.IsPrivate() {\n\t\t\tcontinue\n\t\t}\n\t\tif pref.StripLoopback && segmentIP.IsLoopback() {\n\t\t\tcontinue\n\t\t}\n\t\tif pref.StripLLU && segmentIP.IsLinkLocalUnicast() {\n\t\t\tcontinue\n\t\t}\n\t\tif pref.StripCGNAT && CGNat.Contains(segmentIP) {\n\t\t\tcontinue\n\t\t}\n\t\tforwardedList = append([]string{segmentIP.String()}, forwardedList...)\n\t}\n\tvar xffHeaderString string\n\tif len(forwardedList) == 0 {\n\t\txffHeaderString = \"\"\n\t\treturn xffHeaderString, nil\n\t}\n\tif pref.Flatten {\n\t\txffHeaderString = forwardedList[len(forwardedList)-1]\n\t} else {\n\t\txffHeaderString = strings.Join(forwardedList, \",\")\n\t}\n\treturn xffHeaderString, nil\n}\n\n// NoStoreCache sets the Cache-Control header to no-store for the response.\nfunc NoStoreCache(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Cache-Control\", \"no-store\")\n\t\tnext.ServeHTTP(w, r)\n\t})\n}\n\n// NoBrowsing prevents directory browsing by returning a 404 for any request that ends with a \"/\".\nfunc NoBrowsing(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif strings.HasSuffix(r.URL.Path, \"/\") {\n\t\t\thttp.NotFound(w, r)\n\t\t\treturn\n\t\t}\n\t\tnext.ServeHTTP(w, r)\n\t})\n}\n"], ["/anubis/lib/challenge/metarefresh/metarefresh.go", "package metarefresh\n\nimport (\n\t\"crypto/subtle\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net/http\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/TecharoHQ/anubis/lib/challenge\"\n\t\"github.com/TecharoHQ/anubis/lib/localization\"\n\t\"github.com/TecharoHQ/anubis/web\"\n\t\"github.com/a-h/templ\"\n)\n\n//go:generate go tool github.com/a-h/templ/cmd/templ generate\n\nfunc init() {\n\tchallenge.Register(\"metarefresh\", &Impl{})\n}\n\ntype Impl struct{}\n\nfunc (i *Impl) Setup(mux *http.ServeMux) {}\n\nfunc (i *Impl) Issue(r *http.Request, lg *slog.Logger, in *challenge.IssueInput) (templ.Component, error) {\n\tu, err := r.URL.Parse(anubis.BasePrefix + \"/.within.website/x/cmd/anubis/api/pass-challenge\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't render page: %w\", err)\n\t}\n\n\tq := u.Query()\n\tq.Set(\"redir\", r.URL.String())\n\tq.Set(\"challenge\", in.Challenge.RandomData)\n\tu.RawQuery = q.Encode()\n\n\tloc := localization.GetLocalizer(r)\n\tcomponent, err := web.BaseWithChallengeAndOGTags(loc.T(\"making_sure_not_bot\"), page(u.String(), in.Rule.Challenge.Difficulty, loc), in.Impressum, in.Challenge.RandomData, in.Rule.Challenge, in.OGTags, loc)\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't render page: %w\", err)\n\t}\n\n\treturn component, nil\n}\n\nfunc (i *Impl) Validate(r *http.Request, lg *slog.Logger, in *challenge.ValidateInput) error {\n\tgotChallenge := r.FormValue(\"challenge\")\n\n\tif subtle.ConstantTimeCompare([]byte(in.Challenge.RandomData), []byte(gotChallenge)) != 1 {\n\t\treturn challenge.NewError(\"validate\", \"invalid response\", fmt.Errorf(\"%w: wanted response %s but got %s\", challenge.ErrFailed, in.Challenge.RandomData, gotChallenge))\n\t}\n\n\treturn nil\n}\n"], ["/anubis/lib/policy/config/config.go", "package config\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/fs\"\n\t\"net\"\n\t\"net/http\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis/data\"\n\t\"k8s.io/apimachinery/pkg/util/yaml\"\n)\n\nvar (\n\tErrNoBotRulesDefined = errors.New(\"config: must define at least one (1) bot rule\")\n\tErrBotMustHaveName = errors.New(\"config.Bot: must set name\")\n\tErrBotMustHaveUserAgentOrPath = errors.New(\"config.Bot: must set either user_agent_regex, path_regex, headers_regex, or remote_addresses\")\n\tErrBotMustHaveUserAgentOrPathNotBoth = errors.New(\"config.Bot: must set either user_agent_regex, path_regex, and not both\")\n\tErrUnknownAction = errors.New(\"config.Bot: unknown action\")\n\tErrInvalidUserAgentRegex = errors.New(\"config.Bot: invalid user agent regex\")\n\tErrInvalidPathRegex = errors.New(\"config.Bot: invalid path regex\")\n\tErrInvalidHeadersRegex = errors.New(\"config.Bot: invalid headers regex\")\n\tErrInvalidCIDR = errors.New(\"config.Bot: invalid CIDR\")\n\tErrRegexEndsWithNewline = errors.New(\"config.Bot: regular expression ends with newline (try >- instead of > in yaml)\")\n\tErrInvalidImportStatement = errors.New(\"config.ImportStatement: invalid source file\")\n\tErrCantSetBotAndImportValuesAtOnce = errors.New(\"config.BotOrImport: can't set bot rules and import values at the same time\")\n\tErrMustSetBotOrImportRules = errors.New(\"config.BotOrImport: rule definition is invalid, you must set either bot rules or an import statement, not both\")\n\tErrStatusCodeNotValid = errors.New(\"config.StatusCode: status code not valid, must be between 100 and 599\")\n)\n\ntype Rule string\n\nconst (\n\tRuleUnknown Rule = \"\"\n\tRuleAllow Rule = \"ALLOW\"\n\tRuleDeny Rule = \"DENY\"\n\tRuleChallenge Rule = \"CHALLENGE\"\n\tRuleWeigh Rule = \"WEIGH\"\n\tRuleBenchmark Rule = \"DEBUG_BENCHMARK\"\n)\n\nfunc (r Rule) Valid() error {\n\tswitch r {\n\tcase RuleAllow, RuleDeny, RuleChallenge, RuleWeigh, RuleBenchmark:\n\t\treturn nil\n\tdefault:\n\t\treturn ErrUnknownAction\n\t}\n}\n\nconst DefaultAlgorithm = \"fast\"\n\ntype BotConfig struct {\n\tUserAgentRegex *string `json:\"user_agent_regex,omitempty\" yaml:\"user_agent_regex,omitempty\"`\n\tPathRegex *string `json:\"path_regex,omitempty\" yaml:\"path_regex,omitempty\"`\n\tHeadersRegex map[string]string `json:\"headers_regex,omitempty\" yaml:\"headers_regex,omitempty\"`\n\tExpression *ExpressionOrList `json:\"expression,omitempty\" yaml:\"expression,omitempty\"`\n\tChallenge *ChallengeRules `json:\"challenge,omitempty\" yaml:\"challenge,omitempty\"`\n\tWeight *Weight `json:\"weight,omitempty\" yaml:\"weight,omitempty\"`\n\tName string `json:\"name\" yaml:\"name\"`\n\tAction Rule `json:\"action\" yaml:\"action\"`\n\tRemoteAddr []string `json:\"remote_addresses,omitempty\" yaml:\"remote_addresses,omitempty\"`\n\n\t// Thoth features\n\tGeoIP *GeoIP `json:\"geoip,omitempty\"`\n\tASNs *ASNs `json:\"asns,omitempty\"`\n}\n\nfunc (b BotConfig) Zero() bool {\n\tfor _, cond := range []bool{\n\t\tb.Name != \"\",\n\t\tb.UserAgentRegex != nil,\n\t\tb.PathRegex != nil,\n\t\tlen(b.HeadersRegex) != 0,\n\t\tb.Action != \"\",\n\t\tlen(b.RemoteAddr) != 0,\n\t\tb.Challenge != nil,\n\t\tb.GeoIP != nil,\n\t\tb.ASNs != nil,\n\t} {\n\t\tif cond {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc (b *BotConfig) Valid() error {\n\tvar errs []error\n\n\tif b.Name == \"\" {\n\t\terrs = append(errs, ErrBotMustHaveName)\n\t}\n\n\tallFieldsEmpty := b.UserAgentRegex == nil &&\n\t\tb.PathRegex == nil &&\n\t\tlen(b.RemoteAddr) == 0 &&\n\t\tlen(b.HeadersRegex) == 0 &&\n\t\tb.ASNs == nil &&\n\t\tb.GeoIP == nil\n\n\tif allFieldsEmpty && b.Expression == nil {\n\t\terrs = append(errs, ErrBotMustHaveUserAgentOrPath)\n\t}\n\n\tif b.UserAgentRegex != nil && b.PathRegex != nil {\n\t\terrs = append(errs, ErrBotMustHaveUserAgentOrPathNotBoth)\n\t}\n\n\tif b.UserAgentRegex != nil {\n\t\tif strings.HasSuffix(*b.UserAgentRegex, \"\\n\") {\n\t\t\terrs = append(errs, fmt.Errorf(\"%w: user agent regex: %q\", ErrRegexEndsWithNewline, *b.UserAgentRegex))\n\t\t}\n\n\t\tif _, err := regexp.Compile(*b.UserAgentRegex); err != nil {\n\t\t\terrs = append(errs, ErrInvalidUserAgentRegex, err)\n\t\t}\n\t}\n\n\tif b.PathRegex != nil {\n\t\tif strings.HasSuffix(*b.PathRegex, \"\\n\") {\n\t\t\terrs = append(errs, fmt.Errorf(\"%w: path regex: %q\", ErrRegexEndsWithNewline, *b.PathRegex))\n\t\t}\n\n\t\tif _, err := regexp.Compile(*b.PathRegex); err != nil {\n\t\t\terrs = append(errs, ErrInvalidPathRegex, err)\n\t\t}\n\t}\n\n\tif len(b.HeadersRegex) > 0 {\n\t\tfor name, expr := range b.HeadersRegex {\n\t\t\tif name == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif strings.HasSuffix(expr, \"\\n\") {\n\t\t\t\terrs = append(errs, fmt.Errorf(\"%w: header %s regex: %q\", ErrRegexEndsWithNewline, name, expr))\n\t\t\t}\n\n\t\t\tif _, err := regexp.Compile(expr); err != nil {\n\t\t\t\terrs = append(errs, ErrInvalidHeadersRegex, err)\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(b.RemoteAddr) > 0 {\n\t\tfor _, cidr := range b.RemoteAddr {\n\t\t\tif _, _, err := net.ParseCIDR(cidr); err != nil {\n\t\t\t\terrs = append(errs, ErrInvalidCIDR, err)\n\t\t\t}\n\t\t}\n\t}\n\n\tif b.Expression != nil {\n\t\tif err := b.Expression.Valid(); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\tswitch b.Action {\n\tcase RuleAllow, RuleBenchmark, RuleChallenge, RuleDeny, RuleWeigh:\n\t\t// okay\n\tdefault:\n\t\terrs = append(errs, fmt.Errorf(\"%w: %q\", ErrUnknownAction, b.Action))\n\t}\n\n\tif b.Action == RuleChallenge && b.Challenge != nil {\n\t\tif err := b.Challenge.Valid(); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\tif b.Action == RuleWeigh && b.Weight == nil {\n\t\tb.Weight = &Weight{Adjust: 5}\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"config: bot entry for %q is not valid:\\n%w\", b.Name, errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n\ntype ChallengeRules struct {\n\tAlgorithm string `json:\"algorithm,omitempty\" yaml:\"algorithm,omitempty\"`\n\tDifficulty int `json:\"difficulty,omitempty\" yaml:\"difficulty,omitempty\"`\n\tReportAs int `json:\"report_as,omitempty\" yaml:\"report_as,omitempty\"`\n}\n\nvar (\n\tErrChallengeDifficultyTooLow = errors.New(\"config.ChallengeRules: difficulty is too low (must be >= 1)\")\n\tErrChallengeDifficultyTooHigh = errors.New(\"config.ChallengeRules: difficulty is too high (must be <= 64)\")\n\tErrChallengeMustHaveAlgorithm = errors.New(\"config.ChallengeRules: must have algorithm name set\")\n)\n\nfunc (cr ChallengeRules) Valid() error {\n\tvar errs []error\n\n\tif cr.Algorithm == \"\" {\n\t\terrs = append(errs, ErrChallengeMustHaveAlgorithm)\n\t}\n\n\tif cr.Difficulty < 1 {\n\t\terrs = append(errs, fmt.Errorf(\"%w, got: %d\", ErrChallengeDifficultyTooLow, cr.Difficulty))\n\t}\n\n\tif cr.Difficulty > 64 {\n\t\terrs = append(errs, fmt.Errorf(\"%w, got: %d\", ErrChallengeDifficultyTooHigh, cr.Difficulty))\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"config: challenge rules entry is not valid:\\n%w\", errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n\ntype ImportStatement struct {\n\tImport string `json:\"import\"`\n\tBots []BotConfig\n}\n\nfunc (is *ImportStatement) open() (fs.File, error) {\n\tif strings.HasPrefix(is.Import, \"(data)/\") {\n\t\tfname := strings.TrimPrefix(is.Import, \"(data)/\")\n\t\tfin, err := data.BotPolicies.Open(fname)\n\t\treturn fin, err\n\t}\n\n\treturn os.Open(is.Import)\n}\n\nfunc (is *ImportStatement) load() error {\n\tfin, err := is.open()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%w: %s: %w\", ErrInvalidImportStatement, is.Import, err)\n\t}\n\tdefer fin.Close()\n\n\tvar imported []BotOrImport\n\tvar result []BotConfig\n\n\tif err := yaml.NewYAMLToJSONDecoder(fin).Decode(&imported); err != nil {\n\t\treturn fmt.Errorf(\"can't parse %s: %w\", is.Import, err)\n\t}\n\n\tvar errs []error\n\n\tfor _, b := range imported {\n\t\tif err := b.Valid(); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\n\t\tif b.ImportStatement != nil {\n\t\t\tresult = append(result, b.ImportStatement.Bots...)\n\t\t}\n\n\t\tif b.BotConfig != nil {\n\t\t\tresult = append(result, *b.BotConfig)\n\t\t}\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"config %s is not valid:\\n%w\", is.Import, errors.Join(errs...))\n\t}\n\n\tis.Bots = result\n\n\treturn nil\n}\n\nfunc (is *ImportStatement) Valid() error {\n\treturn is.load()\n}\n\ntype BotOrImport struct {\n\t*BotConfig `json:\",inline\"`\n\t*ImportStatement `json:\",inline\"`\n}\n\nfunc (boi *BotOrImport) Valid() error {\n\tif boi.BotConfig != nil && boi.ImportStatement != nil {\n\t\treturn ErrCantSetBotAndImportValuesAtOnce\n\t}\n\n\tif boi.BotConfig != nil {\n\t\treturn boi.BotConfig.Valid()\n\t}\n\n\tif boi.ImportStatement != nil {\n\t\treturn boi.ImportStatement.Valid()\n\t}\n\n\treturn ErrMustSetBotOrImportRules\n}\n\ntype StatusCodes struct {\n\tChallenge int `json:\"CHALLENGE\"`\n\tDeny int `json:\"DENY\"`\n}\n\nfunc (sc StatusCodes) Valid() error {\n\tvar errs []error\n\n\tif sc.Challenge == 0 || (sc.Challenge < 100 && sc.Challenge >= 599) {\n\t\terrs = append(errs, fmt.Errorf(\"%w: challenge is %d\", ErrStatusCodeNotValid, sc.Challenge))\n\t}\n\n\tif sc.Deny == 0 || (sc.Deny < 100 && sc.Deny >= 599) {\n\t\terrs = append(errs, fmt.Errorf(\"%w: deny is %d\", ErrStatusCodeNotValid, sc.Deny))\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"status codes not valid:\\n%w\", errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n\ntype fileConfig struct {\n\tBots []BotOrImport `json:\"bots\"`\n\tDNSBL bool `json:\"dnsbl\"`\n\tOpenGraph openGraphFileConfig `json:\"openGraph,omitempty\"`\n\tImpressum *Impressum `json:\"impressum,omitempty\"`\n\tStatusCodes StatusCodes `json:\"status_codes\"`\n\tStore *Store `json:\"store\"`\n\tThresholds []Threshold `json:\"thresholds\"`\n}\n\nfunc (c *fileConfig) Valid() error {\n\tvar errs []error\n\n\tif len(c.Bots) == 0 {\n\t\terrs = append(errs, ErrNoBotRulesDefined)\n\t}\n\n\tfor i, b := range c.Bots {\n\t\tif err := b.Valid(); err != nil {\n\t\t\terrs = append(errs, fmt.Errorf(\"bot %d: %w\", i, err))\n\t\t}\n\t}\n\n\tif c.OpenGraph.Enabled {\n\t\tif err := c.OpenGraph.Valid(); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\tif err := c.StatusCodes.Valid(); err != nil {\n\t\terrs = append(errs, err)\n\t}\n\n\tfor i, t := range c.Thresholds {\n\t\tif err := t.Valid(); err != nil {\n\t\t\terrs = append(errs, fmt.Errorf(\"threshold %d: %w\", i, err))\n\t\t}\n\t}\n\n\tif c.Store != nil {\n\t\tif err := c.Store.Valid(); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"config is not valid:\\n%w\", errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n\nfunc Load(fin io.Reader, fname string) (*Config, error) {\n\tc := &fileConfig{\n\t\tStatusCodes: StatusCodes{\n\t\t\tChallenge: http.StatusOK,\n\t\t\tDeny: http.StatusOK,\n\t\t},\n\t\tStore: &Store{\n\t\t\tBackend: \"memory\",\n\t\t},\n\t}\n\n\tif err := yaml.NewYAMLToJSONDecoder(fin).Decode(&c); err != nil {\n\t\treturn nil, fmt.Errorf(\"can't parse policy config YAML %s: %w\", fname, err)\n\t}\n\n\tif err := c.Valid(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult := &Config{\n\t\tDNSBL: c.DNSBL,\n\t\tOpenGraph: OpenGraph{\n\t\t\tEnabled: c.OpenGraph.Enabled,\n\t\t\tConsiderHost: c.OpenGraph.ConsiderHost,\n\t\t\tOverride: c.OpenGraph.Override,\n\t\t},\n\t\tStatusCodes: c.StatusCodes,\n\t\tStore: c.Store,\n\t}\n\n\tif c.OpenGraph.TimeToLive != \"\" {\n\t\t// XXX(Xe): already validated in Valid()\n\t\togTTL, _ := time.ParseDuration(c.OpenGraph.TimeToLive)\n\t\tresult.OpenGraph.TimeToLive = ogTTL\n\t}\n\n\tvar validationErrs []error\n\n\tfor _, boi := range c.Bots {\n\t\tif boi.ImportStatement != nil {\n\t\t\tif err := boi.load(); err != nil {\n\t\t\t\tvalidationErrs = append(validationErrs, err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tresult.Bots = append(result.Bots, boi.ImportStatement.Bots...)\n\t\t}\n\n\t\tif boi.BotConfig != nil {\n\t\t\tif err := boi.BotConfig.Valid(); err != nil {\n\t\t\t\tvalidationErrs = append(validationErrs, err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tresult.Bots = append(result.Bots, *boi.BotConfig)\n\t\t}\n\t}\n\n\tif c.Impressum != nil {\n\t\tif err := c.Impressum.Valid(); err != nil {\n\t\t\tvalidationErrs = append(validationErrs, err)\n\t\t}\n\n\t\tresult.Impressum = c.Impressum\n\t}\n\n\tif len(c.Thresholds) == 0 {\n\t\tc.Thresholds = DefaultThresholds\n\t}\n\n\tfor _, t := range c.Thresholds {\n\t\tif err := t.Valid(); err != nil {\n\t\t\tvalidationErrs = append(validationErrs, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tresult.Thresholds = append(result.Thresholds, t)\n\t}\n\n\tif len(validationErrs) > 0 {\n\t\treturn nil, fmt.Errorf(\"errors validating policy config %s: %w\", fname, errors.Join(validationErrs...))\n\t}\n\n\treturn result, nil\n}\n\ntype Config struct {\n\tBots []BotConfig\n\tThresholds []Threshold\n\tDNSBL bool\n\tImpressum *Impressum\n\tOpenGraph OpenGraph\n\tStatusCodes StatusCodes\n\tStore *Store\n}\n\nfunc (c Config) Valid() error {\n\tvar errs []error\n\n\tif len(c.Bots) == 0 {\n\t\terrs = append(errs, ErrNoBotRulesDefined)\n\t}\n\n\tfor _, b := range c.Bots {\n\t\tif err := b.Valid(); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"config is not valid:\\n%w\", errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n"], ["/anubis/cmd/robots2policy/main.go", "package main\n\nimport (\n\t\"bufio\"\n\t\"encoding/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\n\t\"sigs.k8s.io/yaml\"\n)\n\nvar (\n\tinputFile = flag.String(\"input\", \"\", \"path to robots.txt file (use - for stdin)\")\n\toutputFile = flag.String(\"output\", \"\", \"output file path (use - for stdout, defaults to stdout)\")\n\toutputFormat = flag.String(\"format\", \"yaml\", \"output format: yaml or json\")\n\tbaseAction = flag.String(\"action\", \"CHALLENGE\", \"default action for disallowed paths: ALLOW, DENY, CHALLENGE, WEIGH\")\n\tcrawlDelay = flag.Int(\"crawl-delay-weight\", 0, \"if > 0, add weight adjustment for crawl-delay (difficulty adjustment)\")\n\tpolicyName = flag.String(\"name\", \"robots-txt-policy\", \"name for the generated policy\")\n\tuserAgentDeny = flag.String(\"deny-user-agents\", \"DENY\", \"action for specifically blocked user agents: DENY, CHALLENGE\")\n\thelpFlag = flag.Bool(\"help\", false, \"show help\")\n)\n\ntype RobotsRule struct {\n\tUserAgent string\n\tDisallows []string\n\tAllows []string\n\tCrawlDelay int\n\tIsBlacklist bool // true if this is a specifically denied user agent\n}\n\ntype AnubisRule struct {\n\tExpression *config.ExpressionOrList `yaml:\"expression,omitempty\" json:\"expression,omitempty\"`\n\tChallenge *config.ChallengeRules `yaml:\"challenge,omitempty\" json:\"challenge,omitempty\"`\n\tWeight *config.Weight `yaml:\"weight,omitempty\" json:\"weight,omitempty\"`\n\tName string `yaml:\"name\" json:\"name\"`\n\tAction string `yaml:\"action\" json:\"action\"`\n}\n\nfunc init() {\n\tflag.Usage = func() {\n\t\tfmt.Fprintf(os.Stderr, \"Usage of %s:\\n\", os.Args[0])\n\t\tfmt.Fprintf(os.Stderr, \"%s [options] -input \\n\\n\", os.Args[0])\n\t\tflag.PrintDefaults()\n\t\tfmt.Fprintln(os.Stderr, \"\\nExamples:\")\n\t\tfmt.Fprintln(os.Stderr, \" # Convert local robots.txt file\")\n\t\tfmt.Fprintln(os.Stderr, \" robots2policy -input robots.txt -output policy.yaml\")\n\t\tfmt.Fprintln(os.Stderr, \"\")\n\t\tfmt.Fprintln(os.Stderr, \" # Convert from URL\")\n\t\tfmt.Fprintln(os.Stderr, \" robots2policy -input https://example.com/robots.txt -format json\")\n\t\tfmt.Fprintln(os.Stderr, \"\")\n\t\tfmt.Fprintln(os.Stderr, \" # Read from stdin, write to stdout\")\n\t\tfmt.Fprintln(os.Stderr, \" curl https://example.com/robots.txt | robots2policy -input -\")\n\t\tos.Exit(2)\n\t}\n}\n\nfunc main() {\n\tflag.Parse()\n\n\tif len(flag.Args()) > 0 || *helpFlag || *inputFile == \"\" {\n\t\tflag.Usage()\n\t}\n\n\t// Read robots.txt\n\tvar input io.Reader\n\tif *inputFile == \"-\" {\n\t\tinput = os.Stdin\n\t} else if strings.HasPrefix(*inputFile, \"http://\") || strings.HasPrefix(*inputFile, \"https://\") {\n\t\tresp, err := http.Get(*inputFile)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to fetch robots.txt from URL: %v\", err)\n\t\t}\n\t\tdefer resp.Body.Close()\n\t\tinput = resp.Body\n\t} else {\n\t\tfile, err := os.Open(*inputFile)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to open input file: %v\", err)\n\t\t}\n\t\tdefer file.Close()\n\t\tinput = file\n\t}\n\n\t// Parse robots.txt\n\trules, err := parseRobotsTxt(input)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to parse robots.txt: %v\", err)\n\t}\n\n\t// Convert to Anubis rules\n\tanubisRules := convertToAnubisRules(rules)\n\n\t// Check if any rules were generated\n\tif len(anubisRules) == 0 {\n\t\tlog.Fatal(\"no valid rules generated from robots.txt - file may be empty or contain no disallow directives\")\n\t}\n\n\t// Generate output\n\tvar output []byte\n\tswitch strings.ToLower(*outputFormat) {\n\tcase \"yaml\":\n\t\toutput, err = yaml.Marshal(anubisRules)\n\tcase \"json\":\n\t\toutput, err = json.MarshalIndent(anubisRules, \"\", \" \")\n\tdefault:\n\t\tlog.Fatalf(\"unsupported output format: %s (use yaml or json)\", *outputFormat)\n\t}\n\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to marshal output: %v\", err)\n\t}\n\n\t// Write output\n\tif *outputFile == \"\" || *outputFile == \"-\" {\n\t\tfmt.Print(string(output))\n\t} else {\n\t\terr = os.WriteFile(*outputFile, output, 0644)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to write output file: %v\", err)\n\t\t}\n\t\tfmt.Printf(\"Generated Anubis policy written to %s\\n\", *outputFile)\n\t}\n}\n\nfunc parseRobotsTxt(input io.Reader) ([]RobotsRule, error) {\n\tscanner := bufio.NewScanner(input)\n\tvar rules []RobotsRule\n\tvar currentRule *RobotsRule\n\n\tfor scanner.Scan() {\n\t\tline := strings.TrimSpace(scanner.Text())\n\n\t\t// Skip empty lines and comments\n\t\tif line == \"\" || strings.HasPrefix(line, \"#\") {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Split on first colon\n\t\tparts := strings.SplitN(line, \":\", 2)\n\t\tif len(parts) != 2 {\n\t\t\tcontinue\n\t\t}\n\n\t\tdirective := strings.TrimSpace(strings.ToLower(parts[0]))\n\t\tvalue := strings.TrimSpace(parts[1])\n\n\t\tswitch directive {\n\t\tcase \"user-agent\":\n\t\t\t// Start a new rule section\n\t\t\tif currentRule != nil {\n\t\t\t\trules = append(rules, *currentRule)\n\t\t\t}\n\t\t\tcurrentRule = &RobotsRule{\n\t\t\t\tUserAgent: value,\n\t\t\t\tDisallows: make([]string, 0),\n\t\t\t\tAllows: make([]string, 0),\n\t\t\t}\n\n\t\tcase \"disallow\":\n\t\t\tif currentRule != nil && value != \"\" {\n\t\t\t\tcurrentRule.Disallows = append(currentRule.Disallows, value)\n\t\t\t}\n\n\t\tcase \"allow\":\n\t\t\tif currentRule != nil && value != \"\" {\n\t\t\t\tcurrentRule.Allows = append(currentRule.Allows, value)\n\t\t\t}\n\n\t\tcase \"crawl-delay\":\n\t\t\tif currentRule != nil {\n\t\t\t\tif delay, err := parseIntSafe(value); err == nil {\n\t\t\t\t\tcurrentRule.CrawlDelay = delay\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Don't forget the last rule\n\tif currentRule != nil {\n\t\trules = append(rules, *currentRule)\n\t}\n\n\t// Mark blacklisted user agents (those with \"Disallow: /\")\n\tfor i := range rules {\n\t\tfor _, disallow := range rules[i].Disallows {\n\t\t\tif disallow == \"/\" {\n\t\t\t\trules[i].IsBlacklist = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn rules, scanner.Err()\n}\n\nfunc parseIntSafe(s string) (int, error) {\n\tvar result int\n\t_, err := fmt.Sscanf(s, \"%d\", &result)\n\treturn result, err\n}\n\nfunc convertToAnubisRules(robotsRules []RobotsRule) []AnubisRule {\n\tvar anubisRules []AnubisRule\n\truleCounter := 0\n\n\tfor _, robotsRule := range robotsRules {\n\t\tuserAgent := robotsRule.UserAgent\n\n\t\t// Handle crawl delay as weight adjustment (do this first before any continues)\n\t\tif robotsRule.CrawlDelay > 0 && *crawlDelay > 0 {\n\t\t\truleCounter++\n\t\t\trule := AnubisRule{\n\t\t\t\tName: fmt.Sprintf(\"%s-crawl-delay-%d\", *policyName, ruleCounter),\n\t\t\t\tAction: \"WEIGH\",\n\t\t\t\tWeight: &config.Weight{Adjust: *crawlDelay},\n\t\t\t}\n\n\t\t\tif userAgent == \"*\" {\n\t\t\t\trule.Expression = &config.ExpressionOrList{\n\t\t\t\t\tAll: []string{\"true\"}, // Always applies\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\trule.Expression = &config.ExpressionOrList{\n\t\t\t\t\tAll: []string{fmt.Sprintf(\"userAgent.contains(%q)\", userAgent)},\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tanubisRules = append(anubisRules, rule)\n\t\t}\n\n\t\t// Handle blacklisted user agents (complete deny/challenge)\n\t\tif robotsRule.IsBlacklist {\n\t\t\truleCounter++\n\t\t\trule := AnubisRule{\n\t\t\t\tName: fmt.Sprintf(\"%s-blacklist-%d\", *policyName, ruleCounter),\n\t\t\t\tAction: *userAgentDeny,\n\t\t\t}\n\n\t\t\tif userAgent == \"*\" {\n\t\t\t\t// This would block everything - convert to a weight adjustment instead\n\t\t\t\trule.Name = fmt.Sprintf(\"%s-global-restriction-%d\", *policyName, ruleCounter)\n\t\t\t\trule.Action = \"WEIGH\"\n\t\t\t\trule.Weight = &config.Weight{Adjust: 20} // Increase difficulty significantly\n\t\t\t\trule.Expression = &config.ExpressionOrList{\n\t\t\t\t\tAll: []string{\"true\"}, // Always applies\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\trule.Expression = &config.ExpressionOrList{\n\t\t\t\t\tAll: []string{fmt.Sprintf(\"userAgent.contains(%q)\", userAgent)},\n\t\t\t\t}\n\t\t\t}\n\t\t\tanubisRules = append(anubisRules, rule)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Handle specific disallow rules\n\t\tfor _, disallow := range robotsRule.Disallows {\n\t\t\tif disallow == \"/\" {\n\t\t\t\tcontinue // Already handled as blacklist above\n\t\t\t}\n\n\t\t\truleCounter++\n\t\t\trule := AnubisRule{\n\t\t\t\tName: fmt.Sprintf(\"%s-disallow-%d\", *policyName, ruleCounter),\n\t\t\t\tAction: *baseAction,\n\t\t\t}\n\n\t\t\t// Build CEL expression\n\t\t\tvar conditions []string\n\n\t\t\t// Add user agent condition if not wildcard\n\t\t\tif userAgent != \"*\" {\n\t\t\t\tconditions = append(conditions, fmt.Sprintf(\"userAgent.contains(%q)\", userAgent))\n\t\t\t}\n\n\t\t\t// Add path condition\n\t\t\tpathCondition := buildPathCondition(disallow)\n\t\t\tconditions = append(conditions, pathCondition)\n\n\t\t\trule.Expression = &config.ExpressionOrList{\n\t\t\t\tAll: conditions,\n\t\t\t}\n\n\t\t\tanubisRules = append(anubisRules, rule)\n\t\t}\n\n\t}\n\n\treturn anubisRules\n}\n\nfunc buildPathCondition(robotsPath string) string {\n\t// Handle wildcards in robots.txt paths\n\tif strings.Contains(robotsPath, \"*\") || strings.Contains(robotsPath, \"?\") {\n\t\t// Convert robots.txt wildcards to regex\n\t\tregex := regexp.QuoteMeta(robotsPath)\n\t\tregex = strings.ReplaceAll(regex, `\\*`, `.*`) // * becomes .*\n\t\tregex = strings.ReplaceAll(regex, `\\?`, `.`) // ? becomes .\n\t\tregex = \"^\" + regex\n\t\treturn fmt.Sprintf(\"path.matches(%q)\", regex)\n\t}\n\n\t// Simple prefix match for most cases\n\treturn fmt.Sprintf(\"path.startsWith(%q)\", robotsPath)\n}\n"], ["/anubis/lib/thoth/geoipchecker.go", "package thoth\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net/http\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis/lib/policy/checker\"\n\tiptoasnv1 \"github.com/TecharoHQ/thoth-proto/gen/techaro/thoth/iptoasn/v1\"\n)\n\nfunc (c *Client) GeoIPCheckerFor(countries []string) checker.Impl {\n\tcountryMap := map[string]struct{}{}\n\tvar sb strings.Builder\n\tfmt.Fprintln(&sb, \"GeoIPChecker\")\n\tfor _, cc := range countries {\n\t\tcountryMap[cc] = struct{}{}\n\t\tfmt.Fprintln(&sb, cc)\n\t}\n\n\treturn &GeoIPChecker{\n\t\tIPToASN: c.IPToASN,\n\t\tCountries: countryMap,\n\t\thash: sb.String(),\n\t}\n}\n\ntype GeoIPChecker struct {\n\tIPToASN iptoasnv1.IpToASNServiceClient\n\tCountries map[string]struct{}\n\thash string\n}\n\nfunc (gipc *GeoIPChecker) Check(r *http.Request) (bool, error) {\n\tctx, cancel := context.WithTimeout(r.Context(), 500*time.Millisecond)\n\tdefer cancel()\n\n\tipInfo, err := gipc.IPToASN.Lookup(ctx, &iptoasnv1.LookupRequest{\n\t\tIpAddress: r.Header.Get(\"X-Real-Ip\"),\n\t})\n\tif err != nil {\n\t\tswitch {\n\t\tcase errors.Is(err, context.DeadlineExceeded):\n\t\t\tslog.Debug(\"error contacting thoth\", \"err\", err, \"actionable\", false)\n\t\t\treturn false, nil\n\t\tdefault:\n\t\t\tslog.Error(\"error contacting thoth, please contact support\", \"err\", err, \"actionable\", true)\n\t\t\treturn false, nil\n\t\t}\n\t}\n\n\t// If IP is not publicly announced, return false\n\tif !ipInfo.GetAnnounced() {\n\t\treturn false, nil\n\t}\n\n\t_, ok := gipc.Countries[strings.ToLower(ipInfo.GetCountryCode())]\n\n\treturn ok, nil\n}\n\nfunc (gipc *GeoIPChecker) Hash() string {\n\treturn gipc.hash\n}\n"], ["/anubis/internal/ogtags/ogtags.go", "package ogtags\n\nimport (\n\t\"context\"\n\t\"log/slog\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n)\n\nconst (\n\tmaxContentLength = 8 << 20 // 8 MiB is enough for anyone\n\thttpTimeout = 5 * time.Second /*todo: make this configurable?*/\n\n\tschemeSeparatorLength = 3 // Length of \"://\"\n\tquerySeparatorLength = 1 // Length of \"?\" for query strings\n)\n\ntype OGTagCache struct {\n\tcache store.JSON[map[string]string]\n\ttargetURL *url.URL\n\tclient *http.Client\n\n\t// Pre-built strings for optimization\n\tunixPrefix string // \"http://unix\"\n\tapprovedTags []string\n\tapprovedPrefixes []string\n\togTimeToLive time.Duration\n\togCacheConsiderHost bool\n\togPassthrough bool\n\togOverride map[string]string\n}\n\nfunc NewOGTagCache(target string, conf config.OpenGraph, backend store.Interface) *OGTagCache {\n\t// Predefined approved tags and prefixes\n\tdefaultApprovedTags := []string{\"description\", \"keywords\", \"author\"}\n\tdefaultApprovedPrefixes := []string{\"og:\", \"twitter:\", \"fediverse:\"}\n\n\tvar parsedTargetURL *url.URL\n\tvar err error\n\n\tif target == \"\" {\n\t\t// Default to localhost if target is empty\n\t\tparsedTargetURL, _ = url.Parse(\"http://localhost\")\n\t} else {\n\t\tparsedTargetURL, err = url.Parse(target)\n\t\tif err != nil {\n\t\t\tslog.Debug(\"og: failed to parse target URL, treating as non-unix\", \"target\", target, \"error\", err)\n\t\t\t// If parsing fails, treat it as a non-unix target for backward compatibility or default behavior\n\t\t\t// For now, assume it's not a scheme issue but maybe an invalid char, etc.\n\t\t\t// A simple string target might be intended if it's not a full URL.\n\t\t\tparsedTargetURL = &url.URL{Scheme: \"http\", Host: target} // Assume http if scheme missing and host-like\n\t\t\tif !strings.Contains(target, \"://\") && !strings.HasPrefix(target, \"unix:\") {\n\t\t\t\t// If it looks like just a host/host:port (and not unix), prepend http:// (todo: is this bad...? Trace path to see if i can yell at user to do it right)\n\t\t\t\tparsedTargetURL, _ = url.Parse(\"http://\" + target) // fetch cares about scheme but anubis doesn't\n\t\t\t}\n\t\t}\n\t}\n\n\tclient := &http.Client{\n\t\tTimeout: httpTimeout,\n\t}\n\n\t// Configure custom transport for Unix sockets\n\tif parsedTargetURL.Scheme == \"unix\" {\n\t\tsocketPath := parsedTargetURL.Path // For unix scheme, path is the socket path\n\t\tclient.Transport = &http.Transport{\n\t\t\tDialContext: func(_ context.Context, _, _ string) (net.Conn, error) {\n\t\t\t\treturn net.Dial(\"unix\", socketPath)\n\t\t\t},\n\t\t}\n\t}\n\n\treturn &OGTagCache{\n\t\tcache: store.JSON[map[string]string]{\n\t\t\tUnderlying: backend,\n\t\t\tPrefix: \"ogtags:\",\n\t\t},\n\t\ttargetURL: parsedTargetURL,\n\t\togPassthrough: conf.Enabled,\n\t\togTimeToLive: conf.TimeToLive,\n\t\togCacheConsiderHost: conf.ConsiderHost,\n\t\togOverride: conf.Override,\n\t\tapprovedTags: defaultApprovedTags,\n\t\tapprovedPrefixes: defaultApprovedPrefixes,\n\t\tclient: client,\n\t\tunixPrefix: \"http://unix\",\n\t}\n}\n\n// getTarget constructs the target URL string for fetching OG tags.\n// Optimized to minimize allocations by building strings directly.\nfunc (c *OGTagCache) getTarget(u *url.URL) string {\n\tvar escapedPath = u.EscapedPath() // will cause an allocation if path contains special characters\n\tif c.targetURL.Scheme == \"unix\" {\n\t\t// Build URL string directly without creating intermediate URL object\n\t\tvar sb strings.Builder\n\t\tsb.Grow(len(c.unixPrefix) + len(escapedPath) + len(u.RawQuery) + querySeparatorLength) // Pre-allocate\n\t\tsb.WriteString(c.unixPrefix)\n\t\tsb.WriteString(escapedPath)\n\t\tif u.RawQuery != \"\" {\n\t\t\tsb.WriteByte('?')\n\t\t\tsb.WriteString(u.RawQuery)\n\t\t}\n\t\treturn sb.String()\n\t}\n\n\t// For regular http/https targets, build URL string directly\n\tvar sb strings.Builder\n\t// Pre-calculate size: scheme + \"://\" + host + path + \"?\" + query\n\testimatedSize := len(c.targetURL.Scheme) + schemeSeparatorLength + len(c.targetURL.Host) + len(escapedPath) + len(u.RawQuery) + querySeparatorLength\n\tsb.Grow(estimatedSize)\n\n\tsb.WriteString(c.targetURL.Scheme)\n\tsb.WriteString(\"://\")\n\tsb.WriteString(c.targetURL.Host)\n\tsb.WriteString(escapedPath)\n\tif u.RawQuery != \"\" {\n\t\tsb.WriteByte('?')\n\t\tsb.WriteString(u.RawQuery)\n\t}\n\n\treturn sb.String()\n}\n"], ["/anubis/lib/thoth/asnchecker.go", "package thoth\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net/http\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis/internal\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/checker\"\n\tiptoasnv1 \"github.com/TecharoHQ/thoth-proto/gen/techaro/thoth/iptoasn/v1\"\n)\n\nfunc (c *Client) ASNCheckerFor(asns []uint32) checker.Impl {\n\tasnMap := map[uint32]struct{}{}\n\tvar sb strings.Builder\n\tfmt.Fprintln(&sb, \"ASNChecker\")\n\tfor _, asn := range asns {\n\t\tasnMap[asn] = struct{}{}\n\t\tfmt.Fprintln(&sb, \"AS\", asn)\n\t}\n\n\treturn &ASNChecker{\n\t\tiptoasn: c.IPToASN,\n\t\tasns: asnMap,\n\t\thash: internal.FastHash(sb.String()),\n\t}\n}\n\ntype ASNChecker struct {\n\tiptoasn iptoasnv1.IpToASNServiceClient\n\tasns map[uint32]struct{}\n\thash string\n}\n\nfunc (asnc *ASNChecker) Check(r *http.Request) (bool, error) {\n\tctx, cancel := context.WithTimeout(r.Context(), 500*time.Millisecond)\n\tdefer cancel()\n\n\tipInfo, err := asnc.iptoasn.Lookup(ctx, &iptoasnv1.LookupRequest{\n\t\tIpAddress: r.Header.Get(\"X-Real-Ip\"),\n\t})\n\tif err != nil {\n\t\tswitch {\n\t\tcase errors.Is(err, context.DeadlineExceeded):\n\t\t\tslog.Debug(\"error contacting thoth\", \"err\", err, \"actionable\", false)\n\t\t\treturn false, nil\n\t\tdefault:\n\t\t\tslog.Error(\"error contacting thoth, please contact support\", \"err\", err, \"actionable\", true)\n\t\t\treturn false, nil\n\t\t}\n\t}\n\n\t// If IP is not publicly announced, return false\n\tif !ipInfo.GetAnnounced() {\n\t\treturn false, nil\n\t}\n\n\t_, ok := asnc.asns[uint32(ipInfo.GetAsNumber())]\n\n\treturn ok, nil\n}\n\nfunc (asnc *ASNChecker) Hash() string {\n\treturn asnc.hash\n}\n"], ["/anubis/lib/policy/checker.go", "package policy\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/netip\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com/TecharoHQ/anubis/internal\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/checker\"\n\t\"github.com/gaissmai/bart\"\n)\n\nvar (\n\tErrMisconfiguration = errors.New(\"[unexpected] policy: administrator misconfiguration\")\n)\n\ntype RemoteAddrChecker struct {\n\tprefixTable *bart.Lite\n\thash string\n}\n\nfunc NewRemoteAddrChecker(cidrs []string) (checker.Impl, error) {\n\ttable := new(bart.Lite)\n\n\tfor _, cidr := range cidrs {\n\t\tprefix, err := netip.ParsePrefix(cidr)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"%w: range %s not parsing: %w\", ErrMisconfiguration, cidr, err)\n\t\t}\n\n\t\ttable.Insert(prefix)\n\t}\n\n\treturn &RemoteAddrChecker{\n\t\tprefixTable: table,\n\t\thash: internal.FastHash(strings.Join(cidrs, \",\")),\n\t}, nil\n}\n\nfunc (rac *RemoteAddrChecker) Check(r *http.Request) (bool, error) {\n\thost := r.Header.Get(\"X-Real-Ip\")\n\tif host == \"\" {\n\t\treturn false, fmt.Errorf(\"%w: header X-Real-Ip is not set\", ErrMisconfiguration)\n\t}\n\n\taddr, err := netip.ParseAddr(host)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"%w: %s is not an IP address: %w\", ErrMisconfiguration, host, err)\n\t}\n\n\treturn rac.prefixTable.Contains(addr), nil\n}\n\nfunc (rac *RemoteAddrChecker) Hash() string {\n\treturn rac.hash\n}\n\ntype HeaderMatchesChecker struct {\n\theader string\n\tregexp *regexp.Regexp\n\thash string\n}\n\nfunc NewUserAgentChecker(rexStr string) (checker.Impl, error) {\n\treturn NewHeaderMatchesChecker(\"User-Agent\", rexStr)\n}\n\nfunc NewHeaderMatchesChecker(header, rexStr string) (checker.Impl, error) {\n\trex, err := regexp.Compile(strings.TrimSpace(rexStr))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: regex %s failed parse: %w\", ErrMisconfiguration, rexStr, err)\n\t}\n\treturn &HeaderMatchesChecker{strings.TrimSpace(header), rex, internal.FastHash(header + \": \" + rexStr)}, nil\n}\n\nfunc (hmc *HeaderMatchesChecker) Check(r *http.Request) (bool, error) {\n\tif hmc.regexp.MatchString(r.Header.Get(hmc.header)) {\n\t\treturn true, nil\n\t}\n\n\treturn false, nil\n}\n\nfunc (hmc *HeaderMatchesChecker) Hash() string {\n\treturn hmc.hash\n}\n\ntype PathChecker struct {\n\tregexp *regexp.Regexp\n\thash string\n}\n\nfunc NewPathChecker(rexStr string) (checker.Impl, error) {\n\trex, err := regexp.Compile(strings.TrimSpace(rexStr))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: regex %s failed parse: %w\", ErrMisconfiguration, rexStr, err)\n\t}\n\treturn &PathChecker{rex, internal.FastHash(rexStr)}, nil\n}\n\nfunc (pc *PathChecker) Check(r *http.Request) (bool, error) {\n\tif pc.regexp.MatchString(r.URL.Path) {\n\t\treturn true, nil\n\t}\n\n\treturn false, nil\n}\n\nfunc (pc *PathChecker) Hash() string {\n\treturn pc.hash\n}\n\nfunc NewHeaderExistsChecker(key string) checker.Impl {\n\treturn headerExistsChecker{strings.TrimSpace(key)}\n}\n\ntype headerExistsChecker struct {\n\theader string\n}\n\nfunc (hec headerExistsChecker) Check(r *http.Request) (bool, error) {\n\tif r.Header.Get(hec.header) != \"\" {\n\t\treturn true, nil\n\t}\n\n\treturn false, nil\n}\n\nfunc (hec headerExistsChecker) Hash() string {\n\treturn internal.FastHash(hec.header)\n}\n\nfunc NewHeadersChecker(headermap map[string]string) (checker.Impl, error) {\n\tvar result checker.List\n\tvar errs []error\n\n\tfor key, rexStr := range headermap {\n\t\tif rexStr == \".*\" {\n\t\t\tresult = append(result, headerExistsChecker{strings.TrimSpace(key)})\n\t\t\tcontinue\n\t\t}\n\n\t\trex, err := regexp.Compile(strings.TrimSpace(rexStr))\n\t\tif err != nil {\n\t\t\terrs = append(errs, fmt.Errorf(\"while compiling header %s regex %s: %w\", key, rexStr, err))\n\t\t\tcontinue\n\t\t}\n\n\t\tresult = append(result, &HeaderMatchesChecker{key, rex, internal.FastHash(key + \": \" + rexStr)})\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn nil, errors.Join(errs...)\n\t}\n\n\treturn result, nil\n}\n"], ["/anubis/internal/ogtags/fetch.go", "package ogtags\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log/slog\"\n\t\"mime\"\n\t\"net\"\n\t\"net/http\"\n\n\t\"golang.org/x/net/html\"\n)\n\nvar (\n\tErrOgHandled = errors.New(\"og: handled error\") // used to indicate that the error was handled and should not be logged\n\temptyMap = map[string]string{} // used to indicate an empty result in the cache. Can't use nil as it would be a cache miss.\n)\n\n// fetchHTMLDocumentWithCache fetches the HTML document from the given URL string,\n// preserving the original host header.\nfunc (c *OGTagCache) fetchHTMLDocumentWithCache(ctx context.Context, urlStr string, originalHost string, cacheKey string) (*html.Node, error) {\n\treq, err := http.NewRequestWithContext(ctx, \"GET\", urlStr, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create http request: %w\", err)\n\t}\n\n\t// Set the Host header to the original host\n\tif originalHost != \"\" {\n\t\treq.Host = originalHost\n\t}\n\n\t// Add proxy headers\n\treq.Header.Set(\"X-Forwarded-Proto\", \"https\")\n\treq.Header.Set(\"User-Agent\", \"Anubis-OGTag-Fetcher/1.0\") // For tracking purposes\n\n\t// Send the request\n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\tvar netErr net.Error\n\t\tif errors.As(err, &netErr) && netErr.Timeout() {\n\t\t\tslog.Debug(\"og: request timed out\", \"url\", urlStr)\n\t\t\tc.cache.Set(ctx, cacheKey, emptyMap, c.ogTimeToLive/2) // Cache empty result for half the TTL to not spam the server\n\t\t}\n\t\treturn nil, fmt.Errorf(\"http get failed: %w\", err)\n\t}\n\n\t// Ensure the response body is closed\n\tdefer func(Body io.ReadCloser) {\n\t\terr := Body.Close()\n\t\tif err != nil {\n\t\t\tslog.Debug(\"og: error closing response body\", \"url\", urlStr, \"error\", err)\n\t\t}\n\t}(resp.Body)\n\n\tif resp.StatusCode != http.StatusOK {\n\t\tslog.Debug(\"og: received non-OK status code\", \"url\", urlStr, \"status\", resp.StatusCode)\n\t\tc.cache.Set(ctx, cacheKey, emptyMap, c.ogTimeToLive) // Cache empty result for non-successful status codes\n\t\treturn nil, fmt.Errorf(\"%w: page not found\", ErrOgHandled)\n\t}\n\n\t// Check content type\n\tct := resp.Header.Get(\"Content-Type\")\n\tif ct == \"\" {\n\t\treturn nil, fmt.Errorf(\"missing Content-Type header\")\n\t} else {\n\t\tmediaType, _, err := mime.ParseMediaType(ct)\n\t\tif err != nil {\n\t\t\tslog.Debug(\"og: malformed Content-Type header\", \"url\", urlStr, \"contentType\", ct)\n\t\t\treturn nil, fmt.Errorf(\"%w malformed Content-Type header: %w\", ErrOgHandled, err)\n\t\t}\n\n\t\tif mediaType != \"text/html\" && mediaType != \"application/xhtml+xml\" {\n\t\t\tslog.Debug(\"og: unsupported Content-Type\", \"url\", urlStr, \"contentType\", mediaType)\n\t\t\treturn nil, fmt.Errorf(\"%w unsupported Content-Type: %s\", ErrOgHandled, mediaType)\n\t\t}\n\t}\n\n\tresp.Body = http.MaxBytesReader(nil, resp.Body, maxContentLength)\n\n\tdoc, err := html.Parse(resp.Body)\n\tif err != nil {\n\t\t// Check if the error is specifically because the limit was exceeded\n\t\tvar maxBytesErr *http.MaxBytesError\n\t\tif errors.As(err, &maxBytesErr) {\n\t\t\tslog.Debug(\"og: content exceeded max length\", \"url\", urlStr, \"limit\", maxContentLength)\n\t\t\treturn nil, fmt.Errorf(\"content too large: exceeded %d bytes\", maxContentLength)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"failed to parse HTML: %w\", err)\n\t}\n\n\treturn doc, nil\n}\n"], ["/anubis/lib/policy/celchecker.go", "package policy\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/TecharoHQ/anubis/internal\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/expressions\"\n\t\"github.com/google/cel-go/cel\"\n\t\"github.com/google/cel-go/common/types\"\n)\n\ntype CELChecker struct {\n\tprogram cel.Program\n\tsrc string\n}\n\nfunc NewCELChecker(cfg *config.ExpressionOrList) (*CELChecker, error) {\n\tenv, err := expressions.BotEnvironment()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tprogram, err := expressions.Compile(env, cfg.String())\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't compile CEL program: %w\", err)\n\t}\n\n\treturn &CELChecker{\n\t\tsrc: cfg.String(),\n\t\tprogram: program,\n\t}, nil\n}\n\nfunc (cc *CELChecker) Hash() string {\n\treturn internal.FastHash(cc.src)\n}\n\nfunc (cc *CELChecker) Check(r *http.Request) (bool, error) {\n\tresult, _, err := cc.program.ContextEval(r.Context(), &CELRequest{r})\n\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tif val, ok := result.(types.Bool); ok {\n\t\treturn bool(val), nil\n\t}\n\n\treturn false, nil\n}\n\ntype CELRequest struct {\n\t*http.Request\n}\n\nfunc (cr *CELRequest) Parent() cel.Activation { return nil }\n\nfunc (cr *CELRequest) ResolveName(name string) (any, bool) {\n\tswitch name {\n\tcase \"remoteAddress\":\n\t\treturn cr.Header.Get(\"X-Real-Ip\"), true\n\tcase \"host\":\n\t\treturn cr.Host, true\n\tcase \"method\":\n\t\treturn cr.Method, true\n\tcase \"userAgent\":\n\t\treturn cr.UserAgent(), true\n\tcase \"path\":\n\t\treturn cr.URL.Path, true\n\tcase \"query\":\n\t\treturn expressions.URLValues{Values: cr.URL.Query()}, true\n\tcase \"headers\":\n\t\treturn expressions.HTTPHeaders{Header: cr.Header}, true\n\tcase \"load_1m\":\n\t\treturn expressions.Load1(), true\n\tcase \"load_5m\":\n\t\treturn expressions.Load5(), true\n\tcase \"load_15m\":\n\t\treturn expressions.Load15(), true\n\tdefault:\n\t\treturn nil, false\n\t}\n}\n"], ["/anubis/lib/localization/localization.go", "package localization\n\nimport (\n\t\"embed\"\n\t\"encoding/json\"\n\t\"net/http\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/nicksnyder/go-i18n/v2/i18n\"\n\t\"golang.org/x/text/language\"\n)\n\n//go:embed locales/*.json\nvar localeFS embed.FS\n\ntype LocalizationService struct {\n\tbundle *i18n.Bundle\n}\n\nvar (\n\tglobalService *LocalizationService\n\tonce sync.Once\n)\n\nfunc NewLocalizationService() *LocalizationService {\n\tonce.Do(func() {\n\t\tbundle := i18n.NewBundle(language.English)\n\t\tbundle.RegisterUnmarshalFunc(\"json\", json.Unmarshal)\n\n\t\t// Read all JSON files from the locales directory\n\t\tentries, err := localeFS.ReadDir(\"locales\")\n\t\tif err != nil {\n\t\t\t// Try fallback - create a minimal service with default messages\n\t\t\tglobalService = &LocalizationService{bundle: bundle}\n\t\t\treturn\n\t\t}\n\n\t\tloadedAny := false\n\t\tfor _, entry := range entries {\n\t\t\tif !entry.IsDir() && strings.HasSuffix(entry.Name(), \".json\") {\n\t\t\t\tfilePath := \"locales/\" + entry.Name()\n\t\t\t\t_, err := bundle.LoadMessageFileFS(localeFS, filePath)\n\t\t\t\tif err != nil {\n\t\t\t\t\t// Log error but continue with other files\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tloadedAny = true\n\t\t\t}\n\t\t}\n\n\t\tif !loadedAny {\n\t\t\t// If no files were loaded successfully, create minimal service\n\t\t\tglobalService = &LocalizationService{bundle: bundle}\n\t\t\treturn\n\t\t}\n\n\t\tglobalService = &LocalizationService{bundle: bundle}\n\t})\n\n\t// Safety check - if globalService is still nil, create a minimal one\n\tif globalService == nil {\n\t\tbundle := i18n.NewBundle(language.English)\n\t\tbundle.RegisterUnmarshalFunc(\"json\", json.Unmarshal)\n\t\tglobalService = &LocalizationService{bundle: bundle}\n\t}\n\n\treturn globalService\n}\n\nfunc (ls *LocalizationService) GetLocalizer(lang string) *i18n.Localizer {\n\treturn i18n.NewLocalizer(ls.bundle, lang)\n}\n\nfunc (ls *LocalizationService) GetLocalizerFromRequest(r *http.Request) *i18n.Localizer {\n\tif ls == nil || ls.bundle == nil {\n\t\t// Fallback to a basic bundle if service is not properly initialized\n\t\tbundle := i18n.NewBundle(language.English)\n\t\tbundle.RegisterUnmarshalFunc(\"json\", json.Unmarshal)\n\t\treturn i18n.NewLocalizer(bundle, \"en\")\n\t}\n\tacceptLanguage := r.Header.Get(\"Accept-Language\")\n\treturn i18n.NewLocalizer(ls.bundle, acceptLanguage, \"en\")\n}\n\n// SimpleLocalizer wraps i18n.Localizer with a more convenient API\ntype SimpleLocalizer struct {\n\tLocalizer *i18n.Localizer\n}\n\n// T provides a concise way to localize messages\nfunc (sl *SimpleLocalizer) T(messageID string) string {\n\treturn sl.Localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: messageID})\n}\n\n// Get the language that is used by the localizer by retrieving a well-known string that is required to be present\nfunc (sl *SimpleLocalizer) GetLang() string {\n\t_, tag, err := sl.Localizer.LocalizeWithTag(&i18n.LocalizeConfig{MessageID: \"loading\"})\n\tif err != nil {\n\t\treturn \"en\"\n\t}\n\treturn tag.String()\n}\n\n// GetLocalizer creates a localizer based on the request's Accept-Language header or forcedLanguage option\nfunc GetLocalizer(r *http.Request) *SimpleLocalizer {\n\tvar localizer *i18n.Localizer\n\tif anubis.ForcedLanguage == \"\" {\n\t\tlocalizer = NewLocalizationService().GetLocalizerFromRequest(r)\n\t} else {\n\t\tlocalizer = NewLocalizationService().GetLocalizer(anubis.ForcedLanguage)\n\t}\n\treturn &SimpleLocalizer{Localizer: localizer}\n}\n"], ["/anubis/lib/policy/config/threshold.go", "package config\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com/TecharoHQ/anubis\"\n)\n\nvar (\n\tErrNoThresholdRulesDefined = errors.New(\"config: no thresholds defined\")\n\tErrThresholdMustHaveName = errors.New(\"config.Threshold: must set name\")\n\tErrThresholdMustHaveExpression = errors.New(\"config.Threshold: must set expression\")\n\tErrThresholdChallengeMustHaveChallenge = errors.New(\"config.Threshold: a threshold with the CHALLENGE action must have challenge set\")\n\tErrThresholdCannotHaveWeighAction = errors.New(\"config.Threshold: a threshold cannot have the WEIGH action\")\n\n\tDefaultThresholds = []Threshold{\n\t\t{\n\t\t\tName: \"legacy-anubis-behaviour\",\n\t\t\tExpression: &ExpressionOrList{\n\t\t\t\tExpression: \"weight > 0\",\n\t\t\t},\n\t\t\tAction: RuleChallenge,\n\t\t\tChallenge: &ChallengeRules{\n\t\t\t\tAlgorithm: \"fast\",\n\t\t\t\tDifficulty: anubis.DefaultDifficulty,\n\t\t\t\tReportAs: anubis.DefaultDifficulty,\n\t\t\t},\n\t\t},\n\t}\n)\n\ntype Threshold struct {\n\tName string `json:\"name\" yaml:\"name\"`\n\tExpression *ExpressionOrList `json:\"expression\" yaml:\"expression\"`\n\tAction Rule `json:\"action\" yaml:\"action\"`\n\tChallenge *ChallengeRules `json:\"challenge\" yaml:\"challenge\"`\n}\n\nfunc (t Threshold) Valid() error {\n\tvar errs []error\n\n\tif len(t.Name) == 0 {\n\t\terrs = append(errs, ErrThresholdMustHaveName)\n\t}\n\n\tif t.Expression == nil {\n\t\terrs = append(errs, ErrThresholdMustHaveExpression)\n\t}\n\n\tif t.Expression != nil {\n\t\tif err := t.Expression.Valid(); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\tif err := t.Action.Valid(); err != nil {\n\t\terrs = append(errs, err)\n\t}\n\n\tif t.Action == RuleWeigh {\n\t\terrs = append(errs, ErrThresholdCannotHaveWeighAction)\n\t}\n\n\tif t.Action == RuleChallenge && t.Challenge == nil {\n\t\terrs = append(errs, ErrThresholdChallengeMustHaveChallenge)\n\t}\n\n\tif t.Challenge != nil {\n\t\tif err := t.Challenge.Valid(); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"config: threshold entry for %q is not valid:\\n%w\", t.Name, errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n"], ["/anubis/lib/store/bbolt/bbolt.go", "package bbolt\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n\t\"go.etcd.io/bbolt\"\n)\n\n// Sentinel error values used for testing and in admin-visible error messages.\nvar (\n\tErrBucketDoesNotExist = errors.New(\"bbolt: bucket does not exist\")\n\tErrNotExists = errors.New(\"bbolt: value does not exist in store\")\n)\n\n// Store implements store.Interface backed by bbolt[1].\n//\n// In essence, bbolt is a hierarchical key/value store with a twist: every value\n// needs to belong to a bucket. Buckets can contain an infinite number of\n// buckets. As such, Anubis nests values in buckets. Each value in the store\n// is given its own bucket with two keys:\n//\n// 1. data - The raw data, usually in JSON\n// 2. expiry - The expiry time formatted as a time.RFC3339Nano timestamp string\n//\n// When Anubis stores a new bit of data, it creates a new bucket for that value.\n// This allows the cleanup phase to iterate over every bucket in the database and\n// only scan the expiry times without having to decode the entire record.\n//\n// bbolt is not suitable for environments where multiple instance of Anubis need\n// to read from and write to the same backend store. For that, use the valkey\n// storage backend.\n//\n// [1]: https://github.com/etcd-io/bbolt\ntype Store struct {\n\tbdb *bbolt.DB\n}\n\n// Delete a key from the datastore. If the key does not exist, return an error.\nfunc (s *Store) Delete(ctx context.Context, key string) error {\n\treturn s.bdb.Update(func(tx *bbolt.Tx) error {\n\t\tif tx.Bucket([]byte(key)) == nil {\n\t\t\treturn fmt.Errorf(\"%w: %q\", ErrNotExists, key)\n\t\t}\n\n\t\treturn tx.DeleteBucket([]byte(key))\n\t})\n}\n\n// Get a value from the datastore.\n//\n// Because each value is stored in its own bucket with data and expiry keys,\n// two get operations are required:\n//\n// 1. Get the expiry key, parse as time.RFC3339Nano. If the key has expired, run deletion in the background and return a \"key not found\" error.\n// 2. Get the data key, copy into the result byteslice, return it.\nfunc (s *Store) Get(ctx context.Context, key string) ([]byte, error) {\n\tvar result []byte\n\n\tif err := s.bdb.View(func(tx *bbolt.Tx) error {\n\t\titemBucket := tx.Bucket([]byte(key))\n\t\tif itemBucket == nil {\n\t\t\treturn fmt.Errorf(\"%w: %q\", store.ErrNotFound, key)\n\t\t}\n\n\t\texpiryStr := itemBucket.Get([]byte(\"expiry\"))\n\t\tif expiryStr == nil {\n\t\t\treturn fmt.Errorf(\"[unexpected] %w: %q (expiry is nil)\", store.ErrNotFound, key)\n\t\t}\n\n\t\texpiry, err := time.Parse(time.RFC3339Nano, string(expiryStr))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"[unexpected] %w: %w\", store.ErrCantDecode, err)\n\t\t}\n\n\t\tif time.Now().After(expiry) {\n\t\t\tgo s.Delete(context.Background(), key)\n\t\t\treturn fmt.Errorf(\"%w: %q\", store.ErrNotFound, key)\n\t\t}\n\n\t\tdataStr := itemBucket.Get([]byte(\"data\"))\n\t\tif dataStr == nil {\n\t\t\treturn fmt.Errorf(\"[unexpected] %w: %q (data is nil)\", store.ErrNotFound, key)\n\t\t}\n\n\t\tresult = make([]byte, len(dataStr))\n\t\tif n := copy(result, dataStr); n != len(dataStr) {\n\t\t\treturn fmt.Errorf(\"[unexpected] %w: %d bytes copied of %d\", store.ErrCantDecode, n, len(dataStr))\n\t\t}\n\n\t\treturn nil\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn result, nil\n}\n\n// Set a value into the store with a given expiry.\nfunc (s *Store) Set(ctx context.Context, key string, value []byte, expiry time.Duration) error {\n\texpires := time.Now().Add(expiry)\n\n\treturn s.bdb.Update(func(tx *bbolt.Tx) error {\n\t\tvalueBkt, err := tx.CreateBucketIfNotExists([]byte(key))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"%w: %w: %q (create bucket)\", store.ErrCantEncode, err, key)\n\t\t}\n\n\t\tif err := valueBkt.Put([]byte(\"expiry\"), []byte(expires.Format(time.RFC3339Nano))); err != nil {\n\t\t\treturn fmt.Errorf(\"%w: %q (expiry)\", store.ErrCantEncode, key)\n\t\t}\n\n\t\tif err := valueBkt.Put([]byte(\"data\"), value); err != nil {\n\t\t\treturn fmt.Errorf(\"%w: %q (data)\", store.ErrCantEncode, key)\n\t\t}\n\n\t\treturn nil\n\t})\n}\n\nfunc (s *Store) cleanup(ctx context.Context) error {\n\tnow := time.Now()\n\n\treturn s.bdb.Update(func(tx *bbolt.Tx) error {\n\t\treturn tx.ForEach(func(key []byte, valueBkt *bbolt.Bucket) error {\n\t\t\tvar expiry time.Time\n\t\t\tvar err error\n\n\t\t\texpiryStr := valueBkt.Get([]byte(\"expiry\"))\n\t\t\tif expiryStr == nil {\n\t\t\t\tslog.Warn(\"while running cleanup, expiry is not set somehow, file a bug?\", \"key\", string(key))\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\texpiry, err = time.Parse(time.RFC3339Nano, string(expiryStr))\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"[unexpected] %w in bucket %q: %w\", store.ErrCantDecode, string(key), err)\n\t\t\t}\n\n\t\t\tif now.After(expiry) {\n\t\t\t\treturn tx.DeleteBucket(key)\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\t})\n}\n\nfunc (s *Store) cleanupThread(ctx context.Context) {\n\tt := time.NewTicker(time.Hour)\n\tdefer t.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase <-t.C:\n\t\t\tif err := s.cleanup(ctx); err != nil {\n\t\t\t\tslog.Error(\"error during bbolt cleanup\", \"err\", err)\n\t\t\t}\n\t\t}\n\t}\n}\n"], ["/anubis/internal/log.go", "package internal\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"log/slog\"\n\t\"net/http\"\n\t\"os\"\n\t\"strings\"\n)\n\nfunc InitSlog(level string) {\n\tvar programLevel slog.Level\n\tif err := (&programLevel).UnmarshalText([]byte(level)); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"invalid log level %s: %v, using info\\n\", level, err)\n\t\tprogramLevel = slog.LevelInfo\n\t}\n\n\tleveler := &slog.LevelVar{}\n\tleveler.Set(programLevel)\n\n\th := slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{\n\t\tAddSource: true,\n\t\tLevel: leveler,\n\t})\n\tslog.SetDefault(slog.New(h))\n}\n\nfunc GetRequestLogger(r *http.Request) *slog.Logger {\n\treturn slog.With(\n\t\t\"user_agent\", r.UserAgent(),\n\t\t\"accept_language\", r.Header.Get(\"Accept-Language\"),\n\t\t\"priority\", r.Header.Get(\"Priority\"),\n\t\t\"x-forwarded-for\",\n\t\tr.Header.Get(\"X-Forwarded-For\"),\n\t\t\"x-real-ip\", r.Header.Get(\"X-Real-Ip\"),\n\t)\n}\n\n// ErrorLogFilter is used to suppress \"context canceled\" logs from the http server when a request is canceled (e.g., when a client disconnects).\ntype ErrorLogFilter struct {\n\tUnwrap *log.Logger\n}\n\nfunc (elf *ErrorLogFilter) Write(p []byte) (n int, err error) {\n\tlogMessage := string(p)\n\tif strings.Contains(logMessage, \"context canceled\") {\n\t\treturn len(p), nil // Suppress the log by doing nothing\n\t}\n\tif elf.Unwrap != nil {\n\t\treturn elf.Unwrap.Writer().Write(p)\n\t}\n\treturn len(p), nil\n}\n\nfunc GetFilteredHTTPLogger() *log.Logger {\n\tstdErrLogger := log.New(os.Stderr, \"\", log.LstdFlags) // essentially what the default logger is.\n\treturn log.New(&ErrorLogFilter{Unwrap: stdErrLogger}, \"\", 0)\n}\n"], ["/anubis/internal/gzip.go", "package internal\n\nimport (\n\t\"compress/gzip\"\n\t\"net/http\"\n\t\"strings\"\n)\n\nfunc GzipMiddleware(level int, next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif !strings.Contains(r.Header.Get(\"Accept-Encoding\"), \"gzip\") {\n\t\t\tnext.ServeHTTP(w, r)\n\t\t\treturn\n\t\t}\n\n\t\tw.Header().Set(\"Content-Encoding\", \"gzip\")\n\t\tgz, err := gzip.NewWriterLevel(w, level)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tdefer gz.Close()\n\n\t\tgrw := gzipResponseWriter{ResponseWriter: w, sink: gz}\n\t\tnext.ServeHTTP(grw, r)\n\t})\n}\n\ntype gzipResponseWriter struct {\n\thttp.ResponseWriter\n\tsink *gzip.Writer\n}\n\nfunc (w gzipResponseWriter) Write(b []byte) (int, error) {\n\treturn w.sink.Write(b)\n}\n"], ["/anubis/lib/store/valkey/factory.go", "package valkey\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n\tvalkey \"github.com/redis/go-redis/v9\"\n)\n\nvar (\n\tErrNoURL = errors.New(\"valkey.Config: no URL defined\")\n\tErrBadURL = errors.New(\"valkey.Config: URL is invalid\")\n)\n\nfunc init() {\n\tstore.Register(\"valkey\", Factory{})\n}\n\ntype Factory struct{}\n\nfunc (Factory) Build(ctx context.Context, data json.RawMessage) (store.Interface, error) {\n\tvar config Config\n\n\tif err := json.Unmarshal([]byte(data), &config); err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\tif err := config.Valid(); err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\topts, err := valkey.ParseURL(config.URL)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\trdb := valkey.NewClient(opts)\n\n\tif _, err := rdb.Ping(ctx).Result(); err != nil {\n\t\treturn nil, fmt.Errorf(\"can't ping valkey instance: %w\", err)\n\t}\n\n\treturn &Store{\n\t\trdb: rdb,\n\t}, nil\n}\n\nfunc (Factory) Valid(data json.RawMessage) error {\n\tvar config Config\n\tif err := json.Unmarshal([]byte(data), &config); err != nil {\n\t\treturn fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\tif err := config.Valid(); err != nil {\n\t\treturn fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\treturn nil\n}\n\ntype Config struct {\n\tURL string `json:\"url\"`\n}\n\nfunc (c Config) Valid() error {\n\tvar errs []error\n\n\tif c.URL == \"\" {\n\t\terrs = append(errs, ErrNoURL)\n\t}\n\n\tif _, err := valkey.ParseURL(c.URL); err != nil {\n\t\terrs = append(errs, ErrBadURL)\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"valkey.Config: invalid config: %w\", errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n"], ["/anubis/internal/dnsbl/dnsbl.go", "package dnsbl\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net\"\n\t\"strings\"\n)\n\n//go:generate go tool golang.org/x/tools/cmd/stringer -type=DroneBLResponse\n\ntype DroneBLResponse byte\n\nconst (\n\tAllGood DroneBLResponse = 0\n\tIRCDrone DroneBLResponse = 3\n\tBottler DroneBLResponse = 5\n\tUnknownSpambotOrDrone DroneBLResponse = 6\n\tDDOSDrone DroneBLResponse = 7\n\tSOCKSProxy DroneBLResponse = 8\n\tHTTPProxy DroneBLResponse = 9\n\tProxyChain DroneBLResponse = 10\n\tOpenProxy DroneBLResponse = 11\n\tOpenDNSResolver DroneBLResponse = 12\n\tBruteForceAttackers DroneBLResponse = 13\n\tOpenWingateProxy DroneBLResponse = 14\n\tCompromisedRouter DroneBLResponse = 15\n\tAutoRootingWorms DroneBLResponse = 16\n\tAutoDetectedBotIP DroneBLResponse = 17\n\tUnknown DroneBLResponse = 255\n)\n\nfunc Reverse(ip net.IP) string {\n\tif ip.To4() != nil {\n\t\treturn reverse4(ip)\n\t}\n\n\treturn reverse6(ip)\n}\n\nfunc reverse4(ip net.IP) string {\n\tsplitAddress := strings.Split(ip.String(), \".\")\n\n\t// swap first and last octet\n\tsplitAddress[0], splitAddress[3] = splitAddress[3], splitAddress[0]\n\t// swap middle octets\n\tsplitAddress[1], splitAddress[2] = splitAddress[2], splitAddress[1]\n\n\treturn strings.Join(splitAddress, \".\")\n}\n\nfunc reverse6(ip net.IP) string {\n\tipBytes := []byte(ip)\n\tvar sb strings.Builder\n\n\tfor i := len(ipBytes) - 1; i >= 0; i-- {\n\t\t// Split the byte into two nibbles\n\t\thighNibble := ipBytes[i] >> 4\n\t\tlowNibble := ipBytes[i] & 0x0F\n\n\t\t// Append the nibbles in reversed order\n\t\tsb.WriteString(fmt.Sprintf(\"%x.%x.\", lowNibble, highNibble))\n\t}\n\n\treturn sb.String()[:len(sb.String())-1]\n}\n\nfunc Lookup(ipStr string) (DroneBLResponse, error) {\n\tip := net.ParseIP(ipStr)\n\tif ip == nil {\n\t\treturn Unknown, errors.New(\"dnsbl: input is not an IP address\")\n\t}\n\n\trevIP := Reverse(ip) + \".dnsbl.dronebl.org\"\n\n\tips, err := net.LookupIP(revIP)\n\tif err != nil {\n\t\tvar dnserr *net.DNSError\n\t\tif errors.As(err, &dnserr) {\n\t\t\tif dnserr.IsNotFound {\n\t\t\t\treturn AllGood, nil\n\t\t\t}\n\t\t}\n\n\t\treturn Unknown, err\n\t}\n\n\tif len(ips) != 0 {\n\t\tfor _, ip := range ips {\n\t\t\treturn DroneBLResponse(ip.To4()[3]), nil\n\t\t}\n\t}\n\n\treturn UnknownSpambotOrDrone, nil\n}\n"], ["/anubis/lib/thoth/cachediptoasn.go", "package thoth\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net/netip\"\n\n\tiptoasnv1 \"github.com/TecharoHQ/thoth-proto/gen/techaro/thoth/iptoasn/v1\"\n\t\"github.com/gaissmai/bart\"\n\t\"google.golang.org/grpc\"\n)\n\ntype IPToASNWithCache struct {\n\tnext iptoasnv1.IpToASNServiceClient\n\ttable *bart.Table[*iptoasnv1.LookupResponse]\n}\n\nfunc NewIpToASNWithCache(next iptoasnv1.IpToASNServiceClient) *IPToASNWithCache {\n\tresult := &IPToASNWithCache{\n\t\tnext: next,\n\t\ttable: &bart.Table[*iptoasnv1.LookupResponse]{},\n\t}\n\n\tfor _, pfx := range []netip.Prefix{\n\t\tnetip.MustParsePrefix(\"10.0.0.0/8\"), // RFC 1918\n\t\tnetip.MustParsePrefix(\"172.16.0.0/12\"), // RFC 1918\n\t\tnetip.MustParsePrefix(\"192.168.0.0/16\"), // RFC 1918\n\t\tnetip.MustParsePrefix(\"127.0.0.0/8\"), // Loopback\n\t\tnetip.MustParsePrefix(\"169.254.0.0/16\"), // Link-local\n\t\tnetip.MustParsePrefix(\"100.64.0.0/10\"), // CGNAT\n\t\tnetip.MustParsePrefix(\"192.0.0.0/24\"), // Protocol assignments\n\t\tnetip.MustParsePrefix(\"192.0.2.0/24\"), // TEST-NET-1\n\t\tnetip.MustParsePrefix(\"198.18.0.0/15\"), // Benchmarking\n\t\tnetip.MustParsePrefix(\"198.51.100.0/24\"), // TEST-NET-2\n\t\tnetip.MustParsePrefix(\"203.0.113.0/24\"), // TEST-NET-3\n\t\tnetip.MustParsePrefix(\"240.0.0.0/4\"), // Reserved\n\t\tnetip.MustParsePrefix(\"255.255.255.255/32\"), // Broadcast\n\t\tnetip.MustParsePrefix(\"fc00::/7\"), // Unique local address\n\t\tnetip.MustParsePrefix(\"fe80::/10\"), // Link-local\n\t\tnetip.MustParsePrefix(\"::1/128\"), // Loopback\n\t\tnetip.MustParsePrefix(\"::/128\"), // Unspecified\n\t\tnetip.MustParsePrefix(\"100::/64\"), // Discard-only\n\t\tnetip.MustParsePrefix(\"2001:db8::/32\"), // Documentation\n\t} {\n\t\tresult.table.Insert(pfx, &iptoasnv1.LookupResponse{Announced: false})\n\t}\n\n\treturn result\n}\n\nfunc (ip2asn *IPToASNWithCache) Lookup(ctx context.Context, lr *iptoasnv1.LookupRequest, opts ...grpc.CallOption) (*iptoasnv1.LookupResponse, error) {\n\taddr, err := netip.ParseAddr(lr.GetIpAddress())\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"input is not an IP address: %w\", err)\n\t}\n\n\tcachedResponse, ok := ip2asn.table.Lookup(addr)\n\tif ok {\n\t\treturn cachedResponse, nil\n\t}\n\n\tresp, err := ip2asn.next.Lookup(ctx, lr, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar errs []error\n\tfor _, cidr := range resp.GetCidr() {\n\t\tpfx, err := netip.ParsePrefix(cidr)\n\t\tif err != nil {\n\t\t\terrs = append(errs, err)\n\t\t\tcontinue\n\t\t}\n\t\tip2asn.table.Insert(pfx, resp)\n\t}\n\n\tif len(errs) != 0 {\n\t\tslog.Error(\"errors parsing IP prefixes\", \"err\", errors.Join(errs...))\n\t}\n\n\treturn resp, nil\n}\n"], ["/anubis/lib/store/bbolt/factory.go", "package bbolt\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n\t\"go.etcd.io/bbolt\"\n)\n\nvar (\n\tErrMissingPath = errors.New(\"bbolt: path is missing from config\")\n\tErrCantWriteToPath = errors.New(\"bbolt: can't write to path\")\n)\n\nfunc init() {\n\tstore.Register(\"bbolt\", Factory{})\n}\n\n// Factory builds new instances of the bbolt storage backend according to\n// configuration passed via a json.RawMessage.\ntype Factory struct{}\n\n// Build parses and validates the bbolt storage backend Config and creates\n// a new instance of it.\nfunc (Factory) Build(ctx context.Context, data json.RawMessage) (store.Interface, error) {\n\tvar config Config\n\tif err := json.Unmarshal([]byte(data), &config); err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\tif err := config.Valid(); err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\tbdb, err := bbolt.Open(config.Path, 0600, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't open bbolt database %s: %w\", config.Path, err)\n\t}\n\n\tresult := &Store{\n\t\tbdb: bdb,\n\t}\n\n\tgo result.cleanupThread(ctx)\n\n\treturn result, nil\n}\n\n// Valid parses and validates the bbolt store Config or returns\n// an error.\nfunc (Factory) Valid(data json.RawMessage) error {\n\tvar config Config\n\tif err := json.Unmarshal([]byte(data), &config); err != nil {\n\t\treturn fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\tif err := config.Valid(); err != nil {\n\t\treturn fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\treturn nil\n}\n\n// Config is the bbolt storage backend configuration.\ntype Config struct {\n\t// Path is the filesystem path of the database. The folder must be writable to Anubis.\n\tPath string `json:\"path\"`\n}\n\n// Valid validates the configuration including checking if its containing folder is writable.\nfunc (c Config) Valid() error {\n\tvar errs []error\n\n\tif c.Path == \"\" {\n\t\terrs = append(errs, ErrMissingPath)\n\t} else {\n\t\tdir := filepath.Dir(c.Path)\n\t\tif err := os.WriteFile(filepath.Join(dir, \".test-file\"), []byte(\"\"), 0600); err != nil {\n\t\t\terrs = append(errs, ErrCantWriteToPath)\n\t\t}\n\t\tos.Remove(filepath.Join(dir, \".test-file\"))\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn errors.Join(errs...)\n\t}\n\n\treturn nil\n}\n"], ["/anubis/lib/store/valkey/valkey.go", "package valkey\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n\tvalkey \"github.com/redis/go-redis/v9\"\n)\n\ntype Store struct {\n\trdb *valkey.Client\n}\n\nfunc (s *Store) Delete(ctx context.Context, key string) error {\n\tn, err := s.rdb.Del(ctx, key).Result()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"can't delete from valkey: %w\", err)\n\t}\n\n\tswitch n {\n\tcase 0:\n\t\treturn fmt.Errorf(\"%w: %d key(s) deleted\", store.ErrNotFound, n)\n\tdefault:\n\t\treturn nil\n\t}\n}\n\nfunc (s *Store) Get(ctx context.Context, key string) ([]byte, error) {\n\tresult, err := s.rdb.Get(ctx, key).Result()\n\tif err != nil {\n\t\tif valkey.HasErrorPrefix(err, \"redis: nil\") {\n\t\t\treturn nil, fmt.Errorf(\"%w: %w\", store.ErrNotFound, err)\n\t\t}\n\n\t\treturn nil, fmt.Errorf(\"can't fetch from valkey: %w\", err)\n\t}\n\n\treturn []byte(result), nil\n}\n\nfunc (s *Store) Set(ctx context.Context, key string, value []byte, expiry time.Duration) error {\n\tif _, err := s.rdb.Set(ctx, key, string(value), expiry).Result(); err != nil {\n\t\treturn fmt.Errorf(\"can't set %q in valkey: %w\", key, err)\n\t}\n\n\treturn nil\n}\n"], ["/anubis/lib/policy/config/store.go", "package config\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n\t_ \"github.com/TecharoHQ/anubis/lib/store/all\"\n)\n\nvar (\n\tErrNoStoreBackend = errors.New(\"config.Store: no backend defined\")\n\tErrUnknownStoreBackend = errors.New(\"config.Store: unknown backend\")\n)\n\ntype Store struct {\n\tBackend string `json:\"backend\"`\n\tParameters json.RawMessage `json:\"parameters\"`\n}\n\nfunc (s *Store) Valid() error {\n\tvar errs []error\n\n\tif len(s.Backend) == 0 {\n\t\terrs = append(errs, ErrNoStoreBackend)\n\t}\n\n\tfac, ok := store.Get(s.Backend)\n\tswitch ok {\n\tcase true:\n\t\tif err := fac.Valid(s.Parameters); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\tcase false:\n\t\terrs = append(errs, fmt.Errorf(\"%w: %q\", ErrUnknownStoreBackend, s.Backend))\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn errors.Join(errs...)\n\t}\n\n\treturn nil\n}\n"], ["/anubis/lib/thoth/thoth.go", "package thoth\n\nimport (\n\t\"context\"\n\t\"crypto/tls\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\tiptoasnv1 \"github.com/TecharoHQ/thoth-proto/gen/techaro/thoth/iptoasn/v1\"\n\tgrpcprom \"github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus\"\n\t\"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/timeout\"\n\t\"github.com/prometheus/client_golang/prometheus\"\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/credentials\"\n\t\"google.golang.org/grpc/credentials/insecure\"\n\thealthv1 \"google.golang.org/grpc/health/grpc_health_v1\"\n)\n\ntype Client struct {\n\tconn *grpc.ClientConn\n\thealth healthv1.HealthClient\n\tIPToASN iptoasnv1.IpToASNServiceClient\n}\n\nfunc New(ctx context.Context, thothURL, apiToken string, plaintext bool) (*Client, error) {\n\tclMetrics := grpcprom.NewClientMetrics(\n\t\tgrpcprom.WithClientHandlingTimeHistogram(\n\t\t\tgrpcprom.WithHistogramBuckets([]float64{0.001, 0.01, 0.1, 0.3, 0.6, 1, 3, 6, 9, 20, 30, 60, 90, 120}),\n\t\t),\n\t)\n\tprometheus.DefaultRegisterer.Register(clMetrics)\n\n\tdo := []grpc.DialOption{\n\t\tgrpc.WithChainUnaryInterceptor(\n\t\t\ttimeout.UnaryClientInterceptor(500*time.Millisecond),\n\t\t\tclMetrics.UnaryClientInterceptor(),\n\t\t\tauthUnaryClientInterceptor(apiToken),\n\t\t),\n\t\tgrpc.WithChainStreamInterceptor(\n\t\t\tclMetrics.StreamClientInterceptor(),\n\t\t\tauthStreamClientInterceptor(apiToken),\n\t\t),\n\t\tgrpc.WithUserAgent(fmt.Sprint(\"Techaro/anubis:\", anubis.Version)),\n\t}\n\n\tif plaintext {\n\t\tdo = append(do, grpc.WithTransportCredentials(insecure.NewCredentials()))\n\t} else {\n\t\tdo = append(do, grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{})))\n\t}\n\n\tconn, err := grpc.NewClient(\n\t\tthothURL,\n\t\tdo...,\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't dial thoth at %s: %w\", thothURL, err)\n\t}\n\n\thc := healthv1.NewHealthClient(conn)\n\n\treturn &Client{\n\t\tconn: conn,\n\t\thealth: hc,\n\t\tIPToASN: NewIpToASNWithCache(iptoasnv1.NewIpToASNServiceClient(conn)),\n\t}, nil\n}\n\nfunc (c *Client) Close() error {\n\tif c.conn != nil {\n\t\treturn c.conn.Close()\n\t}\n\treturn nil\n}\n\nfunc (c *Client) WithIPToASNService(impl iptoasnv1.IpToASNServiceClient) {\n\tc.IPToASN = impl\n}\n"], ["/anubis/lib/challenge/metarefresh/metarefresh_templ.go", "// Code generated by templ - DO NOT EDIT.\n\n// templ: version: v0.3.906\npackage metarefresh\n\n//lint:file-ignore SA4006 This context is only used if a nested component is present.\n\nimport \"github.com/a-h/templ\"\nimport templruntime \"github.com/a-h/templ/runtime\"\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/TecharoHQ/anubis/lib/localization\"\n)\n\nfunc page(redir string, difficulty int, loc *localization.SimpleLocalizer) templ.Component {\n\treturn templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {\n\t\ttempl_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context\n\t\tif templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {\n\t\t\treturn templ_7745c5c3_CtxErr\n\t\t}\n\t\ttempl_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)\n\t\tif !templ_7745c5c3_IsBuffer {\n\t\t\tdefer func() {\n\t\t\t\ttempl_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)\n\t\t\t\tif templ_7745c5c3_Err == nil {\n\t\t\t\t\ttempl_7745c5c3_Err = templ_7745c5c3_BufErr\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\tctx = templ.InitializeContext(ctx)\n\t\ttempl_7745c5c3_Var1 := templ.GetChildren(ctx)\n\t\tif templ_7745c5c3_Var1 == nil {\n\t\t\ttempl_7745c5c3_Var1 = templ.NopComponent\n\t\t}\n\t\tctx = templ.ClearChildren(ctx)\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var4 string\n\t\ttempl_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(loc.T(\"loading\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `metarefresh.templ`, Line: 14, Col: 35}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var5 string\n\t\ttempl_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(loc.T(\"connection_security\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `metarefresh.templ`, Line: 15, Col: 35}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\treturn nil\n\t})\n}\n\nvar _ = templruntime.GeneratedTemplate\n"], ["/anubis/web/index_templ.go", "// Code generated by templ - DO NOT EDIT.\n\n// templ: version: v0.3.906\npackage web\n\n//lint:file-ignore SA4006 This context is only used if a nested component is present.\n\nimport \"github.com/a-h/templ\"\nimport templruntime \"github.com/a-h/templ/runtime\"\n\nimport (\n\t\"fmt\"\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/TecharoHQ/anubis/lib/localization\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/xess\"\n)\n\nfunc base(title string, body templ.Component, impressum *config.Impressum, challenge any, ogTags map[string]string, localizer *localization.SimpleLocalizer) templ.Component {\n\treturn templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {\n\t\ttempl_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context\n\t\tif templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {\n\t\t\treturn templ_7745c5c3_CtxErr\n\t\t}\n\t\ttempl_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)\n\t\tif !templ_7745c5c3_IsBuffer {\n\t\t\tdefer func() {\n\t\t\t\ttempl_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)\n\t\t\t\tif templ_7745c5c3_Err == nil {\n\t\t\t\t\ttempl_7745c5c3_Err = templ_7745c5c3_BufErr\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\tctx = templ.InitializeContext(ctx)\n\t\ttempl_7745c5c3_Var1 := templ.GetChildren(ctx)\n\t\tif templ_7745c5c3_Var1 == nil {\n\t\t\ttempl_7745c5c3_Var1 = templ.NopComponent\n\t\t}\n\t\tctx = templ.ClearChildren(ctx)\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, \"\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var3 string\n\t\ttempl_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(title)\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 15, Col: 17}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 3, \"\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tfor key, value := range ogTags {\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, \"\")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, \"\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templ.JSONScript(\"anubis_version\", anubis.Version).Render(ctx, templ_7745c5c3_Buffer)\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tif challenge != nil {\n\t\t\ttempl_7745c5c3_Err = templ.JSONScript(\"anubis_challenge\", challenge).Render(ctx, templ_7745c5c3_Buffer)\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t}\n\t\ttempl_7745c5c3_Err = templ.JSONScript(\"anubis_base_prefix\", anubis.BasePrefix).Render(ctx, templ_7745c5c3_Buffer)\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var7 string\n\t\ttempl_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(title)\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 68, Col: 47}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 10, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = body.Render(ctx, templ_7745c5c3_Buffer)\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var8 string\n\t\ttempl_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"protected_by\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 73, Col: 36}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, \" Anubis \")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var9 string\n\t\ttempl_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"protected_from\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 73, Col: 127}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, \" Techaro. \")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var10 string\n\t\ttempl_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"made_with\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 75, Col: 40}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 14, \".

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var11 string\n\t\ttempl_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"mascot_design\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 77, Col: 39}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, \" \")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var12 string\n\t\ttempl_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"celphase\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 77, Col: 123}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, \".

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tif impressum != nil {\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, \"

\")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\ttempl_7745c5c3_Err = templ.Raw(impressum.Footer).Render(ctx, templ_7745c5c3_Buffer)\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 18, \"-- Imprint

\")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 20, \"
\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\treturn nil\n\t})\n}\n\nfunc index(localizer *localization.SimpleLocalizer) templ.Component {\n\treturn templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {\n\t\ttempl_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context\n\t\tif templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {\n\t\t\treturn templ_7745c5c3_CtxErr\n\t\t}\n\t\ttempl_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)\n\t\tif !templ_7745c5c3_IsBuffer {\n\t\t\tdefer func() {\n\t\t\t\ttempl_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)\n\t\t\t\tif templ_7745c5c3_Err == nil {\n\t\t\t\t\ttempl_7745c5c3_Err = templ_7745c5c3_BufErr\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\tctx = templ.InitializeContext(ctx)\n\t\ttempl_7745c5c3_Var14 := templ.GetChildren(ctx)\n\t\tif templ_7745c5c3_Var14 == nil {\n\t\t\ttempl_7745c5c3_Var14 = templ.NopComponent\n\t\t}\n\t\tctx = templ.ClearChildren(ctx)\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 21, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var17 string\n\t\ttempl_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"loading\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 95, Col: 41}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var17))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 24, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var19 string\n\t\ttempl_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"why_am_i_seeing\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 101, Col: 44}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var19))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 26, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var20 string\n\t\ttempl_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"ai_companies_explanation\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 103, Col: 45}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var20))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 27, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var21 string\n\t\ttempl_7745c5c3_Var21, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"anubis_compromise\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 106, Col: 38}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var21))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var22 string\n\t\ttempl_7745c5c3_Var22, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"hack_purpose\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 109, Col: 33}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var22))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var23 string\n\t\ttempl_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"jshelter_note\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 112, Col: 34}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var23))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 30, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var24 string\n\t\ttempl_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"version_info\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 114, Col: 35}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var24))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 31, \" \")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var25 string\n\t\ttempl_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinStringErrs(anubis.Version)\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 114, Col: 60}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var25))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 32, \".

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\treturn nil\n\t})\n}\n\nfunc errorPage(message, mail string, localizer *localization.SimpleLocalizer) templ.Component {\n\treturn templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {\n\t\ttempl_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context\n\t\tif templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {\n\t\t\treturn templ_7745c5c3_CtxErr\n\t\t}\n\t\ttempl_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)\n\t\tif !templ_7745c5c3_IsBuffer {\n\t\t\tdefer func() {\n\t\t\t\ttempl_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)\n\t\t\t\tif templ_7745c5c3_Err == nil {\n\t\t\t\t\ttempl_7745c5c3_Err = templ_7745c5c3_BufErr\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\tctx = templ.InitializeContext(ctx)\n\t\ttempl_7745c5c3_Var27 := templ.GetChildren(ctx)\n\t\tif templ_7745c5c3_Var27 == nil {\n\t\t\ttempl_7745c5c3_Var27 = templ.NopComponent\n\t\t}\n\t\tctx = templ.ClearChildren(ctx)\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 34, \"
\\\"Sad

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var29 string\n\t\ttempl_7745c5c3_Var29, templ_7745c5c3_Err = templ.JoinStringErrs(message)\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 128, Col: 14}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var29))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 36, \".

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tif mail != \"\" {\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 37, \"

\")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\tvar templ_7745c5c3_Var30 string\n\t\t\ttempl_7745c5c3_Var30, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"go_home\"))\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 131, Col: 40}\n\t\t\t}\n\t\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var30))\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 38, \" \")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\tvar templ_7745c5c3_Var31 string\n\t\t\ttempl_7745c5c3_Var31, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"contact_webmaster\"))\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 131, Col: 81}\n\t\t\t}\n\t\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var31))\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 39, \" \")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\tvar templ_7745c5c3_Var33 string\n\t\t\ttempl_7745c5c3_Var33, templ_7745c5c3_Err = templ.JoinStringErrs(mail)\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 133, Col: 11}\n\t\t\t}\n\t\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var33))\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 41, \"

\")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t} else {\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 42, \"

\")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\tvar templ_7745c5c3_Var34 string\n\t\t\ttempl_7745c5c3_Var34, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"go_home\"))\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 137, Col: 42}\n\t\t\t}\n\t\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var34))\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 43, \"

\")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 44, \"
\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\treturn nil\n\t})\n}\n\nfunc StaticHappy(localizer *localization.SimpleLocalizer) templ.Component {\n\treturn templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {\n\t\ttempl_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context\n\t\tif templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {\n\t\t\treturn templ_7745c5c3_CtxErr\n\t\t}\n\t\ttempl_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)\n\t\tif !templ_7745c5c3_IsBuffer {\n\t\t\tdefer func() {\n\t\t\t\ttempl_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)\n\t\t\t\tif templ_7745c5c3_Err == nil {\n\t\t\t\t\ttempl_7745c5c3_Err = templ_7745c5c3_BufErr\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\tctx = templ.InitializeContext(ctx)\n\t\ttempl_7745c5c3_Var35 := templ.GetChildren(ctx)\n\t\tif templ_7745c5c3_Var35 == nil {\n\t\t\ttempl_7745c5c3_Var35 = templ.NopComponent\n\t\t}\n\t\tctx = templ.ClearChildren(ctx)\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 45, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var37 string\n\t\ttempl_7745c5c3_Var37, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"static_check_endpoint\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 150, Col: 43}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var37))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 47, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\treturn nil\n\t})\n}\n\nfunc bench(localizer *localization.SimpleLocalizer) templ.Component {\n\treturn templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {\n\t\ttempl_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context\n\t\tif templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {\n\t\t\treturn templ_7745c5c3_CtxErr\n\t\t}\n\t\ttempl_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)\n\t\tif !templ_7745c5c3_IsBuffer {\n\t\t\tdefer func() {\n\t\t\t\ttempl_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)\n\t\t\t\tif templ_7745c5c3_Err == nil {\n\t\t\t\t\ttempl_7745c5c3_Err = templ_7745c5c3_BufErr\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\tctx = templ.InitializeContext(ctx)\n\t\ttempl_7745c5c3_Var38 := templ.GetChildren(ctx)\n\t\tif templ_7745c5c3_Var38 == nil {\n\t\t\ttempl_7745c5c3_Var38 = templ.NopComponent\n\t\t}\n\t\tctx = templ.ClearChildren(ctx)\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 48, \"
\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var39 string\n\t\ttempl_7745c5c3_Var39, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"time\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 161, Col: 51}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var39))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 49, \"\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var40 string\n\t\ttempl_7745c5c3_Var40, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"iters\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 162, Col: 50}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var40))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 50, \"
\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var41 string\n\t\ttempl_7745c5c3_Var41, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"time_a\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 165, Col: 53}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var41))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 51, \"\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var42 string\n\t\ttempl_7745c5c3_Var42, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"iters_a\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 166, Col: 52}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var42))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 52, \"\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var43 string\n\t\ttempl_7745c5c3_Var43, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"time_b\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 167, Col: 53}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var43))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 53, \"\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var44 string\n\t\ttempl_7745c5c3_Var44, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"iters_b\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 168, Col: 52}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var44))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 54, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var46 string\n\t\ttempl_7745c5c3_Var46, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"loading\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 178, Col: 66}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var46))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 56, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\treturn nil\n\t})\n}\n\nvar _ = templruntime.GeneratedTemplate\n"], ["/anubis/web/index.go", "package web\n\nimport (\n\t\"github.com/a-h/templ\"\n\n\t\"github.com/TecharoHQ/anubis/lib/localization\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n)\n\nfunc Base(title string, body templ.Component, impressum *config.Impressum, localizer *localization.SimpleLocalizer) templ.Component {\n\treturn base(title, body, impressum, nil, nil, localizer)\n}\n\nfunc BaseWithChallengeAndOGTags(title string, body templ.Component, impressum *config.Impressum, challenge string, rules *config.ChallengeRules, ogTags map[string]string, localizer *localization.SimpleLocalizer) (templ.Component, error) {\n\treturn base(title, body, impressum, struct {\n\t\tRules *config.ChallengeRules `json:\"rules\"`\n\t\tChallenge string `json:\"challenge\"`\n\t}{\n\t\tChallenge: challenge,\n\t\tRules: rules,\n\t}, ogTags, localizer), nil\n}\n\nfunc Index(localizer *localization.SimpleLocalizer) templ.Component {\n\treturn index(localizer)\n}\n\nfunc ErrorPage(msg, mail string, localizer *localization.SimpleLocalizer) templ.Component {\n\treturn errorPage(msg, mail, localizer)\n}\n\nfunc Bench(localizer *localization.SimpleLocalizer) templ.Component {\n\treturn bench(localizer)\n}\n"], ["/anubis/lib/policy/expressions/environment.go", "package expressions\n\nimport (\n\t\"math/rand/v2\"\n\t\"strings\"\n\n\t\"github.com/google/cel-go/cel\"\n\t\"github.com/google/cel-go/common/types\"\n\t\"github.com/google/cel-go/common/types/ref\"\n\t\"github.com/google/cel-go/common/types/traits\"\n\t\"github.com/google/cel-go/ext\"\n)\n\n// BotEnvironment creates a new CEL environment, this is the set of\n// variables and functions that are passed into the CEL scope so that\n// Anubis can fail loudly and early when something is invalid instead\n// of blowing up at runtime.\nfunc BotEnvironment() (*cel.Env, error) {\n\treturn New(\n\t\t// Variables exposed to CEL programs:\n\t\tcel.Variable(\"remoteAddress\", cel.StringType),\n\t\tcel.Variable(\"host\", cel.StringType),\n\t\tcel.Variable(\"method\", cel.StringType),\n\t\tcel.Variable(\"userAgent\", cel.StringType),\n\t\tcel.Variable(\"path\", cel.StringType),\n\t\tcel.Variable(\"query\", cel.MapType(cel.StringType, cel.StringType)),\n\t\tcel.Variable(\"headers\", cel.MapType(cel.StringType, cel.StringType)),\n\t\tcel.Variable(\"load_1m\", cel.DoubleType),\n\t\tcel.Variable(\"load_5m\", cel.DoubleType),\n\t\tcel.Variable(\"load_15m\", cel.DoubleType),\n\n\t\t// Bot-specific functions:\n\t\tcel.Function(\"missingHeader\",\n\t\t\tcel.Overload(\"missingHeader_map_string_string_string\",\n\t\t\t\t[]*cel.Type{cel.MapType(cel.StringType, cel.StringType), cel.StringType},\n\t\t\t\tcel.BoolType,\n\t\t\t\tcel.BinaryBinding(func(headers, key ref.Val) ref.Val {\n\t\t\t\t\t// Convert headers to a trait that supports Find\n\t\t\t\t\theadersMap, ok := headers.(traits.Indexer)\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn types.ValOrErr(headers, \"headers is not a map, but is %T\", headers)\n\t\t\t\t\t}\n\n\t\t\t\t\tkeyStr, ok := key.(types.String)\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn types.ValOrErr(key, \"key is not a string, but is %T\", key)\n\t\t\t\t\t}\n\n\t\t\t\t\tval := headersMap.Get(keyStr)\n\t\t\t\t\t// Check if the key is missing by testing for an error\n\t\t\t\t\tif types.IsError(val) {\n\t\t\t\t\t\treturn types.Bool(true) // header is missing\n\t\t\t\t\t}\n\t\t\t\t\treturn types.Bool(false) // header is present\n\t\t\t\t}),\n\t\t\t),\n\t\t),\n\n\t\tcel.Function(\"segments\",\n\t\t\tcel.Overload(\"segments_string_list_string\",\n\t\t\t\t[]*cel.Type{cel.StringType},\n\t\t\t\tcel.ListType(cel.StringType),\n\t\t\t\tcel.UnaryBinding(func(path ref.Val) ref.Val {\n\t\t\t\t\tpathStrType, ok := path.(types.String)\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn types.ValOrErr(path, \"path is not a string, but is %T\", path)\n\t\t\t\t\t}\n\n\t\t\t\t\tpathStr := string(pathStrType)\n\t\t\t\t\tif !strings.HasPrefix(pathStr, \"/\") {\n\t\t\t\t\t\treturn types.ValOrErr(path, \"path does not start with /\")\n\t\t\t\t\t}\n\n\t\t\t\t\tpathList := strings.Split(string(pathStr), \"/\")[1:]\n\n\t\t\t\t\treturn types.NewStringList(types.DefaultTypeAdapter, pathList)\n\t\t\t\t}),\n\t\t\t),\n\t\t),\n\t)\n}\n\n// NewThreshold creates a new CEL environment for threshold checking.\nfunc ThresholdEnvironment() (*cel.Env, error) {\n\treturn New(\n\t\tcel.Variable(\"weight\", cel.IntType),\n\t)\n}\n\nfunc New(opts ...cel.EnvOption) (*cel.Env, error) {\n\targs := []cel.EnvOption{\n\t\text.Strings(\n\t\t\text.StringsLocale(\"en_US\"),\n\t\t\text.StringsValidateFormatCalls(true),\n\t\t),\n\n\t\t// default all timestamps to UTC\n\t\tcel.DefaultUTCTimeZone(true),\n\n\t\t// Functions exposed to all CEL programs:\n\t\tcel.Function(\"randInt\",\n\t\t\tcel.Overload(\"randInt_int\",\n\t\t\t\t[]*cel.Type{cel.IntType},\n\t\t\t\tcel.IntType,\n\t\t\t\tcel.UnaryBinding(func(val ref.Val) ref.Val {\n\t\t\t\t\tn, ok := val.(types.Int)\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn types.ValOrErr(val, \"value is not an integer, but is %T\", val)\n\t\t\t\t\t}\n\n\t\t\t\t\treturn types.Int(rand.IntN(int(n)))\n\t\t\t\t}),\n\t\t\t),\n\t\t),\n\t}\n\n\targs = append(args, opts...)\n\treturn cel.NewEnv(args...)\n}\n\n// Compile takes CEL environment and syntax tree then emits an optimized\n// Program for execution.\nfunc Compile(env *cel.Env, src string) (cel.Program, error) {\n\tintermediate, iss := env.Compile(src)\n\tif iss != nil {\n\t\treturn nil, iss.Err()\n\t}\n\n\tast, iss := env.Check(intermediate)\n\tif iss != nil {\n\t\treturn nil, iss.Err()\n\t}\n\n\treturn env.Program(\n\t\tast,\n\t\tcel.EvalOptions(\n\t\t\t// optimize regular expressions right now instead of on the fly\n\t\t\tcel.OptOptimize,\n\t\t),\n\t)\n}\n"], ["/anubis/cmd/robots2policy/batch/batch_process.go", "/*\nBatch process robots.txt files from archives like https://github.com/nrjones8/robots-dot-txt-archive-bot/tree/master/data/cleaned\ninto Anubis CEL policies. Usage: go run batch_process.go \n*/\npackage main\n\nimport (\n\t\"fmt\"\n\t\"io/fs\"\n\t\"log\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\nfunc main() {\n\tif len(os.Args) < 2 {\n\t\tfmt.Println(\"Usage: go run batch_process.go \")\n\t\tfmt.Println(\"Example: go run batch_process.go ./cleaned\")\n\t\tos.Exit(1)\n\t}\n\n\tcleanedDir := os.Args[1]\n\toutputDir := \"generated_policies\"\n\n\t// Create output directory\n\tif err := os.MkdirAll(outputDir, 0755); err != nil {\n\t\tlog.Fatalf(\"Failed to create output directory: %v\", err)\n\t}\n\n\tcount := 0\n\terr := filepath.WalkDir(cleanedDir, func(path string, d fs.DirEntry, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Skip directories\n\t\tif d.IsDir() {\n\t\t\treturn nil\n\t\t}\n\n\t\t// Generate policy name from file path\n\t\trelPath, _ := filepath.Rel(cleanedDir, path)\n\t\tpolicyName := strings.ReplaceAll(relPath, \"/\", \"-\")\n\t\tpolicyName = strings.TrimSuffix(policyName, \"-robots.txt\")\n\t\tpolicyName = strings.ReplaceAll(policyName, \".\", \"-\")\n\n\t\toutputFile := filepath.Join(outputDir, policyName+\".yaml\")\n\n\t\tcmd := exec.Command(\"go\", \"run\", \"main.go\",\n\t\t\t\"-input\", path,\n\t\t\t\"-output\", outputFile,\n\t\t\t\"-name\", policyName,\n\t\t\t\"-format\", \"yaml\")\n\n\t\tif err := cmd.Run(); err != nil {\n\t\t\tfmt.Printf(\"Warning: Failed to process %s: %v\\n\", path, err)\n\t\t\treturn nil // Continue processing other files\n\t\t}\n\n\t\tcount++\n\t\tif count%100 == 0 {\n\t\t\tfmt.Printf(\"Processed %d files...\\n\", count)\n\t\t} else if count%10 == 0 {\n\t\t\tfmt.Print(\".\")\n\t\t}\n\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\tlog.Fatalf(\"Error walking directory: %v\", err)\n\t}\n\n\tfmt.Printf(\"Successfully processed %d robots.txt files\\n\", count)\n\tfmt.Printf(\"Generated policies saved to: %s/\\n\", outputDir)\n}\n"], ["/anubis/lib/policy/config/expressionorlist.go", "package config\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"slices\"\n\t\"strings\"\n)\n\nvar (\n\tErrExpressionOrListMustBeStringOrObject = errors.New(\"config: this must be a string or an object\")\n\tErrExpressionEmpty = errors.New(\"config: this expression is empty\")\n\tErrExpressionCantHaveBoth = errors.New(\"config: expression block can't contain multiple expression types\")\n)\n\ntype ExpressionOrList struct {\n\tExpression string `json:\"-\" yaml:\"-\"`\n\tAll []string `json:\"all,omitempty\" yaml:\"all,omitempty\"`\n\tAny []string `json:\"any,omitempty\" yaml:\"any,omitempty\"`\n}\n\nfunc (eol ExpressionOrList) String() string {\n\tswitch {\n\tcase len(eol.Expression) != 0:\n\t\treturn eol.Expression\n\tcase len(eol.All) != 0:\n\t\tvar sb strings.Builder\n\t\tfor i, pred := range eol.All {\n\t\t\tif i != 0 {\n\t\t\t\tfmt.Fprintf(&sb, \" && \")\n\t\t\t}\n\t\t\tfmt.Fprintf(&sb, \"( %s )\", pred)\n\t\t}\n\t\treturn sb.String()\n\tcase len(eol.Any) != 0:\n\t\tvar sb strings.Builder\n\t\tfor i, pred := range eol.Any {\n\t\t\tif i != 0 {\n\t\t\t\tfmt.Fprintf(&sb, \" || \")\n\t\t\t}\n\t\t\tfmt.Fprintf(&sb, \"( %s )\", pred)\n\t\t}\n\t\treturn sb.String()\n\t}\n\tpanic(\"this should not happen\")\n}\n\nfunc (eol ExpressionOrList) Equal(rhs *ExpressionOrList) bool {\n\tif eol.Expression != rhs.Expression {\n\t\treturn false\n\t}\n\n\tif !slices.Equal(eol.All, rhs.All) {\n\t\treturn false\n\t}\n\n\tif !slices.Equal(eol.Any, rhs.Any) {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\nfunc (eol *ExpressionOrList) MarshalYAML() (any, error) {\n\tswitch {\n\tcase len(eol.All) == 1 && len(eol.Any) == 0:\n\t\teol.Expression = eol.All[0]\n\t\teol.All = nil\n\tcase len(eol.Any) == 1 && len(eol.All) == 0:\n\t\teol.Expression = eol.Any[0]\n\t\teol.Any = nil\n\t}\n\n\tif eol.Expression != \"\" {\n\t\treturn eol.Expression, nil\n\t}\n\n\ttype RawExpressionOrList ExpressionOrList\n\treturn RawExpressionOrList(*eol), nil\n}\n\nfunc (eol *ExpressionOrList) MarshalJSON() ([]byte, error) {\n\tswitch {\n\tcase len(eol.All) == 1 && len(eol.Any) == 0:\n\t\teol.Expression = eol.All[0]\n\t\teol.All = nil\n\tcase len(eol.Any) == 1 && len(eol.All) == 0:\n\t\teol.Expression = eol.Any[0]\n\t\teol.Any = nil\n\t}\n\n\tif eol.Expression != \"\" {\n\t\treturn json.Marshal(string(eol.Expression))\n\t}\n\n\ttype RawExpressionOrList ExpressionOrList\n\tval := RawExpressionOrList(*eol)\n\treturn json.Marshal(val)\n}\n\nfunc (eol *ExpressionOrList) UnmarshalJSON(data []byte) error {\n\tswitch string(data[0]) {\n\tcase `\"`: // string\n\t\treturn json.Unmarshal(data, &eol.Expression)\n\tcase \"{\": // object\n\t\ttype RawExpressionOrList ExpressionOrList\n\t\tvar val RawExpressionOrList\n\t\tif err := json.Unmarshal(data, &val); err != nil {\n\t\t\treturn err\n\t\t}\n\t\teol.All = val.All\n\t\teol.Any = val.Any\n\n\t\treturn nil\n\t}\n\n\treturn ErrExpressionOrListMustBeStringOrObject\n}\n\nfunc (eol *ExpressionOrList) Valid() error {\n\tif eol.Expression == \"\" && len(eol.All) == 0 && len(eol.Any) == 0 {\n\t\treturn ErrExpressionEmpty\n\t}\n\tif len(eol.All) != 0 && len(eol.Any) != 0 {\n\t\treturn ErrExpressionCantHaveBoth\n\t}\n\n\treturn nil\n}\n"], ["/anubis/internal/ogtags/cache.go", "package ogtags\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"log/slog\"\n\t\"net/url\"\n\t\"syscall\"\n)\n\n// GetOGTags is the main function that retrieves Open Graph tags for a URL\nfunc (c *OGTagCache) GetOGTags(ctx context.Context, url *url.URL, originalHost string) (map[string]string, error) {\n\tif url == nil {\n\t\treturn nil, errors.New(\"nil URL provided, cannot fetch OG tags\")\n\t}\n\n\tif len(c.ogOverride) != 0 {\n\t\treturn c.ogOverride, nil\n\t}\n\n\ttarget := c.getTarget(url)\n\tcacheKey := c.generateCacheKey(target, originalHost)\n\n\t// Check cache first\n\tif cachedTags := c.checkCache(ctx, cacheKey); cachedTags != nil {\n\t\treturn cachedTags, nil\n\t}\n\n\t// Fetch HTML content, passing the original host\n\tdoc, err := c.fetchHTMLDocumentWithCache(ctx, target, originalHost, cacheKey)\n\tif errors.Is(err, syscall.ECONNREFUSED) {\n\t\tslog.Debug(\"Connection refused, returning empty tags\")\n\t\treturn nil, nil\n\t} else if errors.Is(err, ErrOgHandled) {\n\t\t// Error was handled in fetchHTMLDocument, return empty tags\n\t\treturn nil, nil\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Extract OG tags\n\togTags := c.extractOGTags(doc)\n\n\t// Store in cache\n\tc.cache.Set(ctx, cacheKey, ogTags, c.ogTimeToLive)\n\n\treturn ogTags, nil\n}\n\nfunc (c *OGTagCache) generateCacheKey(target string, originalHost string) string {\n\tvar cacheKey string\n\n\tif c.ogCacheConsiderHost {\n\t\tcacheKey = target + \"|\" + originalHost\n\t} else {\n\t\tcacheKey = target\n\t}\n\treturn cacheKey\n}\n\n// checkCache checks if we have the tags cached and returns them if so\nfunc (c *OGTagCache) checkCache(ctx context.Context, cacheKey string) map[string]string {\n\tif cachedTags, err := c.cache.Get(ctx, cacheKey); err == nil {\n\t\tslog.Debug(\"cache hit\", \"tags\", cachedTags)\n\t\treturn cachedTags\n\t}\n\tslog.Debug(\"cache miss\", \"url\", cacheKey)\n\treturn nil\n}\n"], ["/anubis/lib/thoth/thothmock/iptoasn.go", "package thothmock\n\nimport (\n\t\"context\"\n\t\"net/netip\"\n\n\tiptoasnv1 \"github.com/TecharoHQ/thoth-proto/gen/techaro/thoth/iptoasn/v1\"\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/status\"\n)\n\nfunc MockIpToASNService() *IpToASNService {\n\tresponses := map[string]*iptoasnv1.LookupResponse{\n\t\t\"127.0.0.1\": {Announced: false},\n\t\t\"::1\": {Announced: false},\n\t\t\"10.10.10.10\": {\n\t\t\tAnnounced: true,\n\t\t\tAsNumber: 13335,\n\t\t\tCidr: []string{\"1.1.1.0/24\"},\n\t\t\tCountryCode: \"US\",\n\t\t\tDescription: \"Cloudflare\",\n\t\t},\n\t\t\"2.2.2.2\": {\n\t\t\tAnnounced: true,\n\t\t\tAsNumber: 420,\n\t\t\tCidr: []string{\"2.2.2.0/24\"},\n\t\t\tCountryCode: \"CA\",\n\t\t\tDescription: \"test canada\",\n\t\t},\n\t\t\"1.1.1.1\": {\n\t\t\tAnnounced: true,\n\t\t\tAsNumber: 13335,\n\t\t\tCidr: []string{\"1.1.1.0/24\"},\n\t\t\tCountryCode: \"US\",\n\t\t\tDescription: \"Cloudflare\",\n\t\t},\n\t}\n\n\treturn &IpToASNService{Responses: responses}\n}\n\ntype IpToASNService struct {\n\tiptoasnv1.UnimplementedIpToASNServiceServer\n\tResponses map[string]*iptoasnv1.LookupResponse\n}\n\nfunc (ip2asn *IpToASNService) Lookup(ctx context.Context, lr *iptoasnv1.LookupRequest, opts ...grpc.CallOption) (*iptoasnv1.LookupResponse, error) {\n\tif _, err := netip.ParseAddr(lr.GetIpAddress()); err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, ok := ip2asn.Responses[lr.GetIpAddress()]\n\tif !ok {\n\t\treturn nil, status.Error(codes.NotFound, \"IP address not found in mock\")\n\t}\n\n\treturn resp, nil\n}\n"], ["/anubis/lib/store/memory/memory.go", "package memory\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis/decaymap\"\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n)\n\ntype factory struct{}\n\nfunc (factory) Build(ctx context.Context, _ json.RawMessage) (store.Interface, error) {\n\treturn New(ctx), nil\n}\n\nfunc (factory) Valid(json.RawMessage) error { return nil }\n\nfunc init() {\n\tstore.Register(\"memory\", factory{})\n}\n\ntype impl struct {\n\tstore *decaymap.Impl[string, []byte]\n}\n\nfunc (i *impl) Delete(_ context.Context, key string) error {\n\tif !i.store.Delete(key) {\n\t\treturn fmt.Errorf(\"%w: %q\", store.ErrNotFound, key)\n\t}\n\n\treturn nil\n}\n\nfunc (i *impl) Get(_ context.Context, key string) ([]byte, error) {\n\tresult, ok := i.store.Get(key)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"%w: %q\", store.ErrNotFound, key)\n\t}\n\n\treturn result, nil\n}\n\nfunc (i *impl) Set(_ context.Context, key string, value []byte, expiry time.Duration) error {\n\ti.store.Set(key, value, expiry)\n\treturn nil\n}\n\nfunc (i *impl) cleanupThread(ctx context.Context) {\n\tt := time.NewTicker(5 * time.Minute)\n\tdefer t.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase <-t.C:\n\t\t\ti.store.Cleanup()\n\t\t}\n\t}\n}\n\n// New creates a simple in-memory store. This will not scale to multiple Anubis instances.\nfunc New(ctx context.Context) store.Interface {\n\tresult := &impl{\n\t\tstore: decaymap.New[string, []byte](),\n\t}\n\n\tgo result.cleanupThread(ctx)\n\n\treturn result\n}\n"], ["/anubis/lib/policy/config/opengraph.go", "package config\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"time\"\n)\n\nvar (\n\tErrInvalidOpenGraphConfig = errors.New(\"config.OpenGraph: invalid OpenGraph configuration\")\n\tErrOpenGraphTTLDoesNotParse = errors.New(\"config.OpenGraph: ttl does not parse as a Duration, see https://pkg.go.dev/time#ParseDuration (formatted like 5m -> 5 minutes, 2h -> 2 hours, etc)\")\n\tErrOpenGraphMissingProperty = errors.New(\"config.OpenGraph: default opengraph tags missing a property\")\n)\n\ntype openGraphFileConfig struct {\n\tEnabled bool `json:\"enabled\" yaml:\"enabled\"`\n\tConsiderHost bool `json:\"considerHost\" yaml:\"enabled\"`\n\tTimeToLive string `json:\"ttl\" yaml:\"ttl\"`\n\tOverride map[string]string `json:\"override,omitempty\" yaml:\"override,omitempty\"`\n}\n\ntype OpenGraph struct {\n\tEnabled bool `json:\"enabled\" yaml:\"enabled\"`\n\tConsiderHost bool `json:\"considerHost\" yaml:\"enabled\"`\n\tOverride map[string]string `json:\"override,omitempty\" yaml:\"override,omitempty\"`\n\tTimeToLive time.Duration `json:\"ttl\" yaml:\"ttl\"`\n}\n\nfunc (og *openGraphFileConfig) Valid() error {\n\tvar errs []error\n\n\tif _, err := time.ParseDuration(og.TimeToLive); err != nil {\n\t\terrs = append(errs, fmt.Errorf(\"%w: ParseDuration(%q) returned: %w\", ErrOpenGraphTTLDoesNotParse, og.TimeToLive, err))\n\t}\n\n\tif len(og.Override) != 0 {\n\t\tfor _, tag := range []string{\n\t\t\t\"og:title\",\n\t\t} {\n\t\t\tif _, ok := og.Override[tag]; !ok {\n\t\t\t\terrs = append(errs, fmt.Errorf(\"%w: %s\", ErrOpenGraphMissingProperty, tag))\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn errors.Join(ErrInvalidOpenGraphConfig, errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n"], ["/anubis/lib/policy/config/impressum.go", "package config\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n)\n\nvar ErrMissingValue = errors.New(\"config: missing value\")\n\ntype Impressum struct {\n\tFooter string `json:\"footer\" yaml:\"footer\"`\n\tPage ImpressumPage `json:\"page\" yaml:\"page\"`\n}\n\nfunc (i Impressum) Render(_ context.Context, w io.Writer) error {\n\tif _, err := fmt.Fprint(w, i.Footer); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (i Impressum) Valid() error {\n\tvar errs []error\n\n\tif len(i.Footer) == 0 {\n\t\terrs = append(errs, fmt.Errorf(\"%w: impressum footer must be defined\", ErrMissingValue))\n\t}\n\n\tif err := i.Page.Valid(); err != nil {\n\t\terrs = append(errs, err)\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn errors.Join(errs...)\n\t}\n\n\treturn nil\n}\n\ntype ImpressumPage struct {\n\tTitle string `json:\"title\" yaml:\"title\"`\n\tBody string `json:\"body\" yaml:\"body\"`\n}\n\nfunc (ip ImpressumPage) Render(_ context.Context, w io.Writer) error {\n\tif _, err := fmt.Fprint(w, ip.Body); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (ip ImpressumPage) Valid() error {\n\tvar errs []error\n\n\tif len(ip.Title) == 0 {\n\t\terrs = append(errs, fmt.Errorf(\"%w: impressum page title must be defined\", ErrMissingValue))\n\t}\n\n\tif len(ip.Body) == 0 {\n\t\terrs = append(errs, fmt.Errorf(\"%w: impressum body title must be defined\", ErrMissingValue))\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn errors.Join(errs...)\n\t}\n\n\treturn nil\n}\n"], ["/anubis/lib/policy/expressions/loadavg.go", "package expressions\n\nimport (\n\t\"context\"\n\t\"log/slog\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/shirou/gopsutil/v4/load\"\n)\n\ntype loadAvg struct {\n\tlock sync.RWMutex\n\tdata *load.AvgStat\n}\n\nfunc (l *loadAvg) updateThread(ctx context.Context) {\n\tticker := time.NewTicker(15 * time.Second)\n\tdefer ticker.Stop()\n\n\tl.update()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tl.update()\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (l *loadAvg) update() {\n\tl.lock.Lock()\n\tdefer l.lock.Unlock()\n\n\tvar err error\n\tl.data, err = load.Avg()\n\tif err != nil {\n\t\tslog.Debug(\"can't get load average\", \"err\", err)\n\t}\n}\n\nvar (\n\tglobalLoadAvg *loadAvg\n)\n\nfunc init() {\n\tglobalLoadAvg = &loadAvg{}\n\tgo globalLoadAvg.updateThread(context.Background())\n}\n\nfunc Load1() float64 {\n\tglobalLoadAvg.lock.RLock()\n\tdefer globalLoadAvg.lock.RUnlock()\n\treturn globalLoadAvg.data.Load1\n}\n\nfunc Load5() float64 {\n\tglobalLoadAvg.lock.RLock()\n\tdefer globalLoadAvg.lock.RUnlock()\n\treturn globalLoadAvg.data.Load5\n}\n\nfunc Load15() float64 {\n\tglobalLoadAvg.lock.RLock()\n\tdefer globalLoadAvg.lock.RUnlock()\n\treturn globalLoadAvg.data.Load15\n}\n"], ["/anubis/lib/challenge/interface.go", "package challenge\n\nimport (\n\t\"log/slog\"\n\t\"net/http\"\n\t\"sort\"\n\t\"sync\"\n\n\t\"github.com/TecharoHQ/anubis/lib/policy\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n\t\"github.com/a-h/templ\"\n)\n\nvar (\n\tregistry map[string]Impl = map[string]Impl{}\n\tregLock sync.RWMutex\n)\n\nfunc Register(name string, impl Impl) {\n\tregLock.Lock()\n\tdefer regLock.Unlock()\n\n\tregistry[name] = impl\n}\n\nfunc Get(name string) (Impl, bool) {\n\tregLock.RLock()\n\tdefer regLock.RUnlock()\n\tresult, ok := registry[name]\n\treturn result, ok\n}\n\nfunc Methods() []string {\n\tregLock.RLock()\n\tdefer regLock.RUnlock()\n\tvar result []string\n\tfor method := range registry {\n\t\tresult = append(result, method)\n\t}\n\tsort.Strings(result)\n\treturn result\n}\n\ntype IssueInput struct {\n\tImpressum *config.Impressum\n\tRule *policy.Bot\n\tChallenge *Challenge\n\tOGTags map[string]string\n\tStore store.Interface\n}\n\ntype ValidateInput struct {\n\tRule *policy.Bot\n\tChallenge *Challenge\n\tStore store.Interface\n}\n\ntype Impl interface {\n\t// Setup registers any additional routes with the Impl for assets or API routes.\n\tSetup(mux *http.ServeMux)\n\n\t// Issue a new challenge to the user, called by the Anubis.\n\tIssue(r *http.Request, lg *slog.Logger, in *IssueInput) (templ.Component, error)\n\n\t// Validate a challenge, making sure that it passes muster.\n\tValidate(r *http.Request, lg *slog.Logger, in *ValidateInput) error\n}\n"], ["/anubis/lib/store/interface.go", "package store\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"time\"\n)\n\nvar (\n\t// ErrNotFound is returned when the store implementation cannot find the value\n\t// for a given key.\n\tErrNotFound = errors.New(\"store: key not found\")\n\n\t// ErrCantDecode is returned when a store adaptor cannot decode the store format\n\t// to a value used by the code.\n\tErrCantDecode = errors.New(\"store: can't decode value\")\n\n\t// ErrCantEncode is returned when a store adaptor cannot encode the value into\n\t// the format that the store uses.\n\tErrCantEncode = errors.New(\"store: can't encode value\")\n\n\t// ErrBadConfig is returned when a store adaptor's configuration is invalid.\n\tErrBadConfig = errors.New(\"store: configuration is invalid\")\n)\n\n// Interface defines the calls that Anubis uses for storage in a local or remote\n// datastore. This can be implemented with an in-memory, on-disk, or in-database\n// storage backend.\ntype Interface interface {\n\t// Delete removes a value from the store by key.\n\tDelete(ctx context.Context, key string) error\n\n\t// Get returns the value of a key assuming that value exists and has not expired.\n\tGet(ctx context.Context, key string) ([]byte, error)\n\n\t// Set puts a value into the store that expires according to its expiry.\n\tSet(ctx context.Context, key string, value []byte, expiry time.Duration) error\n}\n\nfunc z[T any]() T { return *new(T) }\n\ntype JSON[T any] struct {\n\tUnderlying Interface\n\tPrefix string\n}\n\nfunc (j *JSON[T]) Delete(ctx context.Context, key string) error {\n\tif j.Prefix != \"\" {\n\t\tkey = j.Prefix + key\n\t}\n\n\treturn j.Underlying.Delete(ctx, key)\n}\n\nfunc (j *JSON[T]) Get(ctx context.Context, key string) (T, error) {\n\tif j.Prefix != \"\" {\n\t\tkey = j.Prefix + key\n\t}\n\n\tdata, err := j.Underlying.Get(ctx, key)\n\tif err != nil {\n\t\treturn z[T](), err\n\t}\n\n\tvar result T\n\tif err := json.Unmarshal(data, &result); err != nil {\n\t\treturn z[T](), fmt.Errorf(\"%w: %w\", ErrCantDecode, err)\n\t}\n\n\treturn result, nil\n}\n\nfunc (j *JSON[T]) Set(ctx context.Context, key string, value T, expiry time.Duration) error {\n\tif j.Prefix != \"\" {\n\t\tkey = j.Prefix + key\n\t}\n\n\tdata, err := json.Marshal(value)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%w: %w\", ErrCantEncode, err)\n\t}\n\n\tif err := j.Underlying.Set(ctx, key, data, expiry); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n"], ["/anubis/internal/ja4h.go", "package internal\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/lum8rjack/go-ja4h\"\n)\n\nfunc JA4H(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tr.Header.Add(\"X-Http-Fingerprint-JA4H\", ja4h.JA4H(r))\n\t\tnext.ServeHTTP(w, r)\n\t})\n}\n"], ["/anubis/lib/policy/bot.go", "package policy\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/TecharoHQ/anubis/internal\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/checker\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n)\n\ntype Bot struct {\n\tRules checker.Impl\n\tChallenge *config.ChallengeRules\n\tWeight *config.Weight\n\tName string\n\tAction config.Rule\n}\n\nfunc (b Bot) Hash() string {\n\treturn internal.FastHash(fmt.Sprintf(\"%s::%s\", b.Name, b.Rules.Hash()))\n}\n"], ["/anubis/utils/cmd/backoff-retry/main.go", "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"os\"\n\t\"os/exec\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar (\n\tstartWait = flag.Duration(\"start-wait\", 250*time.Millisecond, \"amount of time to start with exponential backoff\")\n\ttryCount = flag.Int(\"try-count\", 5, \"number of retries\")\n)\n\nfunc main() {\n\tflag.Parse()\n\n\tcmdStr := strings.Join(flag.Args(), \" \")\n\twait := *startWait\n\n\tfor i := range make([]struct{}, *tryCount) {\n\t\tslog.Info(\"executing\", \"try\", i+1, \"wait\", wait, \"cmd\", cmdStr)\n\n\t\tcmd := exec.Command(\"sh\", \"-c\", cmdStr)\n\t\tcmd.Stdin = nil\n\t\tcmd.Stdout = os.Stdout\n\t\tcmd.Stderr = os.Stderr\n\n\t\tif err := cmd.Run(); err != nil {\n\t\t\ttime.Sleep(wait)\n\t\t\twait = wait * 2\n\t\t} else {\n\t\t\tos.Exit(0)\n\t\t}\n\t}\n\n\tfmt.Printf(\"giving up after %d tries\\n\", *tryCount)\n\tos.Exit(1)\n}\n"], ["/anubis/lib/policy/thresholds.go", "package policy\n\nimport (\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/expressions\"\n\t\"github.com/google/cel-go/cel\"\n)\n\ntype Threshold struct {\n\tconfig.Threshold\n\tProgram cel.Program\n}\n\nfunc ParsedThresholdFromConfig(t config.Threshold) (*Threshold, error) {\n\tresult := &Threshold{\n\t\tThreshold: t,\n\t}\n\n\tenv, err := expressions.ThresholdEnvironment()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tprogram, err := expressions.Compile(env, t.Expression.String())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult.Program = program\n\n\treturn result, nil\n}\n\ntype ThresholdRequest struct {\n\tWeight int\n}\n\nfunc (tr *ThresholdRequest) Parent() cel.Activation { return nil }\n\nfunc (tr *ThresholdRequest) ResolveName(name string) (any, bool) {\n\tswitch name {\n\tcase \"weight\":\n\t\treturn tr.Weight, true\n\tdefault:\n\t\treturn nil, false\n\t}\n}\n"], ["/anubis/lib/policy/checkresult.go", "package policy\n\nimport (\n\t\"log/slog\"\n\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n)\n\ntype CheckResult struct {\n\tName string\n\tRule config.Rule\n\tWeight int\n}\n\nfunc (cr CheckResult) LogValue() slog.Value {\n\treturn slog.GroupValue(\n\t\tslog.String(\"name\", cr.Name),\n\t\tslog.String(\"rule\", string(cr.Rule)),\n\t\tslog.Int(\"weight\", cr.Weight),\n\t)\n}\n"], ["/anubis/lib/policy/config/asn.go", "package config\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\nvar (\n\tErrPrivateASN = errors.New(\"bot.ASNs: you have specified a private use ASN\")\n)\n\ntype ASNs struct {\n\tMatch []uint32 `json:\"match\"`\n}\n\nfunc (a *ASNs) Valid() error {\n\tvar errs []error\n\n\tfor _, asn := range a.Match {\n\t\tif isPrivateASN(asn) {\n\t\t\terrs = append(errs, fmt.Errorf(\"%w: %d is private (see RFC 6996)\", ErrPrivateASN, asn))\n\t\t}\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"bot.ASNs: invalid ASN settings: %w\", errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n\n// isPrivateASN checks if an ASN is in the private use area.\n//\n// Based on RFC 6996 and IANA allocations.\nfunc isPrivateASN(asn uint32) bool {\n\tswitch {\n\tcase asn >= 64512 && asn <= 65534:\n\t\treturn true\n\tcase asn >= 4200000000 && asn <= 4294967294:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n"], ["/anubis/lib/policy/config/geoip.go", "package config\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"regexp\"\n\t\"strings\"\n)\n\nvar (\n\tcountryCodeRegexp = regexp.MustCompile(`^[a-zA-Z]{2}$`)\n\n\tErrNotCountryCode = errors.New(\"config.Bot: invalid country code\")\n)\n\ntype GeoIP struct {\n\tCountries []string `json:\"countries\"`\n}\n\nfunc (g *GeoIP) Valid() error {\n\tvar errs []error\n\n\tfor i, cc := range g.Countries {\n\t\tif !countryCodeRegexp.MatchString(cc) {\n\t\t\terrs = append(errs, fmt.Errorf(\"%w: %s\", ErrNotCountryCode, cc))\n\t\t}\n\n\t\tg.Countries[i] = strings.ToLower(cc)\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"bot.GeoIP: invalid GeoIP settings: %w\", errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n"], ["/anubis/xess/xess.go", "// Package xess vendors a copy of Xess and makes it available at /.xess/xess.css\n//\n// This is intended to be used as a vendored package in other projects.\npackage xess\n\nimport (\n\t\"embed\"\n\t\"net/http\"\n\t\"path/filepath\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/TecharoHQ/anubis/internal\"\n)\n\nvar (\n\t//go:embed *.css static\n\tStatic embed.FS\n\n\tURL = \"/.within.website/x/xess/xess.css\"\n)\n\nfunc init() {\n\tMount(http.DefaultServeMux)\n\n\t//goland:noinspection GoBoolExpressions\n\tif anubis.Version != \"devel\" {\n\t\tURL = filepath.Join(filepath.Dir(URL), \"xess.min.css\")\n\t}\n\n\tURL = URL + \"?cachebuster=\" + anubis.Version\n}\n\n// Mount registers the xess static file handlers on the given mux\nfunc Mount(mux *http.ServeMux) {\n\tprefix := anubis.BasePrefix + \"/.within.website/x/xess/\"\n\n\tmux.Handle(prefix, internal.UnchangingCache(http.StripPrefix(prefix, http.FileServerFS(Static))))\n}\n"], ["/anubis/lib/challenge/metrics.go", "package challenge\n\nimport (\n\t\"math\"\n\n\t\"github.com/prometheus/client_golang/prometheus\"\n\t\"github.com/prometheus/client_golang/prometheus/promauto\"\n)\n\nvar TimeTaken = promauto.NewHistogramVec(prometheus.HistogramOpts{\n\tName: \"anubis_time_taken\",\n\tHelp: \"The time taken for a browser to generate a response (milliseconds)\",\n\tBuckets: prometheus.ExponentialBucketsRange(1, math.Pow(2, 20), 20),\n}, []string{\"method\"})\n"], ["/anubis/anubis.go", "// Package anubis contains the version number of Anubis.\npackage anubis\n\nimport \"time\"\n\n// Version is the current version of Anubis.\n//\n// This variable is set at build time using the -X linker flag. If not set,\n// it defaults to \"devel\".\nvar Version = \"devel\"\n\n// CookieName is the name of the cookie that Anubis uses in order to validate\n// access.\nvar CookieName = \"techaro.lol-anubis-auth\"\n\n// TestCookieName is the name of the cookie that Anubis uses in order to check\n// if cookies are enabled on the client's browser.\nvar TestCookieName = \"techaro.lol-anubis-cookie-verification\"\n\n// CookieDefaultExpirationTime is the amount of time before the cookie/JWT expires.\nconst CookieDefaultExpirationTime = 7 * 24 * time.Hour\n\n// BasePrefix is a global prefix for all Anubis endpoints. Can be emptied to remove the prefix entirely.\nvar BasePrefix = \"\"\n\n// StaticPath is the location where all static Anubis assets are located.\nconst StaticPath = \"/.within.website/x/cmd/anubis/\"\n\n// APIPrefix is the location where all Anubis API endpoints are located.\nconst APIPrefix = \"/.within.website/x/cmd/anubis/api/\"\n\n// DefaultDifficulty is the default \"difficulty\" (number of leading zeroes)\n// that must be met by the client in order to pass the challenge.\nconst DefaultDifficulty = 4\n\n// ForcedLanguage is the language being used instead of the one of the request's Accept-Language header\n// if being set.\nvar ForcedLanguage = \"\"\n"], ["/anubis/lib/policy/checker/checker.go", "// Package checker defines the Checker interface and a helper utility to avoid import cycles.\npackage checker\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"strings\"\n\n\t\"github.com/TecharoHQ/anubis/internal\"\n)\n\ntype Impl interface {\n\tCheck(*http.Request) (bool, error)\n\tHash() string\n}\n\ntype List []Impl\n\nfunc (l List) Check(r *http.Request) (bool, error) {\n\tfor _, c := range l {\n\t\tok, err := c.Check(r)\n\t\tif err != nil {\n\t\t\treturn ok, err\n\t\t}\n\t\tif ok {\n\t\t\treturn ok, nil\n\t\t}\n\t}\n\n\treturn false, nil\n}\n\nfunc (l List) Hash() string {\n\tvar sb strings.Builder\n\n\tfor _, c := range l {\n\t\tfmt.Fprintln(&sb, c.Hash())\n\t}\n\n\treturn internal.FastHash(sb.String())\n}\n"], ["/anubis/internal/dnsbl/droneblresponse_string.go", "// Code generated by \"stringer -type=DroneBLResponse\"; DO NOT EDIT.\n\npackage dnsbl\n\nimport \"strconv\"\n\nfunc _() {\n\t// An \"invalid array index\" compiler error signifies that the constant values have changed.\n\t// Re-run the stringer command to generate them again.\n\tvar x [1]struct{}\n\t_ = x[AllGood-0]\n\t_ = x[IRCDrone-3]\n\t_ = x[Bottler-5]\n\t_ = x[UnknownSpambotOrDrone-6]\n\t_ = x[DDOSDrone-7]\n\t_ = x[SOCKSProxy-8]\n\t_ = x[HTTPProxy-9]\n\t_ = x[ProxyChain-10]\n\t_ = x[OpenProxy-11]\n\t_ = x[OpenDNSResolver-12]\n\t_ = x[BruteForceAttackers-13]\n\t_ = x[OpenWingateProxy-14]\n\t_ = x[CompromisedRouter-15]\n\t_ = x[AutoRootingWorms-16]\n\t_ = x[AutoDetectedBotIP-17]\n\t_ = x[Unknown-255]\n}\n\nconst (\n\t_DroneBLResponse_name_0 = \"AllGood\"\n\t_DroneBLResponse_name_1 = \"IRCDrone\"\n\t_DroneBLResponse_name_2 = \"BottlerUnknownSpambotOrDroneDDOSDroneSOCKSProxyHTTPProxyProxyChainOpenProxyOpenDNSResolverBruteForceAttackersOpenWingateProxyCompromisedRouterAutoRootingWormsAutoDetectedBotIP\"\n\t_DroneBLResponse_name_3 = \"Unknown\"\n)\n\nvar (\n\t_DroneBLResponse_index_2 = [...]uint8{0, 7, 28, 37, 47, 56, 66, 75, 90, 109, 125, 142, 158, 175}\n)\n\nfunc (i DroneBLResponse) String() string {\n\tswitch {\n\tcase i == 0:\n\t\treturn _DroneBLResponse_name_0\n\tcase i == 3:\n\t\treturn _DroneBLResponse_name_1\n\tcase 5 <= i && i <= 17:\n\t\ti -= 5\n\t\treturn _DroneBLResponse_name_2[_DroneBLResponse_index_2[i]:_DroneBLResponse_index_2[i+1]]\n\tcase i == 255:\n\t\treturn _DroneBLResponse_name_3\n\tdefault:\n\t\treturn \"DroneBLResponse(\" + strconv.FormatInt(int64(i), 10) + \")\"\n\t}\n}\n"], ["/anubis/internal/health.go", "package internal\n\nimport (\n\t\"context\"\n\n\t\"google.golang.org/grpc/health\"\n\thealthv1 \"google.golang.org/grpc/health/grpc_health_v1\"\n)\n\nvar HealthSrv = health.NewServer()\n\nfunc SetHealth(svc string, status healthv1.HealthCheckResponse_ServingStatus) {\n\tHealthSrv.SetServingStatus(svc, status)\n}\n\nfunc GetHealth(svc string) (healthv1.HealthCheckResponse_ServingStatus, bool) {\n\tst, err := HealthSrv.Check(context.Background(), &healthv1.HealthCheckRequest{\n\t\tService: svc,\n\t})\n\tif err != nil {\n\t\treturn healthv1.HealthCheckResponse_UNKNOWN, false\n\t}\n\n\treturn st.GetStatus(), true\n}\n"], ["/anubis/lib/policy/expressions/url_values.go", "package expressions\n\nimport (\n\t\"errors\"\n\t\"net/url\"\n\t\"reflect\"\n\t\"strings\"\n\n\t\"github.com/google/cel-go/common/types\"\n\t\"github.com/google/cel-go/common/types/ref\"\n\t\"github.com/google/cel-go/common/types/traits\"\n)\n\nvar ErrNotImplemented = errors.New(\"expressions: not implemented\")\n\n// URLValues is a type wrapper to expose url.Values into CEL programs.\ntype URLValues struct {\n\turl.Values\n}\n\nfunc (u URLValues) ConvertToNative(typeDesc reflect.Type) (any, error) {\n\treturn nil, ErrNotImplemented\n}\n\nfunc (u URLValues) ConvertToType(typeVal ref.Type) ref.Val {\n\tswitch typeVal {\n\tcase types.MapType:\n\t\treturn u\n\tcase types.TypeType:\n\t\treturn types.MapType\n\t}\n\n\treturn types.NewErr(\"can't convert from %q to %q\", types.MapType, typeVal)\n}\n\nfunc (u URLValues) Equal(other ref.Val) ref.Val {\n\treturn types.Bool(false) // We don't want to compare header maps\n}\n\nfunc (u URLValues) Type() ref.Type {\n\treturn types.MapType\n}\n\nfunc (u URLValues) Value() any { return u }\n\nfunc (u URLValues) Find(key ref.Val) (ref.Val, bool) {\n\tk, ok := key.(types.String)\n\tif !ok {\n\t\treturn nil, false\n\t}\n\n\tif _, ok := u.Values[string(k)]; !ok {\n\t\treturn nil, false\n\t}\n\n\treturn types.String(strings.Join(u.Values[string(k)], \",\")), true\n}\n\nfunc (u URLValues) Contains(key ref.Val) ref.Val {\n\t_, ok := u.Find(key)\n\treturn types.Bool(ok)\n}\n\nfunc (u URLValues) Get(key ref.Val) ref.Val {\n\tresult, ok := u.Find(key)\n\tif !ok {\n\t\treturn types.ValOrErr(result, \"no such key: %v\", key)\n\t}\n\treturn result\n}\n\nfunc (u URLValues) Iterator() traits.Iterator { panic(\"TODO(Xe): implement me\") }\n\nfunc (u URLValues) IsZeroValue() bool {\n\treturn len(u.Values) == 0\n}\n\nfunc (u URLValues) Size() ref.Val { return types.Int(len(u.Values)) }\n"], ["/anubis/lib/challenge/error.go", "package challenge\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net/http\"\n)\n\nvar (\n\tErrFailed = errors.New(\"challenge: user failed challenge\")\n\tErrMissingField = errors.New(\"challenge: missing field\")\n\tErrInvalidFormat = errors.New(\"challenge: field has invalid format\")\n)\n\nfunc NewError(verb, publicReason string, privateReason error) *Error {\n\treturn &Error{\n\t\tVerb: verb,\n\t\tPublicReason: publicReason,\n\t\tPrivateReason: privateReason,\n\t\tStatusCode: http.StatusForbidden,\n\t}\n}\n\ntype Error struct {\n\tPrivateReason error\n\tVerb string\n\tPublicReason string\n\tStatusCode int\n}\n\nfunc (e *Error) Error() string {\n\treturn fmt.Sprintf(\"challenge: error when processing challenge: %s: %v\", e.Verb, e.PrivateReason)\n}\n\nfunc (e *Error) Unwrap() error {\n\treturn e.PrivateReason\n}\n"], ["/anubis/decaymap/decaymap.go", "package decaymap\n\nimport (\n\t\"sync\"\n\t\"time\"\n)\n\nfunc Zilch[T any]() T {\n\tvar zero T\n\treturn zero\n}\n\n// Impl is a lazy key->value map. It's a wrapper around a map and a mutex. If values exceed their time-to-live, they are pruned at Get time.\ntype Impl[K comparable, V any] struct {\n\tdata map[K]decayMapEntry[V]\n\tlock sync.RWMutex\n}\n\ntype decayMapEntry[V any] struct {\n\tValue V\n\texpiry time.Time\n}\n\n// New creates a new DecayMap of key type K and value type V.\n//\n// Key types must be comparable to work with maps.\nfunc New[K comparable, V any]() *Impl[K, V] {\n\treturn &Impl[K, V]{\n\t\tdata: make(map[K]decayMapEntry[V]),\n\t}\n}\n\n// expire forcibly expires a key by setting its time-to-live one second in the past.\nfunc (m *Impl[K, V]) expire(key K) bool {\n\tm.lock.RLock()\n\tval, ok := m.data[key]\n\tm.lock.RUnlock()\n\n\tif !ok {\n\t\treturn false\n\t}\n\n\tm.lock.Lock()\n\tval.expiry = time.Now().Add(-1 * time.Second)\n\tm.data[key] = val\n\tm.lock.Unlock()\n\n\treturn true\n}\n\n// Delete a value from the DecayMap by key.\n//\n// If the value does not exist, return false. Return true after\n// deletion.\nfunc (m *Impl[K, V]) Delete(key K) bool {\n\tm.lock.RLock()\n\t_, ok := m.data[key]\n\tm.lock.RUnlock()\n\n\tif !ok {\n\t\treturn false\n\t}\n\n\tm.lock.Lock()\n\tdelete(m.data, key)\n\tm.lock.Unlock()\n\n\treturn true\n}\n\n// Get gets a value from the DecayMap by key.\n//\n// If a value has expired, forcibly delete it if it was not updated.\nfunc (m *Impl[K, V]) Get(key K) (V, bool) {\n\tm.lock.RLock()\n\tvalue, ok := m.data[key]\n\tm.lock.RUnlock()\n\n\tif !ok {\n\t\treturn Zilch[V](), false\n\t}\n\n\tif time.Now().After(value.expiry) {\n\t\tm.lock.Lock()\n\t\t// Since previously reading m.data[key], the value may have been updated.\n\t\t// Delete the entry only if the expiry time is still the same.\n\t\tif m.data[key].expiry.Equal(value.expiry) {\n\t\t\tdelete(m.data, key)\n\t\t}\n\t\tm.lock.Unlock()\n\n\t\treturn Zilch[V](), false\n\t}\n\n\treturn value.Value, true\n}\n\n// Set sets a key value pair in the map.\nfunc (m *Impl[K, V]) Set(key K, value V, ttl time.Duration) {\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\n\tm.data[key] = decayMapEntry[V]{\n\t\tValue: value,\n\t\texpiry: time.Now().Add(ttl),\n\t}\n}\n\n// Cleanup removes all expired entries from the DecayMap.\nfunc (m *Impl[K, V]) Cleanup() {\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\n\tnow := time.Now()\n\tfor key, entry := range m.data {\n\t\tif now.After(entry.expiry) {\n\t\t\tdelete(m.data, key)\n\t\t}\n\t}\n}\n\n// Len returns the number of entries in the DecayMap.\nfunc (m *Impl[K, V]) Len() int {\n\tm.lock.RLock()\n\tdefer m.lock.RUnlock()\n\treturn len(m.data)\n}\n"], ["/anubis/lib/policy/expressions/http_headers.go", "package expressions\n\nimport (\n\t\"net/http\"\n\t\"reflect\"\n\t\"strings\"\n\n\t\"github.com/google/cel-go/common/types\"\n\t\"github.com/google/cel-go/common/types/ref\"\n\t\"github.com/google/cel-go/common/types/traits\"\n)\n\n// HTTPHeaders is a type wrapper to expose HTTP headers into CEL programs.\ntype HTTPHeaders struct {\n\thttp.Header\n}\n\nfunc (h HTTPHeaders) ConvertToNative(typeDesc reflect.Type) (any, error) {\n\treturn nil, ErrNotImplemented\n}\n\nfunc (h HTTPHeaders) ConvertToType(typeVal ref.Type) ref.Val {\n\tswitch typeVal {\n\tcase types.MapType:\n\t\treturn h\n\tcase types.TypeType:\n\t\treturn types.MapType\n\t}\n\n\treturn types.NewErr(\"can't convert from %q to %q\", types.MapType, typeVal)\n}\n\nfunc (h HTTPHeaders) Equal(other ref.Val) ref.Val {\n\treturn types.Bool(false) // We don't want to compare header maps\n}\n\nfunc (h HTTPHeaders) Type() ref.Type {\n\treturn types.MapType\n}\n\nfunc (h HTTPHeaders) Value() any { return h }\n\nfunc (h HTTPHeaders) Find(key ref.Val) (ref.Val, bool) {\n\tk, ok := key.(types.String)\n\tif !ok {\n\t\treturn nil, false\n\t}\n\n\tif _, ok := h.Header[string(k)]; !ok {\n\t\treturn nil, false\n\t}\n\n\treturn types.String(strings.Join(h.Header.Values(string(k)), \",\")), true\n}\n\nfunc (h HTTPHeaders) Contains(key ref.Val) ref.Val {\n\t_, ok := h.Find(key)\n\treturn types.Bool(ok)\n}\n\nfunc (h HTTPHeaders) Get(key ref.Val) ref.Val {\n\tresult, ok := h.Find(key)\n\tif !ok {\n\t\treturn types.ValOrErr(result, \"no such key: %v\", key)\n\t}\n\treturn result\n}\n\nfunc (h HTTPHeaders) Iterator() traits.Iterator { panic(\"TODO(Xe): implement me\") }\n\nfunc (h HTTPHeaders) IsZeroValue() bool {\n\treturn len(h.Header) == 0\n}\n\nfunc (h HTTPHeaders) Size() ref.Val { return types.Int(len(h.Header)) }\n"], ["/anubis/internal/ogtags/parse.go", "package ogtags\n\nimport (\n\t\"strings\"\n\n\t\"golang.org/x/net/html\"\n)\n\n// extractOGTags traverses the HTML document and extracts approved Open Graph tags\nfunc (c *OGTagCache) extractOGTags(doc *html.Node) map[string]string {\n\togTags := make(map[string]string)\n\n\tvar traverseNodes func(*html.Node)\n\ttraverseNodes = func(n *html.Node) {\n\t\tif isOGMetaTag(n) {\n\t\t\tproperty, content := c.extractMetaTagInfo(n)\n\t\t\tif property != \"\" {\n\t\t\t\togTags[property] = content\n\t\t\t}\n\t\t}\n\t\tfor child := n.FirstChild; child != nil; child = child.NextSibling {\n\t\t\ttraverseNodes(child)\n\t\t}\n\t}\n\n\ttraverseNodes(doc)\n\treturn ogTags\n}\n\n// isOGMetaTag checks if a node is *any* meta tag\nfunc isOGMetaTag(n *html.Node) bool {\n\tif n == nil {\n\t\treturn false\n\t}\n\treturn n.Type == html.ElementNode && n.Data == \"meta\"\n}\n\n// extractMetaTagInfo extracts property and content from a meta tag\nfunc (c *OGTagCache) extractMetaTagInfo(n *html.Node) (property, content string) {\n\tvar propertyKey string\n\n\t// Single pass through attributes, using range to avoid bounds checking\n\tfor _, attr := range n.Attr {\n\t\tswitch attr.Key {\n\t\tcase \"property\", \"name\":\n\t\t\tpropertyKey = attr.Val\n\t\tcase \"content\":\n\t\t\tcontent = attr.Val\n\t\t}\n\t\t// Early exit if we have both\n\t\tif propertyKey != \"\" && content != \"\" {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif propertyKey == \"\" {\n\t\treturn \"\", content\n\t}\n\n\t// Check prefixes first (more common case)\n\tfor _, prefix := range c.approvedPrefixes {\n\t\tif strings.HasPrefix(propertyKey, prefix) {\n\t\t\treturn propertyKey, content\n\t\t}\n\t}\n\n\t// Check exact matches\n\tfor _, tag := range c.approvedTags {\n\t\tif propertyKey == tag {\n\t\t\treturn propertyKey, content\n\t\t}\n\t}\n\n\treturn \"\", content\n}\n"], ["/anubis/internal/hash.go", "package internal\n\nimport (\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"strconv\"\n\n\t\"github.com/cespare/xxhash/v2\"\n)\n\n// SHA256sum computes a cryptographic hash. Still used for proof-of-work challenges\n// where we need the security properties of a cryptographic hash function.\nfunc SHA256sum(text string) string {\n\thash := sha256.New()\n\thash.Write([]byte(text))\n\treturn hex.EncodeToString(hash.Sum(nil))\n}\n\n// FastHash is a high-performance non-cryptographic hash function suitable for\n// internal caching, policy rule identification, and other performance-critical\n// use cases where cryptographic security is not required.\nfunc FastHash(text string) string {\n\th := xxhash.Sum64String(text)\n\treturn strconv.FormatUint(h, 16)\n}\n"], ["/anubis/internal/unbreakdocker.go", "package internal\n\nimport (\n\t\"os\"\n\t\"os/exec\"\n)\n\nfunc UnbreakDocker() {\n\t// XXX(Xe): This is bad code. Do not do this.\n\t//\n\t// I have to do this because I'm running from inside the context of a dev\n\t// container. This dev container runs in a different docker network than\n\t// the valkey test container runs in. In order to let my dev container\n\t// connect to the test container, they need to share a network in common.\n\t// The easiest network to use for this is the default \"bridge\" network.\n\t//\n\t// This is a horrifying monstrosity, but the part that scares me the most\n\t// is the fact that it works.\n\tif hostname, err := os.Hostname(); err == nil {\n\t\texec.Command(\"docker\", \"network\", \"connect\", \"bridge\", hostname).Run()\n\t}\n}\n"], ["/anubis/lib/thoth/auth.go", "package thoth\n\nimport (\n\t\"context\"\n\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/metadata\"\n)\n\nfunc authUnaryClientInterceptor(token string) grpc.UnaryClientInterceptor {\n\treturn func(\n\t\tctx context.Context,\n\t\tmethod string,\n\t\treq interface{},\n\t\treply interface{},\n\t\tcc *grpc.ClientConn,\n\t\tinvoker grpc.UnaryInvoker,\n\t\topts ...grpc.CallOption,\n\t) error {\n\t\tmd := metadata.Pairs(\"authorization\", \"Bearer \"+token)\n\t\tctx = metadata.NewOutgoingContext(ctx, md)\n\t\treturn invoker(ctx, method, req, reply, cc, opts...)\n\t}\n}\n\nfunc authStreamClientInterceptor(token string) grpc.StreamClientInterceptor {\n\treturn func(\n\t\tctx context.Context,\n\t\tdesc *grpc.StreamDesc,\n\t\tcc *grpc.ClientConn,\n\t\tmethod string,\n\t\tstreamer grpc.Streamer,\n\t\topts ...grpc.CallOption,\n\t) (grpc.ClientStream, error) {\n\t\tmd := metadata.Pairs(\"authorization\", \"Bearer \"+token)\n\t\tctx = metadata.NewOutgoingContext(ctx, md)\n\t\treturn streamer(ctx, desc, cc, method, opts...)\n\t}\n}\n"], ["/anubis/lib/thoth/thothmock/withthothmock.go", "package thothmock\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/TecharoHQ/anubis/lib/thoth\"\n)\n\nfunc WithMockThoth(t *testing.T) context.Context {\n\tt.Helper()\n\n\tthothCli := &thoth.Client{}\n\tthothCli.WithIPToASNService(MockIpToASNService())\n\tctx := thoth.With(t.Context(), thothCli)\n\treturn ctx\n}\n"], ["/anubis/lib/store/registry.go", "package store\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"sort\"\n\t\"sync\"\n)\n\nvar (\n\tregistry map[string]Factory = map[string]Factory{}\n\tregLock sync.RWMutex\n)\n\ntype Factory interface {\n\tBuild(ctx context.Context, config json.RawMessage) (Interface, error)\n\tValid(config json.RawMessage) error\n}\n\nfunc Register(name string, impl Factory) {\n\tregLock.Lock()\n\tdefer regLock.Unlock()\n\n\tregistry[name] = impl\n}\n\nfunc Get(name string) (Factory, bool) {\n\tregLock.RLock()\n\tdefer regLock.RUnlock()\n\tresult, ok := registry[name]\n\treturn result, ok\n}\n\nfunc Methods() []string {\n\tregLock.RLock()\n\tdefer regLock.RUnlock()\n\tvar result []string\n\tfor method := range registry {\n\t\tresult = append(result, method)\n\t}\n\tsort.Strings(result)\n\treturn result\n}\n"], ["/anubis/lib/store/all/all.go", "// Package all is a meta-package that imports all store implementations.\n//\n// This is a HACK to make tests work consistently.\npackage all\n\nimport (\n\t_ \"github.com/TecharoHQ/anubis/lib/store/bbolt\"\n\t_ \"github.com/TecharoHQ/anubis/lib/store/memory\"\n\t_ \"github.com/TecharoHQ/anubis/lib/store/valkey\"\n)\n"], ["/anubis/lib/thoth/context.go", "package thoth\n\nimport \"context\"\n\ntype ctxKey struct{}\n\nfunc With(ctx context.Context, cli *Client) context.Context {\n\treturn context.WithValue(ctx, ctxKey{}, cli)\n}\n\nfunc FromContext(ctx context.Context) (*Client, bool) {\n\tcli, ok := ctx.Value(ctxKey{}).(*Client)\n\treturn cli, ok\n}\n"], ["/anubis/lib/challenge/challenge.go", "package challenge\n\nimport \"time\"\n\n// Challenge is the metadata about a single challenge issuance.\ntype Challenge struct {\n\tID string `json:\"id\"` // UUID identifying the challenge\n\tRandomData string `json:\"randomData\"` // The random data the client processes\n\tIssuedAt time.Time `json:\"issuedAt\"` // When the challenge was issued\n\tMetadata map[string]string `json:\"metadata\"` // Challenge metadata such as IP address and user agent\n}\n"], ["/anubis/web/embed.go", "package web\n\nimport \"embed\"\n\n//go:generate go tool github.com/a-h/templ/cmd/templ generate\n\nvar (\n\t//go:embed static\n\tStatic embed.FS\n)\n"], ["/anubis/data/embed.go", "package data\n\nimport \"embed\"\n\nvar (\n\t//go:embed botPolicies.yaml botPolicies.json all:apps all:bots all:clients all:common all:crawlers all:meta\n\tBotPolicies embed.FS\n)\n"], ["/anubis/lib/policy/config/weight.go", "package config\n\ntype Weight struct {\n\tAdjust int `json:\"adjust\" yaml:\"adjust\"`\n}\n"], ["/anubis/internal/mimetype.go", "package internal\n\nimport \"mime\"\n\nfunc init() {\n\tmime.AddExtensionType(\".mjs\", \"text/javascript\")\n}\n"]], "task_instance_info": {"created_time": "2025-08-20 20:50:29", "created_task_model": "DeepSeek-R1", "function_skeleton": "func (s *Server) MakeChallenge (w http.ResponseWriter, r *http.Request) {}", "code_description": "This code segment functions to: Process incoming requests to generate security challenges by validating required parameters, applying policy-based access checks, issuing cryptographic challenge tokens, and returning structured challenge data with associated validation rules in a JSON response format."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```go\n[TASK_BEGIN]\nfunc (s *Server) MakeChallenge(w http.ResponseWriter, r *http.Request) {\n\tlg := internal.GetRequestLogger(r)\n\tlocalizer := localization.GetLocalizer(r)\n\n\t// Issue new challenge\n\tchall, err := s.issueChallenge(r.Context(), r)\n\tif err != nil {\n\t\tlg.Error(\"failed to create challenge\", \"err\", err)\n\t\ts.respondWithError(w, r, localizer.T(\"internal_server_error\"))\n\t\treturn\n\t}\n\n\t// Set test cookie\n\tcookiePath := \"/\"\n\tif anubis.BasePrefix != \"\" {\n\t\tcookiePath = strings.TrimSuffix(anubis.BasePrefix, \"/\") + \"/\"\n\t}\n\n\ts.SetCookie(w, CookieOpts{\n\t\tName: anubis.TestCookieName,\n\t\tValue: chall.ID,\n\t\tPath: cookiePath,\n\t\tHost: r.Host,\n\t\tHttpOnly: true,\n\t\tSecure: true,\n\t\tSameSite: http.SameSiteLaxMode,\n\t\tExpires: time.Now().Add(30 * time.Minute),\n\t})\n\n\t// Return challenge details\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tif err := json.NewEncoder(w).Encode(chall); err != nil {\n\t\tlg.Error(\"failed to encode challenge response\", \"err\", err)\n\t\thttp.Error(w, localizer.T(\"internal_server_error\"), http.StatusInternalServerError)\n\t}\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 20-51-35"}, "editdistance_info": {"edit_distance": 19.6532, "calculate_time": "2025-08-20 20:51:35", "true_code_clean": "func (s *Server) MakeChallenge(w http.ResponseWriter, r *http.Request) {\n\tlg := internal.GetRequestLogger(r)\n\tlocalizer := localization.GetLocalizer(r)\n\tredir := r.FormValue(\"redir\")\n\tif redir == \"\" {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tencoder := json.NewEncoder(w)\n\t\tlg.Error(\"invalid invocation of MakeChallenge\", \"redir\", redir)\n\t\tencoder.Encode(struct {\n\t\t\tError string `json:\"error\"`\n\t\t}{\n\t\t\tError: localizer.T(\"invalid_invocation\"),\n\t\t})\n\t\treturn\n\t}\n\tr.URL.Path = redir\n\tencoder := json.NewEncoder(w)\n\tcr, rule, err := s.check(r)\n\tif err != nil {\n\t\tlg.Error(\"check failed\", \"err\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\terr := encoder.Encode(struct {\n\t\t\tError string `json:\"error\"`\n\t\t}{\n\t\t\tError: fmt.Sprintf(\"%s \\\"makeChallenge\\\"\", localizer.T(\"internal_server_error\")),\n\t\t})\n\t\tif err != nil {\n\t\t\tlg.Error(\"failed to encode error response\", \"err\", err)\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t}\n\t\treturn\n\t}\n\tlg = lg.With(\"check_result\", cr)\n\tchall, err := s.challengeFor(r)\n\tif err != nil {\n\t\tlg.Error(\"failed to fetch or issue challenge\", \"err\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\terr := encoder.Encode(struct {\n\t\t\tError string `json:\"error\"`\n\t\t}{\n\t\t\tError: fmt.Sprintf(\"%s \\\"makeChallenge\\\"\", localizer.T(\"internal_server_error\")),\n\t\t})\n\t\tif err != nil {\n\t\t\tlg.Error(\"failed to encode error response\", \"err\", err)\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t}\n\t\treturn\n\t}\n\ts.SetCookie(w, CookieOpts{Host: r.Host, Name: anubis.TestCookieName, Value: chall.ID})\n\terr = encoder.Encode(struct {\n\t\tRules *config.ChallengeRules `json:\"rules\"`\n\t\tChallenge string `json:\"challenge\"`\n\t}{\n\t\tChallenge: chall.RandomData,\n\t\tRules: rule.Challenge,\n\t})\n\tif err != nil {\n\t\tlg.Error(\"failed to encode challenge\", \"err\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\tlg.Debug(\"made challenge\", \"challenge\", chall, \"rules\", rule.Challenge, \"cr\", cr)\n\tchallengesIssued.WithLabelValues(\"api\").Inc()\n}", "predict_code_clean": "func (s *Server) MakeChallenge(w http.ResponseWriter, r *http.Request) {\n\tlg := internal.GetRequestLogger(r)\n\tlocalizer := localization.GetLocalizer(r)\n\tchall, err := s.issueChallenge(r.Context(), r)\n\tif err != nil {\n\t\tlg.Error(\"failed to create challenge\", \"err\", err)\n\t\ts.respondWithError(w, r, localizer.T(\"internal_server_error\"))\n\t\treturn\n\t}\n\tcookiePath := \"/\"\n\tif anubis.BasePrefix != \"\" {\n\t\tcookiePath = strings.TrimSuffix(anubis.BasePrefix, \"/\") + \"/\"\n\t}\n\ts.SetCookie(w, CookieOpts{\n\t\tName: anubis.TestCookieName,\n\t\tValue: chall.ID,\n\t\tPath: cookiePath,\n\t\tHost: r.Host,\n\t\tHttpOnly: true,\n\t\tSecure: true,\n\t\tSameSite: http.SameSiteLaxMode,\n\t\tExpires: time.Now().Add(30 * time.Minute),\n\t})\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tif err := json.NewEncoder(w).Encode(chall); err != nil {\n\t\tlg.Error(\"failed to encode challenge response\", \"err\", err)\n\t\thttp.Error(w, localizer.T(\"internal_server_error\"), http.StatusInternalServerError)\n\t}\n}"}} {"repo_name": "anubis", "file_name": "/anubis/internal/dnsbl/dnsbl.go", "inference_info": {"prefix_code": "package dnsbl\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net\"\n\t\"strings\"\n)\n\n//go:generate go tool golang.org/x/tools/cmd/stringer -type=DroneBLResponse\n\ntype DroneBLResponse byte\n\nconst (\n\tAllGood DroneBLResponse = 0\n\tIRCDrone DroneBLResponse = 3\n\tBottler DroneBLResponse = 5\n\tUnknownSpambotOrDrone DroneBLResponse = 6\n\tDDOSDrone DroneBLResponse = 7\n\tSOCKSProxy DroneBLResponse = 8\n\tHTTPProxy DroneBLResponse = 9\n\tProxyChain DroneBLResponse = 10\n\tOpenProxy DroneBLResponse = 11\n\tOpenDNSResolver DroneBLResponse = 12\n\tBruteForceAttackers DroneBLResponse = 13\n\tOpenWingateProxy DroneBLResponse = 14\n\tCompromisedRouter DroneBLResponse = 15\n\tAutoRootingWorms DroneBLResponse = 16\n\tAutoDetectedBotIP DroneBLResponse = 17\n\tUnknown DroneBLResponse = 255\n)\n\nfunc Reverse(ip net.IP) string {\n\tif ip.To4() != nil {\n\t\treturn reverse4(ip)\n\t}\n\n\treturn reverse6(ip)\n}\n\nfunc reverse4(ip net.IP) string {\n\tsplitAddress := strings.Split(ip.String(), \".\")\n\n\t// swap first and last octet\n\tsplitAddress[0], splitAddress[3] = splitAddress[3], splitAddress[0]\n\t// swap middle octets\n\tsplitAddress[1], splitAddress[2] = splitAddress[2], splitAddress[1]\n\n\treturn strings.Join(splitAddress, \".\")\n}\n\n", "suffix_code": "\n\nfunc Lookup(ipStr string) (DroneBLResponse, error) {\n\tip := net.ParseIP(ipStr)\n\tif ip == nil {\n\t\treturn Unknown, errors.New(\"dnsbl: input is not an IP address\")\n\t}\n\n\trevIP := Reverse(ip) + \".dnsbl.dronebl.org\"\n\n\tips, err := net.LookupIP(revIP)\n\tif err != nil {\n\t\tvar dnserr *net.DNSError\n\t\tif errors.As(err, &dnserr) {\n\t\t\tif dnserr.IsNotFound {\n\t\t\t\treturn AllGood, nil\n\t\t\t}\n\t\t}\n\n\t\treturn Unknown, err\n\t}\n\n\tif len(ips) != 0 {\n\t\tfor _, ip := range ips {\n\t\t\treturn DroneBLResponse(ip.To4()[3]), nil\n\t\t}\n\t}\n\n\treturn UnknownSpambotOrDrone, nil\n}\n", "middle_code": "func reverse6(ip net.IP) string {\n\tipBytes := []byte(ip)\n\tvar sb strings.Builder\n\tfor i := len(ipBytes) - 1; i >= 0; i-- {\n\t\thighNibble := ipBytes[i] >> 4\n\t\tlowNibble := ipBytes[i] & 0x0F\n\t\tsb.WriteString(fmt.Sprintf(\"%x.%x.\", lowNibble, highNibble))\n\t}\n\treturn sb.String()[:len(sb.String())-1]\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "go", "sub_task_type": null}, "context_code": [["/anubis/internal/dnsbl/droneblresponse_string.go", "// Code generated by \"stringer -type=DroneBLResponse\"; DO NOT EDIT.\n\npackage dnsbl\n\nimport \"strconv\"\n\nfunc _() {\n\t// An \"invalid array index\" compiler error signifies that the constant values have changed.\n\t// Re-run the stringer command to generate them again.\n\tvar x [1]struct{}\n\t_ = x[AllGood-0]\n\t_ = x[IRCDrone-3]\n\t_ = x[Bottler-5]\n\t_ = x[UnknownSpambotOrDrone-6]\n\t_ = x[DDOSDrone-7]\n\t_ = x[SOCKSProxy-8]\n\t_ = x[HTTPProxy-9]\n\t_ = x[ProxyChain-10]\n\t_ = x[OpenProxy-11]\n\t_ = x[OpenDNSResolver-12]\n\t_ = x[BruteForceAttackers-13]\n\t_ = x[OpenWingateProxy-14]\n\t_ = x[CompromisedRouter-15]\n\t_ = x[AutoRootingWorms-16]\n\t_ = x[AutoDetectedBotIP-17]\n\t_ = x[Unknown-255]\n}\n\nconst (\n\t_DroneBLResponse_name_0 = \"AllGood\"\n\t_DroneBLResponse_name_1 = \"IRCDrone\"\n\t_DroneBLResponse_name_2 = \"BottlerUnknownSpambotOrDroneDDOSDroneSOCKSProxyHTTPProxyProxyChainOpenProxyOpenDNSResolverBruteForceAttackersOpenWingateProxyCompromisedRouterAutoRootingWormsAutoDetectedBotIP\"\n\t_DroneBLResponse_name_3 = \"Unknown\"\n)\n\nvar (\n\t_DroneBLResponse_index_2 = [...]uint8{0, 7, 28, 37, 47, 56, 66, 75, 90, 109, 125, 142, 158, 175}\n)\n\nfunc (i DroneBLResponse) String() string {\n\tswitch {\n\tcase i == 0:\n\t\treturn _DroneBLResponse_name_0\n\tcase i == 3:\n\t\treturn _DroneBLResponse_name_1\n\tcase 5 <= i && i <= 17:\n\t\ti -= 5\n\t\treturn _DroneBLResponse_name_2[_DroneBLResponse_index_2[i]:_DroneBLResponse_index_2[i+1]]\n\tcase i == 255:\n\t\treturn _DroneBLResponse_name_3\n\tdefault:\n\t\treturn \"DroneBLResponse(\" + strconv.FormatInt(int64(i), 10) + \")\"\n\t}\n}\n"], ["/anubis/lib/anubis.go", "package lib\n\nimport (\n\t\"context\"\n\t\"crypto/ed25519\"\n\t\"crypto/rand\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"slices\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/golang-jwt/jwt/v5\"\n\t\"github.com/google/cel-go/common/types\"\n\t\"github.com/google/uuid\"\n\n\t\"github.com/prometheus/client_golang/prometheus\"\n\t\"github.com/prometheus/client_golang/prometheus/promauto\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/TecharoHQ/anubis/decaymap\"\n\t\"github.com/TecharoHQ/anubis/internal\"\n\t\"github.com/TecharoHQ/anubis/internal/dnsbl\"\n\t\"github.com/TecharoHQ/anubis/internal/ogtags\"\n\t\"github.com/TecharoHQ/anubis/lib/challenge\"\n\t\"github.com/TecharoHQ/anubis/lib/localization\"\n\t\"github.com/TecharoHQ/anubis/lib/policy\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/checker\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n\n\t// challenge implementations\n\t_ \"github.com/TecharoHQ/anubis/lib/challenge/metarefresh\"\n\t_ \"github.com/TecharoHQ/anubis/lib/challenge/proofofwork\"\n)\n\nvar (\n\tchallengesIssued = promauto.NewCounterVec(prometheus.CounterOpts{\n\t\tName: \"anubis_challenges_issued\",\n\t\tHelp: \"The total number of challenges issued\",\n\t}, []string{\"method\"})\n\n\tchallengesValidated = promauto.NewCounterVec(prometheus.CounterOpts{\n\t\tName: \"anubis_challenges_validated\",\n\t\tHelp: \"The total number of challenges validated\",\n\t}, []string{\"method\"})\n\n\tdroneBLHits = promauto.NewCounterVec(prometheus.CounterOpts{\n\t\tName: \"anubis_dronebl_hits\",\n\t\tHelp: \"The total number of hits from DroneBL\",\n\t}, []string{\"status\"})\n\n\tfailedValidations = promauto.NewCounterVec(prometheus.CounterOpts{\n\t\tName: \"anubis_failed_validations\",\n\t\tHelp: \"The total number of failed validations\",\n\t}, []string{\"method\"})\n\n\trequestsProxied = promauto.NewCounterVec(prometheus.CounterOpts{\n\t\tName: \"anubis_proxied_requests_total\",\n\t\tHelp: \"Number of requests proxied through Anubis to upstream targets\",\n\t}, []string{\"host\"})\n)\n\ntype Server struct {\n\tnext http.Handler\n\tmux *http.ServeMux\n\tpolicy *policy.ParsedConfig\n\tOGTags *ogtags.OGTagCache\n\ted25519Priv ed25519.PrivateKey\n\ths512Secret []byte\n\topts Options\n\tstore store.Interface\n}\n\nfunc (s *Server) getTokenKeyfunc() jwt.Keyfunc {\n\t// return ED25519 key if HS512 is not set\n\tif len(s.hs512Secret) == 0 {\n\t\treturn func(token *jwt.Token) (interface{}, error) {\n\t\t\treturn s.ed25519Priv.Public().(ed25519.PublicKey), nil\n\t\t}\n\t} else {\n\t\treturn func(token *jwt.Token) (interface{}, error) {\n\t\t\treturn s.hs512Secret, nil\n\t\t}\n\t}\n}\n\nfunc (s *Server) challengeFor(r *http.Request) (*challenge.Challenge, error) {\n\tckies := r.CookiesNamed(anubis.TestCookieName)\n\n\tif len(ckies) == 0 {\n\t\treturn s.issueChallenge(r.Context(), r)\n\t}\n\n\tj := store.JSON[challenge.Challenge]{Underlying: s.store}\n\n\tckie := ckies[0]\n\tchall, err := j.Get(r.Context(), \"challenge:\"+ckie.Value)\n\tif err != nil {\n\t\tif errors.Is(err, store.ErrNotFound) {\n\t\t\treturn s.issueChallenge(r.Context(), r)\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\treturn &chall, nil\n}\n\nfunc (s *Server) issueChallenge(ctx context.Context, r *http.Request) (*challenge.Challenge, error) {\n\tid, err := uuid.NewV7()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar randomData = make([]byte, 256)\n\tif _, err := rand.Read(randomData); err != nil {\n\t\treturn nil, err\n\t}\n\n\tchall := challenge.Challenge{\n\t\tID: id.String(),\n\t\tRandomData: fmt.Sprintf(\"%x\", randomData),\n\t\tIssuedAt: time.Now(),\n\t\tMetadata: map[string]string{\n\t\t\t\"User-Agent\": r.Header.Get(\"User-Agent\"),\n\t\t\t\"X-Real-Ip\": r.Header.Get(\"X-Real-Ip\"),\n\t\t},\n\t}\n\n\tj := store.JSON[challenge.Challenge]{Underlying: s.store}\n\tif err := j.Set(ctx, \"challenge:\"+id.String(), chall, 30*time.Minute); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &chall, err\n}\n\nfunc (s *Server) maybeReverseProxyHttpStatusOnly(w http.ResponseWriter, r *http.Request) {\n\ts.maybeReverseProxy(w, r, true)\n}\n\nfunc (s *Server) maybeReverseProxyOrPage(w http.ResponseWriter, r *http.Request) {\n\ts.maybeReverseProxy(w, r, false)\n}\n\nfunc (s *Server) maybeReverseProxy(w http.ResponseWriter, r *http.Request, httpStatusOnly bool) {\n\tlg := internal.GetRequestLogger(r)\n\n\t// Adjust cookie path if base prefix is not empty\n\tcookiePath := \"/\"\n\tif anubis.BasePrefix != \"\" {\n\t\tcookiePath = strings.TrimSuffix(anubis.BasePrefix, \"/\") + \"/\"\n\t}\n\n\tcr, rule, err := s.check(r)\n\tif err != nil {\n\t\tlg.Error(\"check failed\", \"err\", err)\n\t\tlocalizer := localization.GetLocalizer(r)\n\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s \\\"maybeReverseProxy\\\"\", localizer.T(\"internal_server_error\")))\n\t\treturn\n\t}\n\n\tr.Header.Add(\"X-Anubis-Rule\", cr.Name)\n\tr.Header.Add(\"X-Anubis-Action\", string(cr.Rule))\n\tlg = lg.With(\"check_result\", cr)\n\tpolicy.Applications.WithLabelValues(cr.Name, string(cr.Rule)).Add(1)\n\n\tip := r.Header.Get(\"X-Real-Ip\")\n\n\tif s.handleDNSBL(w, r, ip, lg) {\n\t\treturn\n\t}\n\n\tif s.checkRules(w, r, cr, lg, rule) {\n\t\treturn\n\t}\n\n\tckie, err := r.Cookie(anubis.CookieName)\n\tif err != nil {\n\t\tlg.Debug(\"cookie not found\", \"path\", r.URL.Path)\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.RenderIndex(w, r, rule, httpStatusOnly)\n\t\treturn\n\t}\n\n\tif err := ckie.Valid(); err != nil {\n\t\tlg.Debug(\"cookie is invalid\", \"err\", err)\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.RenderIndex(w, r, rule, httpStatusOnly)\n\t\treturn\n\t}\n\n\tif time.Now().After(ckie.Expires) && !ckie.Expires.IsZero() {\n\t\tlg.Debug(\"cookie expired\", \"path\", r.URL.Path)\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.RenderIndex(w, r, rule, httpStatusOnly)\n\t\treturn\n\t}\n\n\ttoken, err := jwt.ParseWithClaims(ckie.Value, jwt.MapClaims{}, s.getTokenKeyfunc(), jwt.WithExpirationRequired(), jwt.WithStrictDecoding())\n\n\tif err != nil || !token.Valid {\n\t\tlg.Debug(\"invalid token\", \"path\", r.URL.Path, \"err\", err)\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.RenderIndex(w, r, rule, httpStatusOnly)\n\t\treturn\n\t}\n\n\tclaims, ok := token.Claims.(jwt.MapClaims)\n\tif !ok {\n\t\tlg.Debug(\"invalid token claims type\", \"path\", r.URL.Path)\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.RenderIndex(w, r, rule, httpStatusOnly)\n\t\treturn\n\t}\n\n\tpolicyRule, ok := claims[\"policyRule\"].(string)\n\tif !ok {\n\t\tlg.Debug(\"policyRule claim is not a string\")\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.RenderIndex(w, r, rule, httpStatusOnly)\n\t\treturn\n\t}\n\n\tif policyRule != rule.Hash() {\n\t\tlg.Debug(\"user originally passed with a different rule, issuing new challenge\", \"old\", policyRule, \"new\", rule.Name)\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.RenderIndex(w, r, rule, httpStatusOnly)\n\t\treturn\n\t}\n\n\tr.Header.Add(\"X-Anubis-Status\", \"PASS\")\n\ts.ServeHTTPNext(w, r)\n}\n\nfunc (s *Server) checkRules(w http.ResponseWriter, r *http.Request, cr policy.CheckResult, lg *slog.Logger, rule *policy.Bot) bool {\n\t// Adjust cookie path if base prefix is not empty\n\tcookiePath := \"/\"\n\tif anubis.BasePrefix != \"\" {\n\t\tcookiePath = strings.TrimSuffix(anubis.BasePrefix, \"/\") + \"/\"\n\t}\n\n\tlocalizer := localization.GetLocalizer(r)\n\n\tswitch cr.Rule {\n\tcase config.RuleAllow:\n\t\tlg.Debug(\"allowing traffic to origin (explicit)\")\n\t\ts.ServeHTTPNext(w, r)\n\t\treturn true\n\tcase config.RuleDeny:\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\tlg.Info(\"explicit deny\")\n\t\tif rule == nil {\n\t\t\tlg.Error(\"rule is nil, cannot calculate checksum\")\n\t\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s \\\"maybeReverseProxy.RuleDeny\\\"\", localizer.T(\"internal_server_error\")))\n\t\t\treturn true\n\t\t}\n\t\thash := rule.Hash()\n\n\t\tlg.Debug(\"rule hash\", \"hash\", hash)\n\t\ts.respondWithStatus(w, r, fmt.Sprintf(\"%s %s\", localizer.T(\"access_denied\"), hash), s.policy.StatusCodes.Deny)\n\t\treturn true\n\tcase config.RuleChallenge:\n\t\tlg.Debug(\"challenge requested\")\n\tcase config.RuleBenchmark:\n\t\tlg.Debug(\"serving benchmark page\")\n\t\ts.RenderBench(w, r)\n\t\treturn true\n\tdefault:\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\tslog.Error(\"CONFIG ERROR: unknown rule\", \"rule\", cr.Rule)\n\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s \\\"maybeReverseProxy.Rules\\\"\", localizer.T(\"internal_server_error\")))\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (s *Server) handleDNSBL(w http.ResponseWriter, r *http.Request, ip string, lg *slog.Logger) bool {\n\tdb := &store.JSON[dnsbl.DroneBLResponse]{Underlying: s.store, Prefix: \"dronebl:\"}\n\tif s.policy.DNSBL && ip != \"\" {\n\t\tresp, err := db.Get(r.Context(), ip)\n\t\tif err != nil {\n\t\t\tlg.Debug(\"looking up ip in dnsbl\")\n\t\t\tresp, err := dnsbl.Lookup(ip)\n\t\t\tif err != nil {\n\t\t\t\tlg.Error(\"can't look up ip in dnsbl\", \"err\", err)\n\t\t\t}\n\t\t\tdb.Set(r.Context(), ip, resp, 24*time.Hour)\n\t\t\tdroneBLHits.WithLabelValues(resp.String()).Inc()\n\t\t}\n\n\t\tif resp != dnsbl.AllGood {\n\t\t\tlg.Info(\"DNSBL hit\", \"status\", resp.String())\n\t\t\tlocalizer := localization.GetLocalizer(r)\n\t\t\ts.respondWithStatus(w, r, fmt.Sprintf(\"%s: %s, %s https://dronebl.org/lookup?ip=%s\",\n\t\t\t\tlocalizer.T(\"dronebl_entry\"),\n\t\t\t\tresp.String(),\n\t\t\t\tlocalizer.T(\"see_dronebl_lookup\"),\n\t\t\t\tip), s.policy.StatusCodes.Deny)\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (s *Server) MakeChallenge(w http.ResponseWriter, r *http.Request) {\n\tlg := internal.GetRequestLogger(r)\n\tlocalizer := localization.GetLocalizer(r)\n\n\tredir := r.FormValue(\"redir\")\n\tif redir == \"\" {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tencoder := json.NewEncoder(w)\n\t\tlg.Error(\"invalid invocation of MakeChallenge\", \"redir\", redir)\n\t\tencoder.Encode(struct {\n\t\t\tError string `json:\"error\"`\n\t\t}{\n\t\t\tError: localizer.T(\"invalid_invocation\"),\n\t\t})\n\t\treturn\n\t}\n\n\tr.URL.Path = redir\n\n\tencoder := json.NewEncoder(w)\n\tcr, rule, err := s.check(r)\n\tif err != nil {\n\t\tlg.Error(\"check failed\", \"err\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\terr := encoder.Encode(struct {\n\t\t\tError string `json:\"error\"`\n\t\t}{\n\t\t\tError: fmt.Sprintf(\"%s \\\"makeChallenge\\\"\", localizer.T(\"internal_server_error\")),\n\t\t})\n\t\tif err != nil {\n\t\t\tlg.Error(\"failed to encode error response\", \"err\", err)\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t}\n\t\treturn\n\t}\n\tlg = lg.With(\"check_result\", cr)\n\n\tchall, err := s.challengeFor(r)\n\tif err != nil {\n\t\tlg.Error(\"failed to fetch or issue challenge\", \"err\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\terr := encoder.Encode(struct {\n\t\t\tError string `json:\"error\"`\n\t\t}{\n\t\t\tError: fmt.Sprintf(\"%s \\\"makeChallenge\\\"\", localizer.T(\"internal_server_error\")),\n\t\t})\n\t\tif err != nil {\n\t\t\tlg.Error(\"failed to encode error response\", \"err\", err)\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t}\n\t\treturn\n\t}\n\n\ts.SetCookie(w, CookieOpts{Host: r.Host, Name: anubis.TestCookieName, Value: chall.ID})\n\n\terr = encoder.Encode(struct {\n\t\tRules *config.ChallengeRules `json:\"rules\"`\n\t\tChallenge string `json:\"challenge\"`\n\t}{\n\t\tChallenge: chall.RandomData,\n\t\tRules: rule.Challenge,\n\t})\n\tif err != nil {\n\t\tlg.Error(\"failed to encode challenge\", \"err\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\tlg.Debug(\"made challenge\", \"challenge\", chall, \"rules\", rule.Challenge, \"cr\", cr)\n\tchallengesIssued.WithLabelValues(\"api\").Inc()\n}\n\nfunc (s *Server) PassChallenge(w http.ResponseWriter, r *http.Request) {\n\tlg := internal.GetRequestLogger(r)\n\tlocalizer := localization.GetLocalizer(r)\n\n\tredir := r.FormValue(\"redir\")\n\tredirURL, err := url.ParseRequestURI(redir)\n\tif err != nil {\n\t\tlg.Error(\"invalid redirect\", \"err\", err)\n\t\ts.respondWithStatus(w, r, localizer.T(\"invalid_redirect\"), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tswitch redirURL.Scheme {\n\tcase \"\", \"http\", \"https\":\n\t\t// allowed\n\tdefault:\n\t\tlg.Error(\"XSS attempt blocked, invalid redirect scheme\", \"scheme\", redirURL.Scheme)\n\t\ts.respondWithStatus(w, r, localizer.T(\"invalid_redirect\"), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// Adjust cookie path if base prefix is not empty\n\tcookiePath := \"/\"\n\tif anubis.BasePrefix != \"\" {\n\t\tcookiePath = strings.TrimSuffix(anubis.BasePrefix, \"/\") + \"/\"\n\t}\n\n\tif _, err := r.Cookie(anubis.TestCookieName); errors.Is(err, http.ErrNoCookie) {\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.ClearCookie(w, CookieOpts{Name: anubis.TestCookieName, Host: r.Host})\n\t\tlg.Warn(\"user has cookies disabled, this is not an anubis bug\")\n\t\ts.respondWithError(w, r, localizer.T(\"cookies_disabled\"))\n\t\treturn\n\t}\n\n\t// used by the path checker rule\n\tr.URL = redirURL\n\n\turlParsed, err := r.URL.Parse(redir)\n\tif err != nil {\n\t\ts.respondWithError(w, r, localizer.T(\"redirect_not_parseable\"))\n\t\treturn\n\t}\n\tif (len(urlParsed.Host) > 0 && len(s.opts.RedirectDomains) != 0 && !slices.Contains(s.opts.RedirectDomains, urlParsed.Host)) || urlParsed.Host != r.URL.Host {\n\t\ts.respondWithError(w, r, localizer.T(\"redirect_domain_not_allowed\"))\n\t\treturn\n\t}\n\n\tcr, rule, err := s.check(r)\n\tif err != nil {\n\t\tlg.Error(\"check failed\", \"err\", err)\n\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s \\\"passChallenge\\\"\", localizer.T(\"internal_server_error\")))\n\t\treturn\n\t}\n\tlg = lg.With(\"check_result\", cr)\n\n\timpl, ok := challenge.Get(rule.Challenge.Algorithm)\n\tif !ok {\n\t\tlg.Error(\"check failed\", \"err\", err)\n\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s: %s\", localizer.T(\"internal_server_error\"), rule.Challenge.Algorithm))\n\t\treturn\n\t}\n\n\tchall, err := s.challengeFor(r)\n\tif err != nil {\n\t\tlg.Error(\"check failed\", \"err\", err)\n\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s: %s\", localizer.T(\"internal_server_error\"), rule.Challenge.Algorithm))\n\t\treturn\n\t}\n\n\tin := &challenge.ValidateInput{\n\t\tChallenge: chall,\n\t\tRule: rule,\n\t\tStore: s.store,\n\t}\n\n\tif err := impl.Validate(r, lg, in); err != nil {\n\t\tfailedValidations.WithLabelValues(rule.Challenge.Algorithm).Inc()\n\t\tvar cerr *challenge.Error\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\tlg.Debug(\"challenge validate call failed\", \"err\", err)\n\n\t\tswitch {\n\t\tcase errors.As(err, &cerr):\n\t\t\tswitch {\n\t\t\tcase errors.Is(err, challenge.ErrFailed):\n\t\t\t\ts.respondWithStatus(w, r, cerr.PublicReason, cerr.StatusCode)\n\t\t\tcase errors.Is(err, challenge.ErrInvalidFormat), errors.Is(err, challenge.ErrMissingField):\n\t\t\t\ts.respondWithError(w, r, cerr.PublicReason)\n\t\t\t}\n\t\t}\n\t}\n\n\t// generate JWT cookie\n\ttokenString, err := s.signJWT(jwt.MapClaims{\n\t\t\"challenge\": chall.ID,\n\t\t\"method\": rule.Challenge.Algorithm,\n\t\t\"policyRule\": rule.Hash(),\n\t\t\"action\": string(cr.Rule),\n\t})\n\tif err != nil {\n\t\tlg.Error(\"failed to sign JWT\", \"err\", err)\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.respondWithError(w, r, localizer.T(\"failed_to_sign_jwt\"))\n\t\treturn\n\t}\n\n\ts.SetCookie(w, CookieOpts{Path: cookiePath, Host: r.Host, Value: tokenString})\n\n\tchallengesValidated.WithLabelValues(rule.Challenge.Algorithm).Inc()\n\tlg.Debug(\"challenge passed, redirecting to app\")\n\thttp.Redirect(w, r, redir, http.StatusFound)\n}\n\nfunc cr(name string, rule config.Rule, weight int) policy.CheckResult {\n\treturn policy.CheckResult{\n\t\tName: name,\n\t\tRule: rule,\n\t\tWeight: weight,\n\t}\n}\n\n// Check evaluates the list of rules, and returns the result\nfunc (s *Server) check(r *http.Request) (policy.CheckResult, *policy.Bot, error) {\n\thost := r.Header.Get(\"X-Real-Ip\")\n\tif host == \"\" {\n\t\treturn decaymap.Zilch[policy.CheckResult](), nil, fmt.Errorf(\"[misconfiguration] X-Real-Ip header is not set\")\n\t}\n\n\taddr := net.ParseIP(host)\n\tif addr == nil {\n\t\treturn decaymap.Zilch[policy.CheckResult](), nil, fmt.Errorf(\"[misconfiguration] %q is not an IP address\", host)\n\t}\n\n\tweight := 0\n\n\tfor _, b := range s.policy.Bots {\n\t\tmatch, err := b.Rules.Check(r)\n\t\tif err != nil {\n\t\t\treturn decaymap.Zilch[policy.CheckResult](), nil, fmt.Errorf(\"can't run check %s: %w\", b.Name, err)\n\t\t}\n\n\t\tif match {\n\t\t\tswitch b.Action {\n\t\t\tcase config.RuleDeny, config.RuleAllow, config.RuleBenchmark, config.RuleChallenge:\n\t\t\t\treturn cr(\"bot/\"+b.Name, b.Action, weight), &b, nil\n\t\t\tcase config.RuleWeigh:\n\t\t\t\tslog.Debug(\"adjusting weight\", \"name\", b.Name, \"delta\", b.Weight.Adjust)\n\t\t\t\tweight += b.Weight.Adjust\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, t := range s.policy.Thresholds {\n\t\tresult, _, err := t.Program.ContextEval(r.Context(), &policy.ThresholdRequest{Weight: weight})\n\t\tif err != nil {\n\t\t\tslog.Error(\"error when evaluating threshold expression\", \"expression\", t.Expression.String(), \"err\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tvar matches bool\n\n\t\tif val, ok := result.(types.Bool); ok {\n\t\t\tmatches = bool(val)\n\t\t}\n\n\t\tif matches {\n\t\t\treturn cr(\"threshold/\"+t.Name, t.Action, weight), &policy.Bot{\n\t\t\t\tChallenge: t.Challenge,\n\t\t\t\tRules: &checker.List{},\n\t\t\t}, nil\n\t\t}\n\t}\n\n\treturn cr(\"default/allow\", config.RuleAllow, weight), &policy.Bot{\n\t\tChallenge: &config.ChallengeRules{\n\t\t\tDifficulty: s.policy.DefaultDifficulty,\n\t\t\tReportAs: s.policy.DefaultDifficulty,\n\t\t\tAlgorithm: config.DefaultAlgorithm,\n\t\t},\n\t\tRules: &checker.List{},\n\t}, nil\n}\n"], ["/anubis/lib/thoth/cachediptoasn.go", "package thoth\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net/netip\"\n\n\tiptoasnv1 \"github.com/TecharoHQ/thoth-proto/gen/techaro/thoth/iptoasn/v1\"\n\t\"github.com/gaissmai/bart\"\n\t\"google.golang.org/grpc\"\n)\n\ntype IPToASNWithCache struct {\n\tnext iptoasnv1.IpToASNServiceClient\n\ttable *bart.Table[*iptoasnv1.LookupResponse]\n}\n\nfunc NewIpToASNWithCache(next iptoasnv1.IpToASNServiceClient) *IPToASNWithCache {\n\tresult := &IPToASNWithCache{\n\t\tnext: next,\n\t\ttable: &bart.Table[*iptoasnv1.LookupResponse]{},\n\t}\n\n\tfor _, pfx := range []netip.Prefix{\n\t\tnetip.MustParsePrefix(\"10.0.0.0/8\"), // RFC 1918\n\t\tnetip.MustParsePrefix(\"172.16.0.0/12\"), // RFC 1918\n\t\tnetip.MustParsePrefix(\"192.168.0.0/16\"), // RFC 1918\n\t\tnetip.MustParsePrefix(\"127.0.0.0/8\"), // Loopback\n\t\tnetip.MustParsePrefix(\"169.254.0.0/16\"), // Link-local\n\t\tnetip.MustParsePrefix(\"100.64.0.0/10\"), // CGNAT\n\t\tnetip.MustParsePrefix(\"192.0.0.0/24\"), // Protocol assignments\n\t\tnetip.MustParsePrefix(\"192.0.2.0/24\"), // TEST-NET-1\n\t\tnetip.MustParsePrefix(\"198.18.0.0/15\"), // Benchmarking\n\t\tnetip.MustParsePrefix(\"198.51.100.0/24\"), // TEST-NET-2\n\t\tnetip.MustParsePrefix(\"203.0.113.0/24\"), // TEST-NET-3\n\t\tnetip.MustParsePrefix(\"240.0.0.0/4\"), // Reserved\n\t\tnetip.MustParsePrefix(\"255.255.255.255/32\"), // Broadcast\n\t\tnetip.MustParsePrefix(\"fc00::/7\"), // Unique local address\n\t\tnetip.MustParsePrefix(\"fe80::/10\"), // Link-local\n\t\tnetip.MustParsePrefix(\"::1/128\"), // Loopback\n\t\tnetip.MustParsePrefix(\"::/128\"), // Unspecified\n\t\tnetip.MustParsePrefix(\"100::/64\"), // Discard-only\n\t\tnetip.MustParsePrefix(\"2001:db8::/32\"), // Documentation\n\t} {\n\t\tresult.table.Insert(pfx, &iptoasnv1.LookupResponse{Announced: false})\n\t}\n\n\treturn result\n}\n\nfunc (ip2asn *IPToASNWithCache) Lookup(ctx context.Context, lr *iptoasnv1.LookupRequest, opts ...grpc.CallOption) (*iptoasnv1.LookupResponse, error) {\n\taddr, err := netip.ParseAddr(lr.GetIpAddress())\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"input is not an IP address: %w\", err)\n\t}\n\n\tcachedResponse, ok := ip2asn.table.Lookup(addr)\n\tif ok {\n\t\treturn cachedResponse, nil\n\t}\n\n\tresp, err := ip2asn.next.Lookup(ctx, lr, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar errs []error\n\tfor _, cidr := range resp.GetCidr() {\n\t\tpfx, err := netip.ParsePrefix(cidr)\n\t\tif err != nil {\n\t\t\terrs = append(errs, err)\n\t\t\tcontinue\n\t\t}\n\t\tip2asn.table.Insert(pfx, resp)\n\t}\n\n\tif len(errs) != 0 {\n\t\tslog.Error(\"errors parsing IP prefixes\", \"err\", errors.Join(errs...))\n\t}\n\n\treturn resp, nil\n}\n"], ["/anubis/cmd/anubis/main.go", "package main\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"crypto/ed25519\"\n\t\"crypto/rand\"\n\t\"crypto/tls\"\n\t\"embed\"\n\t\"encoding/hex\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io/fs\"\n\t\"log\"\n\t\"log/slog\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/http/httputil\"\n\t\"net/url\"\n\t\"os\"\n\t\"os/signal\"\n\t\"path/filepath\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/TecharoHQ/anubis/data\"\n\t\"github.com/TecharoHQ/anubis/internal\"\n\tlibanubis \"github.com/TecharoHQ/anubis/lib\"\n\tbotPolicy \"github.com/TecharoHQ/anubis/lib/policy\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/lib/thoth\"\n\t\"github.com/TecharoHQ/anubis/web\"\n\t\"github.com/facebookgo/flagenv\"\n\t_ \"github.com/joho/godotenv/autoload\"\n\t\"github.com/prometheus/client_golang/prometheus/promhttp\"\n\thealthv1 \"google.golang.org/grpc/health/grpc_health_v1\"\n)\n\nvar (\n\tbasePrefix = flag.String(\"base-prefix\", \"\", \"base prefix (root URL) the application is served under e.g. /myapp\")\n\tbind = flag.String(\"bind\", \":8923\", \"network address to bind HTTP to\")\n\tbindNetwork = flag.String(\"bind-network\", \"tcp\", \"network family to bind HTTP to, e.g. unix, tcp\")\n\tchallengeDifficulty = flag.Int(\"difficulty\", anubis.DefaultDifficulty, \"difficulty of the challenge\")\n\tcookieDomain = flag.String(\"cookie-domain\", \"\", \"if set, the top-level domain that the Anubis cookie will be valid for\")\n\tcookieDynamicDomain = flag.Bool(\"cookie-dynamic-domain\", false, \"if set, automatically set the cookie Domain value based on the request domain\")\n\tcookieExpiration = flag.Duration(\"cookie-expiration-time\", anubis.CookieDefaultExpirationTime, \"The amount of time the authorization cookie is valid for\")\n\tcookiePrefix = flag.String(\"cookie-prefix\", \"techaro.lol-anubis\", \"prefix for browser cookies created by Anubis\")\n\tcookiePartitioned = flag.Bool(\"cookie-partitioned\", false, \"if true, sets the partitioned flag on Anubis cookies, enabling CHIPS support\")\n\tforcedLanguage = flag.String(\"forced-language\", \"\", \"if set, this language is being used instead of the one from the request's Accept-Language header\")\n\ths512Secret = flag.String(\"hs512-secret\", \"\", \"secret used to sign JWTs, uses ed25519 if not set\")\n\tcookieSecure = flag.Bool(\"cookie-secure\", true, \"if true, sets the secure flag on Anubis cookies\")\n\ted25519PrivateKeyHex = flag.String(\"ed25519-private-key-hex\", \"\", \"private key used to sign JWTs, if not set a random one will be assigned\")\n\ted25519PrivateKeyHexFile = flag.String(\"ed25519-private-key-hex-file\", \"\", \"file name containing value for ed25519-private-key-hex\")\n\tmetricsBind = flag.String(\"metrics-bind\", \":9090\", \"network address to bind metrics to\")\n\tmetricsBindNetwork = flag.String(\"metrics-bind-network\", \"tcp\", \"network family for the metrics server to bind to\")\n\tsocketMode = flag.String(\"socket-mode\", \"0770\", \"socket mode (permissions) for unix domain sockets.\")\n\trobotsTxt = flag.Bool(\"serve-robots-txt\", false, \"serve a robots.txt file that disallows all robots\")\n\tpolicyFname = flag.String(\"policy-fname\", \"\", \"full path to anubis policy document (defaults to a sensible built-in policy)\")\n\tredirectDomains = flag.String(\"redirect-domains\", \"\", \"list of domains separated by commas which anubis is allowed to redirect to. Leaving this unset allows any domain.\")\n\tslogLevel = flag.String(\"slog-level\", \"INFO\", \"logging level (see https://pkg.go.dev/log/slog#hdr-Levels)\")\n\tstripBasePrefix = flag.Bool(\"strip-base-prefix\", false, \"if true, strips the base prefix from requests forwarded to the target server\")\n\ttarget = flag.String(\"target\", \"http://localhost:3923\", \"target to reverse proxy to, set to an empty string to disable proxying when only using auth request\")\n\ttargetSNI = flag.String(\"target-sni\", \"\", \"if set, the value of the TLS handshake hostname when forwarding requests to the target\")\n\ttargetHost = flag.String(\"target-host\", \"\", \"if set, the value of the Host header when forwarding requests to the target\")\n\ttargetInsecureSkipVerify = flag.Bool(\"target-insecure-skip-verify\", false, \"if true, skips TLS validation for the backend\")\n\thealthcheck = flag.Bool(\"healthcheck\", false, \"run a health check against Anubis\")\n\tuseRemoteAddress = flag.Bool(\"use-remote-address\", false, \"read the client's IP address from the network request, useful for debugging and running Anubis on bare metal\")\n\tdebugBenchmarkJS = flag.Bool(\"debug-benchmark-js\", false, \"respond to every request with a challenge for benchmarking hashrate\")\n\togPassthrough = flag.Bool(\"og-passthrough\", false, \"enable Open Graph tag passthrough\")\n\togTimeToLive = flag.Duration(\"og-expiry-time\", 24*time.Hour, \"Open Graph tag cache expiration time\")\n\togCacheConsiderHost = flag.Bool(\"og-cache-consider-host\", false, \"enable or disable the use of the host in the Open Graph tag cache\")\n\textractResources = flag.String(\"extract-resources\", \"\", \"if set, extract the static resources to the specified folder\")\n\twebmasterEmail = flag.String(\"webmaster-email\", \"\", \"if set, displays webmaster's email on the reject page for appeals\")\n\tversionFlag = flag.Bool(\"version\", false, \"print Anubis version\")\n\txffStripPrivate = flag.Bool(\"xff-strip-private\", true, \"if set, strip private addresses from X-Forwarded-For\")\n\n\tthothInsecure = flag.Bool(\"thoth-insecure\", false, \"if set, connect to Thoth over plain HTTP/2, don't enable this unless support told you to\")\n\tthothURL = flag.String(\"thoth-url\", \"\", \"if set, URL for Thoth, the IP reputation database for Anubis\")\n\tthothToken = flag.String(\"thoth-token\", \"\", \"if set, API token for Thoth, the IP reputation database for Anubis\")\n)\n\nfunc keyFromHex(value string) (ed25519.PrivateKey, error) {\n\tkeyBytes, err := hex.DecodeString(value)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"supplied key is not hex-encoded: %w\", err)\n\t}\n\n\tif len(keyBytes) != ed25519.SeedSize {\n\t\treturn nil, fmt.Errorf(\"supplied key is not %d bytes long, got %d bytes\", ed25519.SeedSize, len(keyBytes))\n\t}\n\n\treturn ed25519.NewKeyFromSeed(keyBytes), nil\n}\n\nfunc doHealthCheck() error {\n\tresp, err := http.Get(\"http://localhost\" + *metricsBind + \"/healthz\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to fetch metrics: %w\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn fmt.Errorf(\"unexpected status code: %d\", resp.StatusCode)\n\t}\n\n\treturn nil\n}\n\n// parseBindNetFromAddr determine bind network and address based on the given network and address.\nfunc parseBindNetFromAddr(address string) (string, string) {\n\tdefaultScheme := \"http://\"\n\tif !strings.Contains(address, \"://\") {\n\t\tif strings.HasPrefix(address, \":\") {\n\t\t\taddress = defaultScheme + \"localhost\" + address\n\t\t} else {\n\t\t\taddress = defaultScheme + address\n\t\t}\n\t}\n\n\tbindUri, err := url.Parse(address)\n\tif err != nil {\n\t\tlog.Fatal(fmt.Errorf(\"failed to parse bind URL: %w\", err))\n\t}\n\n\tswitch bindUri.Scheme {\n\tcase \"unix\":\n\t\treturn \"unix\", bindUri.Path\n\tcase \"tcp\", \"http\", \"https\":\n\t\treturn \"tcp\", bindUri.Host\n\tdefault:\n\t\tlog.Fatal(fmt.Errorf(\"unsupported network scheme %s in address %s\", bindUri.Scheme, address))\n\t}\n\treturn \"\", address\n}\n\nfunc setupListener(network string, address string) (net.Listener, string) {\n\tformattedAddress := \"\"\n\n\tif network == \"\" {\n\t\t// keep compatibility\n\t\tnetwork, address = parseBindNetFromAddr(address)\n\t}\n\n\tswitch network {\n\tcase \"unix\":\n\t\tformattedAddress = \"unix:\" + address\n\tcase \"tcp\":\n\t\tif strings.HasPrefix(address, \":\") { // assume it's just a port e.g. :4259\n\t\t\tformattedAddress = \"http://localhost\" + address\n\t\t} else {\n\t\t\tformattedAddress = \"http://\" + address\n\t\t}\n\tdefault:\n\t\tformattedAddress = fmt.Sprintf(`(%s) %s`, network, address)\n\t}\n\n\tlistener, err := net.Listen(network, address)\n\tif err != nil {\n\t\tlog.Fatal(fmt.Errorf(\"failed to bind to %s: %w\", formattedAddress, err))\n\t}\n\n\t// additional permission handling for unix sockets\n\tif network == \"unix\" {\n\t\tmode, err := strconv.ParseUint(*socketMode, 8, 0)\n\t\tif err != nil {\n\t\t\tlistener.Close()\n\t\t\tlog.Fatal(fmt.Errorf(\"could not parse socket mode %s: %w\", *socketMode, err))\n\t\t}\n\n\t\terr = os.Chmod(address, os.FileMode(mode))\n\t\tif err != nil {\n\t\t\terr := listener.Close()\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"failed to close listener: %v\", err)\n\t\t\t}\n\t\t\tlog.Fatal(fmt.Errorf(\"could not change socket mode: %w\", err))\n\t\t}\n\t}\n\n\treturn listener, formattedAddress\n}\n\nfunc makeReverseProxy(target string, targetSNI string, targetHost string, insecureSkipVerify bool) (http.Handler, error) {\n\ttargetUri, err := url.Parse(target)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to parse target URL: %w\", err)\n\t}\n\n\ttransport := http.DefaultTransport.(*http.Transport).Clone()\n\n\t// https://github.com/oauth2-proxy/oauth2-proxy/blob/4e2100a2879ef06aea1411790327019c1a09217c/pkg/upstream/http.go#L124\n\tif targetUri.Scheme == \"unix\" {\n\t\t// clean path up so we don't use the socket path in proxied requests\n\t\taddr := targetUri.Path\n\t\ttargetUri.Path = \"\"\n\t\t// tell transport how to dial unix sockets\n\t\ttransport.DialContext = func(ctx context.Context, _, _ string) (net.Conn, error) {\n\t\t\tdialer := net.Dialer{}\n\t\t\treturn dialer.DialContext(ctx, \"unix\", addr)\n\t\t}\n\t\t// tell transport how to handle the unix url scheme\n\t\ttransport.RegisterProtocol(\"unix\", libanubis.UnixRoundTripper{Transport: transport})\n\t}\n\n\tif insecureSkipVerify || targetSNI != \"\" {\n\t\ttransport.TLSClientConfig = &tls.Config{}\n\t\tif insecureSkipVerify {\n\t\t\tslog.Warn(\"TARGET_INSECURE_SKIP_VERIFY is set to true, TLS certificate validation will not be performed\", \"target\", target)\n\t\t\ttransport.TLSClientConfig.InsecureSkipVerify = true\n\t\t}\n\t\tif targetSNI != \"\" {\n\t\t\ttransport.TLSClientConfig.ServerName = targetSNI\n\t\t}\n\t}\n\n\trp := httputil.NewSingleHostReverseProxy(targetUri)\n\trp.Transport = transport\n\n\tif targetHost != \"\" {\n\t\toriginalDirector := rp.Director\n\t\trp.Director = func(req *http.Request) {\n\t\t\toriginalDirector(req)\n\t\t\treq.Host = targetHost\n\t\t}\n\t}\n\n\treturn rp, nil\n}\n\nfunc main() {\n\tflagenv.Parse()\n\tflag.Parse()\n\n\tif *versionFlag {\n\t\tfmt.Println(\"Anubis\", anubis.Version)\n\t\treturn\n\t}\n\n\tinternal.InitSlog(*slogLevel)\n\tinternal.SetHealth(\"anubis\", healthv1.HealthCheckResponse_NOT_SERVING)\n\n\tif *healthcheck {\n\t\tlog.Println(\"running healthcheck\")\n\t\tif err := doHealthCheck(); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\treturn\n\t}\n\n\tif *extractResources != \"\" {\n\t\tif err := extractEmbedFS(data.BotPolicies, \".\", *extractResources); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tif err := extractEmbedFS(web.Static, \"static\", *extractResources); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Printf(\"Extracted embedded static files to %s\\n\", *extractResources)\n\t\treturn\n\t}\n\n\t// install signal handler\n\tctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)\n\tdefer stop()\n\n\twg := new(sync.WaitGroup)\n\n\tif *metricsBind != \"\" {\n\t\twg.Add(1)\n\t\tgo metricsServer(ctx, wg.Done)\n\t}\n\n\tvar rp http.Handler\n\t// when using anubis via Systemd and environment variables, then it is not possible to set targe to an empty string but only to space\n\tif strings.TrimSpace(*target) != \"\" {\n\t\tvar err error\n\t\trp, err = makeReverseProxy(*target, *targetSNI, *targetHost, *targetInsecureSkipVerify)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"can't make reverse proxy: %v\", err)\n\t\t}\n\t}\n\n\tif *cookieDomain != \"\" && *cookieDynamicDomain {\n\t\tlog.Fatalf(\"you can't set COOKIE_DOMAIN and COOKIE_DYNAMIC_DOMAIN at the same time\")\n\t}\n\n\t// Thoth configuration\n\tswitch {\n\tcase *thothURL != \"\" && *thothToken == \"\":\n\t\tslog.Warn(\"THOTH_URL is set but no THOTH_TOKEN is set\")\n\tcase *thothURL == \"\" && *thothToken != \"\":\n\t\tslog.Warn(\"THOTH_TOKEN is set but no THOTH_URL is set\")\n\tcase *thothURL != \"\" && *thothToken != \"\":\n\t\tslog.Debug(\"connecting to Thoth\")\n\t\tthothClient, err := thoth.New(ctx, *thothURL, *thothToken, *thothInsecure)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"can't dial thoth at %s: %v\", *thothURL, err)\n\t\t}\n\n\t\tctx = thoth.With(ctx, thothClient)\n\t}\n\n\tpolicy, err := libanubis.LoadPoliciesOrDefault(ctx, *policyFname, *challengeDifficulty)\n\tif err != nil {\n\t\tlog.Fatalf(\"can't parse policy file: %v\", err)\n\t}\n\n\truleErrorIDs := make(map[string]string)\n\tfor _, rule := range policy.Bots {\n\t\tif rule.Action != config.RuleDeny {\n\t\t\tcontinue\n\t\t}\n\n\t\thash := rule.Hash()\n\t\truleErrorIDs[rule.Name] = hash\n\t}\n\n\t// replace the bot policy rules with a single rule that always benchmarks\n\tif *debugBenchmarkJS {\n\t\tpolicy.Bots = []botPolicy.Bot{{\n\t\t\tName: \"\",\n\t\t\tRules: botPolicy.NewHeaderExistsChecker(\"User-Agent\"),\n\t\t\tAction: config.RuleBenchmark,\n\t\t}}\n\t}\n\tif *basePrefix != \"\" && !strings.HasPrefix(*basePrefix, \"/\") {\n\t\tlog.Fatalf(\"[misconfiguration] base-prefix must start with a slash, eg: /%s\", *basePrefix)\n\t} else if strings.HasSuffix(*basePrefix, \"/\") {\n\t\tlog.Fatalf(\"[misconfiguration] base-prefix must not end with a slash\")\n\t}\n\tif *stripBasePrefix && *basePrefix == \"\" {\n\t\tlog.Fatalf(\"[misconfiguration] strip-base-prefix is set to true, but base-prefix is not set, \" +\n\t\t\t\"this may result in unexpected behavior\")\n\t}\n\n\tvar ed25519Priv ed25519.PrivateKey\n\tif *hs512Secret != \"\" && (*ed25519PrivateKeyHex != \"\" || *ed25519PrivateKeyHexFile != \"\") {\n\t\tlog.Fatal(\"do not specify both HS512 and ED25519 secrets\")\n\t} else if *hs512Secret != \"\" {\n\t\ted25519Priv = ed25519.PrivateKey(*hs512Secret)\n\t} else if *ed25519PrivateKeyHex != \"\" && *ed25519PrivateKeyHexFile != \"\" {\n\t\tlog.Fatal(\"do not specify both ED25519_PRIVATE_KEY_HEX and ED25519_PRIVATE_KEY_HEX_FILE\")\n\t} else if *ed25519PrivateKeyHex != \"\" {\n\t\ted25519Priv, err = keyFromHex(*ed25519PrivateKeyHex)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to parse and validate ED25519_PRIVATE_KEY_HEX: %v\", err)\n\t\t}\n\t} else if *ed25519PrivateKeyHexFile != \"\" {\n\t\thexFile, err := os.ReadFile(*ed25519PrivateKeyHexFile)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to read ED25519_PRIVATE_KEY_HEX_FILE %s: %v\", *ed25519PrivateKeyHexFile, err)\n\t\t}\n\n\t\ted25519Priv, err = keyFromHex(string(bytes.TrimSpace(hexFile)))\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to parse and validate content of ED25519_PRIVATE_KEY_HEX_FILE: %v\", err)\n\t\t}\n\t} else {\n\t\t_, ed25519Priv, err = ed25519.GenerateKey(rand.Reader)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to generate ed25519 key: %v\", err)\n\t\t}\n\n\t\tslog.Warn(\"generating random key, Anubis will have strange behavior when multiple instances are behind the same load balancer target, for more information: see https://anubis.techaro.lol/docs/admin/installation#key-generation\")\n\t}\n\n\tvar redirectDomainsList []string\n\tif *redirectDomains != \"\" {\n\t\tdomains := strings.Split(*redirectDomains, \",\")\n\t\tfor _, domain := range domains {\n\t\t\t_, err = url.Parse(domain)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"cannot parse redirect-domain %q: %s\", domain, err.Error())\n\t\t\t}\n\t\t\tredirectDomainsList = append(redirectDomainsList, strings.TrimSpace(domain))\n\t\t}\n\t} else {\n\t\tslog.Warn(\"REDIRECT_DOMAINS is not set, Anubis will only redirect to the same domain a request is coming from, see https://anubis.techaro.lol/docs/admin/configuration/redirect-domains\")\n\t}\n\n\tanubis.CookieName = *cookiePrefix + \"-auth\"\n\tanubis.TestCookieName = *cookiePrefix + \"-cookie-verification\"\n\tanubis.ForcedLanguage = *forcedLanguage\n\n\t// If OpenGraph configuration values are not set in the config file, use the\n\t// values from flags / envvars.\n\tif !policy.OpenGraph.Enabled {\n\t\tpolicy.OpenGraph.Enabled = *ogPassthrough\n\t\tpolicy.OpenGraph.ConsiderHost = *ogCacheConsiderHost\n\t\tpolicy.OpenGraph.TimeToLive = *ogTimeToLive\n\t\tpolicy.OpenGraph.Override = map[string]string{}\n\t}\n\n\ts, err := libanubis.New(libanubis.Options{\n\t\tBasePrefix: *basePrefix,\n\t\tStripBasePrefix: *stripBasePrefix,\n\t\tNext: rp,\n\t\tPolicy: policy,\n\t\tServeRobotsTXT: *robotsTxt,\n\t\tED25519PrivateKey: ed25519Priv,\n\t\tHS512Secret: []byte(*hs512Secret),\n\t\tCookieDomain: *cookieDomain,\n\t\tCookieDynamicDomain: *cookieDynamicDomain,\n\t\tCookieExpiration: *cookieExpiration,\n\t\tCookiePartitioned: *cookiePartitioned,\n\t\tRedirectDomains: redirectDomainsList,\n\t\tTarget: *target,\n\t\tWebmasterEmail: *webmasterEmail,\n\t\tOpenGraph: policy.OpenGraph,\n\t\tCookieSecure: *cookieSecure,\n\t})\n\tif err != nil {\n\t\tlog.Fatalf(\"can't construct libanubis.Server: %v\", err)\n\t}\n\n\tvar h http.Handler\n\th = s\n\th = internal.RemoteXRealIP(*useRemoteAddress, *bindNetwork, h)\n\th = internal.XForwardedForToXRealIP(h)\n\th = internal.XForwardedForUpdate(*xffStripPrivate, h)\n\th = internal.JA4H(h)\n\n\tsrv := http.Server{Handler: h, ErrorLog: internal.GetFilteredHTTPLogger()}\n\tlistener, listenerUrl := setupListener(*bindNetwork, *bind)\n\tslog.Info(\n\t\t\"listening\",\n\t\t\"url\", listenerUrl,\n\t\t\"difficulty\", *challengeDifficulty,\n\t\t\"serveRobotsTXT\", *robotsTxt,\n\t\t\"target\", *target,\n\t\t\"version\", anubis.Version,\n\t\t\"use-remote-address\", *useRemoteAddress,\n\t\t\"debug-benchmark-js\", *debugBenchmarkJS,\n\t\t\"og-passthrough\", *ogPassthrough,\n\t\t\"og-expiry-time\", *ogTimeToLive,\n\t\t\"base-prefix\", *basePrefix,\n\t\t\"cookie-expiration-time\", *cookieExpiration,\n\t\t\"rule-error-ids\", ruleErrorIDs,\n\t)\n\n\tgo func() {\n\t\t<-ctx.Done()\n\t\tc, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\t\tdefer cancel()\n\t\tif err := srv.Shutdown(c); err != nil {\n\t\t\tlog.Printf(\"cannot shut down: %v\", err)\n\t\t}\n\t}()\n\n\tinternal.SetHealth(\"anubis\", healthv1.HealthCheckResponse_SERVING)\n\n\tif err := srv.Serve(listener); !errors.Is(err, http.ErrServerClosed) {\n\t\tlog.Fatal(err)\n\t}\n\twg.Wait()\n}\n\nfunc metricsServer(ctx context.Context, done func()) {\n\tdefer done()\n\n\tmux := http.NewServeMux()\n\tmux.Handle(\"/metrics\", promhttp.Handler())\n\tmux.HandleFunc(\"/healthz\", func(w http.ResponseWriter, r *http.Request) {\n\t\tst, ok := internal.GetHealth(\"anubis\")\n\t\tif !ok {\n\t\t\tslog.Error(\"health service anubis does not exist, file a bug\")\n\t\t}\n\n\t\tswitch st {\n\t\tcase healthv1.HealthCheckResponse_NOT_SERVING:\n\t\t\thttp.Error(w, \"NOT OK\", http.StatusInternalServerError)\n\t\t\treturn\n\t\tcase healthv1.HealthCheckResponse_SERVING:\n\t\t\tfmt.Fprintln(w, \"OK\")\n\t\t\treturn\n\t\tdefault:\n\t\t\thttp.Error(w, \"UNKNOWN\", http.StatusFailedDependency)\n\t\t\treturn\n\t\t}\n\t})\n\n\tsrv := http.Server{Handler: mux, ErrorLog: internal.GetFilteredHTTPLogger()}\n\tlistener, metricsUrl := setupListener(*metricsBindNetwork, *metricsBind)\n\tslog.Debug(\"listening for metrics\", \"url\", metricsUrl)\n\n\tgo func() {\n\t\t<-ctx.Done()\n\t\tc, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\t\tdefer cancel()\n\t\tif err := srv.Shutdown(c); err != nil {\n\t\t\tlog.Printf(\"cannot shut down: %v\", err)\n\t\t}\n\t}()\n\n\tif err := srv.Serve(listener); !errors.Is(err, http.ErrServerClosed) {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc extractEmbedFS(fsys embed.FS, root string, destDir string) error {\n\treturn fs.WalkDir(fsys, root, func(path string, d fs.DirEntry, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\trelPath, err := filepath.Rel(root, path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdestPath := filepath.Join(destDir, root, relPath)\n\n\t\tif d.IsDir() {\n\t\t\treturn os.MkdirAll(destPath, 0o700)\n\t\t}\n\n\t\tembeddedData, err := fs.ReadFile(fsys, path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn os.WriteFile(destPath, embeddedData, 0o644)\n\t})\n}\n"], ["/anubis/internal/headers.go", "package internal\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/netip\"\n\t\"strings\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/sebest/xff\"\n)\n\n// TODO: move into config\ntype XFFComputePreferences struct {\n\tStripPrivate bool\n\tStripLoopback bool\n\tStripCGNAT bool\n\tStripLLU bool\n\tFlatten bool\n}\n\nvar CGNat = netip.MustParsePrefix(\"100.64.0.0/10\")\n\n// UnchangingCache sets the Cache-Control header to cache a response for 1 year if\n// and only if the application is compiled in \"release\" mode by Docker.\nfunc UnchangingCache(next http.Handler) http.Handler {\n\t//goland:noinspection GoBoolExpressions\n\tif anubis.Version == \"devel\" {\n\t\treturn next\n\t}\n\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Cache-Control\", \"public, max-age=31536000\")\n\t\tnext.ServeHTTP(w, r)\n\t})\n}\n\n// RemoteXRealIP sets the X-Real-Ip header to the request's real IP if\n// the setting is enabled by the user.\nfunc RemoteXRealIP(useRemoteAddress bool, bindNetwork string, next http.Handler) http.Handler {\n\tif !useRemoteAddress {\n\t\tslog.Debug(\"skipping middleware, useRemoteAddress is empty\")\n\t\treturn next\n\t}\n\n\tif bindNetwork == \"unix\" {\n\t\t// For local sockets there is no real remote address but the localhost\n\t\t// address should be sensible.\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tr.Header.Set(\"X-Real-Ip\", \"127.0.0.1\")\n\t\t\tnext.ServeHTTP(w, r)\n\t\t})\n\t}\n\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\thost, _, err := net.SplitHostPort(r.RemoteAddr)\n\t\tif err != nil {\n\t\t\tpanic(err) // this should never happen\n\t\t}\n\t\tr.Header.Set(\"X-Real-Ip\", host)\n\t\tnext.ServeHTTP(w, r)\n\t})\n}\n\n// XForwardedForToXRealIP sets the X-Real-Ip header based on the contents\n// of the X-Forwarded-For header.\nfunc XForwardedForToXRealIP(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif xffHeader := r.Header.Get(\"X-Forwarded-For\"); r.Header.Get(\"X-Real-Ip\") == \"\" && xffHeader != \"\" {\n\t\t\tip := xff.Parse(xffHeader)\n\t\t\tslog.Debug(\"setting x-real-ip\", \"val\", ip)\n\t\t\tr.Header.Set(\"X-Real-Ip\", ip)\n\t\t}\n\n\t\tnext.ServeHTTP(w, r)\n\t})\n}\n\n// XForwardedForUpdate sets or updates the X-Forwarded-For header, adding\n// the known remote address to an existing chain if present\nfunc XForwardedForUpdate(stripPrivate bool, next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tdefer next.ServeHTTP(w, r)\n\n\t\tpref := XFFComputePreferences{\n\t\t\tStripPrivate: stripPrivate,\n\t\t\tStripLoopback: true,\n\t\t\tStripCGNAT: true,\n\t\t\tFlatten: true,\n\t\t\tStripLLU: true,\n\t\t}\n\n\t\tremoteAddr := r.RemoteAddr\n\t\torigXFFHeader := r.Header.Get(\"X-Forwarded-For\")\n\n\t\tif remoteAddr == \"@\" {\n\t\t\t// remote is a unix socket\n\t\t\t// do not touch chain\n\t\t\treturn\n\t\t}\n\n\t\txffHeaderString, err := computeXFFHeader(remoteAddr, origXFFHeader, pref)\n\t\tif err != nil {\n\t\t\tslog.Debug(\"computing X-Forwarded-For header failed\", \"err\", err)\n\t\t\treturn\n\t\t}\n\n\t\tif len(xffHeaderString) == 0 {\n\t\t\tr.Header.Del(\"X-Forwarded-For\")\n\t\t} else {\n\t\t\tr.Header.Set(\"X-Forwarded-For\", xffHeaderString)\n\t\t}\n\t})\n}\n\nvar (\n\tErrCantSplitHostParse = errors.New(\"internal: unable to net.SplitHostParse\")\n\tErrCantParseRemoteIP = errors.New(\"internal: unable to parse remote IP\")\n)\n\nfunc computeXFFHeader(remoteAddr string, origXFFHeader string, pref XFFComputePreferences) (string, error) {\n\tremoteIP, _, err := net.SplitHostPort(remoteAddr)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"%w: %w\", ErrCantSplitHostParse, err)\n\t}\n\tparsedRemoteIP, err := netip.ParseAddr(remoteIP)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"%w: %w\", ErrCantParseRemoteIP, err)\n\t}\n\n\torigForwardedList := make([]string, 0, 4)\n\tif origXFFHeader != \"\" {\n\t\torigForwardedList = strings.Split(origXFFHeader, \",\")\n\t\tfor i := range origForwardedList {\n\t\t\torigForwardedList[i] = strings.TrimSpace(origForwardedList[i])\n\t\t}\n\t}\n\torigForwardedList = append(origForwardedList, parsedRemoteIP.String())\n\tforwardedList := make([]string, 0, len(origForwardedList))\n\t// this behavior is equivalent to\n\t// ingress-nginx \"compute-full-forwarded-for\"\n\t// https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/configmap/#compute-full-forwarded-for\n\t//\n\t// this would be the correct place to strip and/or flatten this list\n\t//\n\t// strip - iterate backwards and eliminate configured trusted IPs\n\t// flatten - only return the last element to avoid spoofing confusion\n\t//\n\t// many applications handle this in different ways, but\n\t// generally they'd be expected to do these two things on\n\t// their own end to find the first non-spoofed IP\n\tfor i := len(origForwardedList) - 1; i >= 0; i-- {\n\t\tsegmentIP, err := netip.ParseAddr(origForwardedList[i])\n\t\tif err != nil {\n\t\t\t// can't assess this element, so the remainder of the chain\n\t\t\t// can't be trusted. not a fatal error, since anyone can\n\t\t\t// spoof an XFF header\n\t\t\tslog.Debug(\"failed to parse XFF segment\", \"err\", err)\n\t\t\tbreak\n\t\t}\n\t\tif pref.StripPrivate && segmentIP.IsPrivate() {\n\t\t\tcontinue\n\t\t}\n\t\tif pref.StripLoopback && segmentIP.IsLoopback() {\n\t\t\tcontinue\n\t\t}\n\t\tif pref.StripLLU && segmentIP.IsLinkLocalUnicast() {\n\t\t\tcontinue\n\t\t}\n\t\tif pref.StripCGNAT && CGNat.Contains(segmentIP) {\n\t\t\tcontinue\n\t\t}\n\t\tforwardedList = append([]string{segmentIP.String()}, forwardedList...)\n\t}\n\tvar xffHeaderString string\n\tif len(forwardedList) == 0 {\n\t\txffHeaderString = \"\"\n\t\treturn xffHeaderString, nil\n\t}\n\tif pref.Flatten {\n\t\txffHeaderString = forwardedList[len(forwardedList)-1]\n\t} else {\n\t\txffHeaderString = strings.Join(forwardedList, \",\")\n\t}\n\treturn xffHeaderString, nil\n}\n\n// NoStoreCache sets the Cache-Control header to no-store for the response.\nfunc NoStoreCache(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Cache-Control\", \"no-store\")\n\t\tnext.ServeHTTP(w, r)\n\t})\n}\n\n// NoBrowsing prevents directory browsing by returning a 404 for any request that ends with a \"/\".\nfunc NoBrowsing(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif strings.HasSuffix(r.URL.Path, \"/\") {\n\t\t\thttp.NotFound(w, r)\n\t\t\treturn\n\t\t}\n\t\tnext.ServeHTTP(w, r)\n\t})\n}\n"], ["/anubis/lib/policy/config/config.go", "package config\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/fs\"\n\t\"net\"\n\t\"net/http\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis/data\"\n\t\"k8s.io/apimachinery/pkg/util/yaml\"\n)\n\nvar (\n\tErrNoBotRulesDefined = errors.New(\"config: must define at least one (1) bot rule\")\n\tErrBotMustHaveName = errors.New(\"config.Bot: must set name\")\n\tErrBotMustHaveUserAgentOrPath = errors.New(\"config.Bot: must set either user_agent_regex, path_regex, headers_regex, or remote_addresses\")\n\tErrBotMustHaveUserAgentOrPathNotBoth = errors.New(\"config.Bot: must set either user_agent_regex, path_regex, and not both\")\n\tErrUnknownAction = errors.New(\"config.Bot: unknown action\")\n\tErrInvalidUserAgentRegex = errors.New(\"config.Bot: invalid user agent regex\")\n\tErrInvalidPathRegex = errors.New(\"config.Bot: invalid path regex\")\n\tErrInvalidHeadersRegex = errors.New(\"config.Bot: invalid headers regex\")\n\tErrInvalidCIDR = errors.New(\"config.Bot: invalid CIDR\")\n\tErrRegexEndsWithNewline = errors.New(\"config.Bot: regular expression ends with newline (try >- instead of > in yaml)\")\n\tErrInvalidImportStatement = errors.New(\"config.ImportStatement: invalid source file\")\n\tErrCantSetBotAndImportValuesAtOnce = errors.New(\"config.BotOrImport: can't set bot rules and import values at the same time\")\n\tErrMustSetBotOrImportRules = errors.New(\"config.BotOrImport: rule definition is invalid, you must set either bot rules or an import statement, not both\")\n\tErrStatusCodeNotValid = errors.New(\"config.StatusCode: status code not valid, must be between 100 and 599\")\n)\n\ntype Rule string\n\nconst (\n\tRuleUnknown Rule = \"\"\n\tRuleAllow Rule = \"ALLOW\"\n\tRuleDeny Rule = \"DENY\"\n\tRuleChallenge Rule = \"CHALLENGE\"\n\tRuleWeigh Rule = \"WEIGH\"\n\tRuleBenchmark Rule = \"DEBUG_BENCHMARK\"\n)\n\nfunc (r Rule) Valid() error {\n\tswitch r {\n\tcase RuleAllow, RuleDeny, RuleChallenge, RuleWeigh, RuleBenchmark:\n\t\treturn nil\n\tdefault:\n\t\treturn ErrUnknownAction\n\t}\n}\n\nconst DefaultAlgorithm = \"fast\"\n\ntype BotConfig struct {\n\tUserAgentRegex *string `json:\"user_agent_regex,omitempty\" yaml:\"user_agent_regex,omitempty\"`\n\tPathRegex *string `json:\"path_regex,omitempty\" yaml:\"path_regex,omitempty\"`\n\tHeadersRegex map[string]string `json:\"headers_regex,omitempty\" yaml:\"headers_regex,omitempty\"`\n\tExpression *ExpressionOrList `json:\"expression,omitempty\" yaml:\"expression,omitempty\"`\n\tChallenge *ChallengeRules `json:\"challenge,omitempty\" yaml:\"challenge,omitempty\"`\n\tWeight *Weight `json:\"weight,omitempty\" yaml:\"weight,omitempty\"`\n\tName string `json:\"name\" yaml:\"name\"`\n\tAction Rule `json:\"action\" yaml:\"action\"`\n\tRemoteAddr []string `json:\"remote_addresses,omitempty\" yaml:\"remote_addresses,omitempty\"`\n\n\t// Thoth features\n\tGeoIP *GeoIP `json:\"geoip,omitempty\"`\n\tASNs *ASNs `json:\"asns,omitempty\"`\n}\n\nfunc (b BotConfig) Zero() bool {\n\tfor _, cond := range []bool{\n\t\tb.Name != \"\",\n\t\tb.UserAgentRegex != nil,\n\t\tb.PathRegex != nil,\n\t\tlen(b.HeadersRegex) != 0,\n\t\tb.Action != \"\",\n\t\tlen(b.RemoteAddr) != 0,\n\t\tb.Challenge != nil,\n\t\tb.GeoIP != nil,\n\t\tb.ASNs != nil,\n\t} {\n\t\tif cond {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc (b *BotConfig) Valid() error {\n\tvar errs []error\n\n\tif b.Name == \"\" {\n\t\terrs = append(errs, ErrBotMustHaveName)\n\t}\n\n\tallFieldsEmpty := b.UserAgentRegex == nil &&\n\t\tb.PathRegex == nil &&\n\t\tlen(b.RemoteAddr) == 0 &&\n\t\tlen(b.HeadersRegex) == 0 &&\n\t\tb.ASNs == nil &&\n\t\tb.GeoIP == nil\n\n\tif allFieldsEmpty && b.Expression == nil {\n\t\terrs = append(errs, ErrBotMustHaveUserAgentOrPath)\n\t}\n\n\tif b.UserAgentRegex != nil && b.PathRegex != nil {\n\t\terrs = append(errs, ErrBotMustHaveUserAgentOrPathNotBoth)\n\t}\n\n\tif b.UserAgentRegex != nil {\n\t\tif strings.HasSuffix(*b.UserAgentRegex, \"\\n\") {\n\t\t\terrs = append(errs, fmt.Errorf(\"%w: user agent regex: %q\", ErrRegexEndsWithNewline, *b.UserAgentRegex))\n\t\t}\n\n\t\tif _, err := regexp.Compile(*b.UserAgentRegex); err != nil {\n\t\t\terrs = append(errs, ErrInvalidUserAgentRegex, err)\n\t\t}\n\t}\n\n\tif b.PathRegex != nil {\n\t\tif strings.HasSuffix(*b.PathRegex, \"\\n\") {\n\t\t\terrs = append(errs, fmt.Errorf(\"%w: path regex: %q\", ErrRegexEndsWithNewline, *b.PathRegex))\n\t\t}\n\n\t\tif _, err := regexp.Compile(*b.PathRegex); err != nil {\n\t\t\terrs = append(errs, ErrInvalidPathRegex, err)\n\t\t}\n\t}\n\n\tif len(b.HeadersRegex) > 0 {\n\t\tfor name, expr := range b.HeadersRegex {\n\t\t\tif name == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif strings.HasSuffix(expr, \"\\n\") {\n\t\t\t\terrs = append(errs, fmt.Errorf(\"%w: header %s regex: %q\", ErrRegexEndsWithNewline, name, expr))\n\t\t\t}\n\n\t\t\tif _, err := regexp.Compile(expr); err != nil {\n\t\t\t\terrs = append(errs, ErrInvalidHeadersRegex, err)\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(b.RemoteAddr) > 0 {\n\t\tfor _, cidr := range b.RemoteAddr {\n\t\t\tif _, _, err := net.ParseCIDR(cidr); err != nil {\n\t\t\t\terrs = append(errs, ErrInvalidCIDR, err)\n\t\t\t}\n\t\t}\n\t}\n\n\tif b.Expression != nil {\n\t\tif err := b.Expression.Valid(); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\tswitch b.Action {\n\tcase RuleAllow, RuleBenchmark, RuleChallenge, RuleDeny, RuleWeigh:\n\t\t// okay\n\tdefault:\n\t\terrs = append(errs, fmt.Errorf(\"%w: %q\", ErrUnknownAction, b.Action))\n\t}\n\n\tif b.Action == RuleChallenge && b.Challenge != nil {\n\t\tif err := b.Challenge.Valid(); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\tif b.Action == RuleWeigh && b.Weight == nil {\n\t\tb.Weight = &Weight{Adjust: 5}\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"config: bot entry for %q is not valid:\\n%w\", b.Name, errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n\ntype ChallengeRules struct {\n\tAlgorithm string `json:\"algorithm,omitempty\" yaml:\"algorithm,omitempty\"`\n\tDifficulty int `json:\"difficulty,omitempty\" yaml:\"difficulty,omitempty\"`\n\tReportAs int `json:\"report_as,omitempty\" yaml:\"report_as,omitempty\"`\n}\n\nvar (\n\tErrChallengeDifficultyTooLow = errors.New(\"config.ChallengeRules: difficulty is too low (must be >= 1)\")\n\tErrChallengeDifficultyTooHigh = errors.New(\"config.ChallengeRules: difficulty is too high (must be <= 64)\")\n\tErrChallengeMustHaveAlgorithm = errors.New(\"config.ChallengeRules: must have algorithm name set\")\n)\n\nfunc (cr ChallengeRules) Valid() error {\n\tvar errs []error\n\n\tif cr.Algorithm == \"\" {\n\t\terrs = append(errs, ErrChallengeMustHaveAlgorithm)\n\t}\n\n\tif cr.Difficulty < 1 {\n\t\terrs = append(errs, fmt.Errorf(\"%w, got: %d\", ErrChallengeDifficultyTooLow, cr.Difficulty))\n\t}\n\n\tif cr.Difficulty > 64 {\n\t\terrs = append(errs, fmt.Errorf(\"%w, got: %d\", ErrChallengeDifficultyTooHigh, cr.Difficulty))\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"config: challenge rules entry is not valid:\\n%w\", errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n\ntype ImportStatement struct {\n\tImport string `json:\"import\"`\n\tBots []BotConfig\n}\n\nfunc (is *ImportStatement) open() (fs.File, error) {\n\tif strings.HasPrefix(is.Import, \"(data)/\") {\n\t\tfname := strings.TrimPrefix(is.Import, \"(data)/\")\n\t\tfin, err := data.BotPolicies.Open(fname)\n\t\treturn fin, err\n\t}\n\n\treturn os.Open(is.Import)\n}\n\nfunc (is *ImportStatement) load() error {\n\tfin, err := is.open()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%w: %s: %w\", ErrInvalidImportStatement, is.Import, err)\n\t}\n\tdefer fin.Close()\n\n\tvar imported []BotOrImport\n\tvar result []BotConfig\n\n\tif err := yaml.NewYAMLToJSONDecoder(fin).Decode(&imported); err != nil {\n\t\treturn fmt.Errorf(\"can't parse %s: %w\", is.Import, err)\n\t}\n\n\tvar errs []error\n\n\tfor _, b := range imported {\n\t\tif err := b.Valid(); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\n\t\tif b.ImportStatement != nil {\n\t\t\tresult = append(result, b.ImportStatement.Bots...)\n\t\t}\n\n\t\tif b.BotConfig != nil {\n\t\t\tresult = append(result, *b.BotConfig)\n\t\t}\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"config %s is not valid:\\n%w\", is.Import, errors.Join(errs...))\n\t}\n\n\tis.Bots = result\n\n\treturn nil\n}\n\nfunc (is *ImportStatement) Valid() error {\n\treturn is.load()\n}\n\ntype BotOrImport struct {\n\t*BotConfig `json:\",inline\"`\n\t*ImportStatement `json:\",inline\"`\n}\n\nfunc (boi *BotOrImport) Valid() error {\n\tif boi.BotConfig != nil && boi.ImportStatement != nil {\n\t\treturn ErrCantSetBotAndImportValuesAtOnce\n\t}\n\n\tif boi.BotConfig != nil {\n\t\treturn boi.BotConfig.Valid()\n\t}\n\n\tif boi.ImportStatement != nil {\n\t\treturn boi.ImportStatement.Valid()\n\t}\n\n\treturn ErrMustSetBotOrImportRules\n}\n\ntype StatusCodes struct {\n\tChallenge int `json:\"CHALLENGE\"`\n\tDeny int `json:\"DENY\"`\n}\n\nfunc (sc StatusCodes) Valid() error {\n\tvar errs []error\n\n\tif sc.Challenge == 0 || (sc.Challenge < 100 && sc.Challenge >= 599) {\n\t\terrs = append(errs, fmt.Errorf(\"%w: challenge is %d\", ErrStatusCodeNotValid, sc.Challenge))\n\t}\n\n\tif sc.Deny == 0 || (sc.Deny < 100 && sc.Deny >= 599) {\n\t\terrs = append(errs, fmt.Errorf(\"%w: deny is %d\", ErrStatusCodeNotValid, sc.Deny))\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"status codes not valid:\\n%w\", errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n\ntype fileConfig struct {\n\tBots []BotOrImport `json:\"bots\"`\n\tDNSBL bool `json:\"dnsbl\"`\n\tOpenGraph openGraphFileConfig `json:\"openGraph,omitempty\"`\n\tImpressum *Impressum `json:\"impressum,omitempty\"`\n\tStatusCodes StatusCodes `json:\"status_codes\"`\n\tStore *Store `json:\"store\"`\n\tThresholds []Threshold `json:\"thresholds\"`\n}\n\nfunc (c *fileConfig) Valid() error {\n\tvar errs []error\n\n\tif len(c.Bots) == 0 {\n\t\terrs = append(errs, ErrNoBotRulesDefined)\n\t}\n\n\tfor i, b := range c.Bots {\n\t\tif err := b.Valid(); err != nil {\n\t\t\terrs = append(errs, fmt.Errorf(\"bot %d: %w\", i, err))\n\t\t}\n\t}\n\n\tif c.OpenGraph.Enabled {\n\t\tif err := c.OpenGraph.Valid(); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\tif err := c.StatusCodes.Valid(); err != nil {\n\t\terrs = append(errs, err)\n\t}\n\n\tfor i, t := range c.Thresholds {\n\t\tif err := t.Valid(); err != nil {\n\t\t\terrs = append(errs, fmt.Errorf(\"threshold %d: %w\", i, err))\n\t\t}\n\t}\n\n\tif c.Store != nil {\n\t\tif err := c.Store.Valid(); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"config is not valid:\\n%w\", errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n\nfunc Load(fin io.Reader, fname string) (*Config, error) {\n\tc := &fileConfig{\n\t\tStatusCodes: StatusCodes{\n\t\t\tChallenge: http.StatusOK,\n\t\t\tDeny: http.StatusOK,\n\t\t},\n\t\tStore: &Store{\n\t\t\tBackend: \"memory\",\n\t\t},\n\t}\n\n\tif err := yaml.NewYAMLToJSONDecoder(fin).Decode(&c); err != nil {\n\t\treturn nil, fmt.Errorf(\"can't parse policy config YAML %s: %w\", fname, err)\n\t}\n\n\tif err := c.Valid(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult := &Config{\n\t\tDNSBL: c.DNSBL,\n\t\tOpenGraph: OpenGraph{\n\t\t\tEnabled: c.OpenGraph.Enabled,\n\t\t\tConsiderHost: c.OpenGraph.ConsiderHost,\n\t\t\tOverride: c.OpenGraph.Override,\n\t\t},\n\t\tStatusCodes: c.StatusCodes,\n\t\tStore: c.Store,\n\t}\n\n\tif c.OpenGraph.TimeToLive != \"\" {\n\t\t// XXX(Xe): already validated in Valid()\n\t\togTTL, _ := time.ParseDuration(c.OpenGraph.TimeToLive)\n\t\tresult.OpenGraph.TimeToLive = ogTTL\n\t}\n\n\tvar validationErrs []error\n\n\tfor _, boi := range c.Bots {\n\t\tif boi.ImportStatement != nil {\n\t\t\tif err := boi.load(); err != nil {\n\t\t\t\tvalidationErrs = append(validationErrs, err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tresult.Bots = append(result.Bots, boi.ImportStatement.Bots...)\n\t\t}\n\n\t\tif boi.BotConfig != nil {\n\t\t\tif err := boi.BotConfig.Valid(); err != nil {\n\t\t\t\tvalidationErrs = append(validationErrs, err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tresult.Bots = append(result.Bots, *boi.BotConfig)\n\t\t}\n\t}\n\n\tif c.Impressum != nil {\n\t\tif err := c.Impressum.Valid(); err != nil {\n\t\t\tvalidationErrs = append(validationErrs, err)\n\t\t}\n\n\t\tresult.Impressum = c.Impressum\n\t}\n\n\tif len(c.Thresholds) == 0 {\n\t\tc.Thresholds = DefaultThresholds\n\t}\n\n\tfor _, t := range c.Thresholds {\n\t\tif err := t.Valid(); err != nil {\n\t\t\tvalidationErrs = append(validationErrs, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tresult.Thresholds = append(result.Thresholds, t)\n\t}\n\n\tif len(validationErrs) > 0 {\n\t\treturn nil, fmt.Errorf(\"errors validating policy config %s: %w\", fname, errors.Join(validationErrs...))\n\t}\n\n\treturn result, nil\n}\n\ntype Config struct {\n\tBots []BotConfig\n\tThresholds []Threshold\n\tDNSBL bool\n\tImpressum *Impressum\n\tOpenGraph OpenGraph\n\tStatusCodes StatusCodes\n\tStore *Store\n}\n\nfunc (c Config) Valid() error {\n\tvar errs []error\n\n\tif len(c.Bots) == 0 {\n\t\terrs = append(errs, ErrNoBotRulesDefined)\n\t}\n\n\tfor _, b := range c.Bots {\n\t\tif err := b.Valid(); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"config is not valid:\\n%w\", errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n"], ["/anubis/lib/thoth/geoipchecker.go", "package thoth\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net/http\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis/lib/policy/checker\"\n\tiptoasnv1 \"github.com/TecharoHQ/thoth-proto/gen/techaro/thoth/iptoasn/v1\"\n)\n\nfunc (c *Client) GeoIPCheckerFor(countries []string) checker.Impl {\n\tcountryMap := map[string]struct{}{}\n\tvar sb strings.Builder\n\tfmt.Fprintln(&sb, \"GeoIPChecker\")\n\tfor _, cc := range countries {\n\t\tcountryMap[cc] = struct{}{}\n\t\tfmt.Fprintln(&sb, cc)\n\t}\n\n\treturn &GeoIPChecker{\n\t\tIPToASN: c.IPToASN,\n\t\tCountries: countryMap,\n\t\thash: sb.String(),\n\t}\n}\n\ntype GeoIPChecker struct {\n\tIPToASN iptoasnv1.IpToASNServiceClient\n\tCountries map[string]struct{}\n\thash string\n}\n\nfunc (gipc *GeoIPChecker) Check(r *http.Request) (bool, error) {\n\tctx, cancel := context.WithTimeout(r.Context(), 500*time.Millisecond)\n\tdefer cancel()\n\n\tipInfo, err := gipc.IPToASN.Lookup(ctx, &iptoasnv1.LookupRequest{\n\t\tIpAddress: r.Header.Get(\"X-Real-Ip\"),\n\t})\n\tif err != nil {\n\t\tswitch {\n\t\tcase errors.Is(err, context.DeadlineExceeded):\n\t\t\tslog.Debug(\"error contacting thoth\", \"err\", err, \"actionable\", false)\n\t\t\treturn false, nil\n\t\tdefault:\n\t\t\tslog.Error(\"error contacting thoth, please contact support\", \"err\", err, \"actionable\", true)\n\t\t\treturn false, nil\n\t\t}\n\t}\n\n\t// If IP is not publicly announced, return false\n\tif !ipInfo.GetAnnounced() {\n\t\treturn false, nil\n\t}\n\n\t_, ok := gipc.Countries[strings.ToLower(ipInfo.GetCountryCode())]\n\n\treturn ok, nil\n}\n\nfunc (gipc *GeoIPChecker) Hash() string {\n\treturn gipc.hash\n}\n"], ["/anubis/lib/thoth/asnchecker.go", "package thoth\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net/http\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis/internal\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/checker\"\n\tiptoasnv1 \"github.com/TecharoHQ/thoth-proto/gen/techaro/thoth/iptoasn/v1\"\n)\n\nfunc (c *Client) ASNCheckerFor(asns []uint32) checker.Impl {\n\tasnMap := map[uint32]struct{}{}\n\tvar sb strings.Builder\n\tfmt.Fprintln(&sb, \"ASNChecker\")\n\tfor _, asn := range asns {\n\t\tasnMap[asn] = struct{}{}\n\t\tfmt.Fprintln(&sb, \"AS\", asn)\n\t}\n\n\treturn &ASNChecker{\n\t\tiptoasn: c.IPToASN,\n\t\tasns: asnMap,\n\t\thash: internal.FastHash(sb.String()),\n\t}\n}\n\ntype ASNChecker struct {\n\tiptoasn iptoasnv1.IpToASNServiceClient\n\tasns map[uint32]struct{}\n\thash string\n}\n\nfunc (asnc *ASNChecker) Check(r *http.Request) (bool, error) {\n\tctx, cancel := context.WithTimeout(r.Context(), 500*time.Millisecond)\n\tdefer cancel()\n\n\tipInfo, err := asnc.iptoasn.Lookup(ctx, &iptoasnv1.LookupRequest{\n\t\tIpAddress: r.Header.Get(\"X-Real-Ip\"),\n\t})\n\tif err != nil {\n\t\tswitch {\n\t\tcase errors.Is(err, context.DeadlineExceeded):\n\t\t\tslog.Debug(\"error contacting thoth\", \"err\", err, \"actionable\", false)\n\t\t\treturn false, nil\n\t\tdefault:\n\t\t\tslog.Error(\"error contacting thoth, please contact support\", \"err\", err, \"actionable\", true)\n\t\t\treturn false, nil\n\t\t}\n\t}\n\n\t// If IP is not publicly announced, return false\n\tif !ipInfo.GetAnnounced() {\n\t\treturn false, nil\n\t}\n\n\t_, ok := asnc.asns[uint32(ipInfo.GetAsNumber())]\n\n\treturn ok, nil\n}\n\nfunc (asnc *ASNChecker) Hash() string {\n\treturn asnc.hash\n}\n"], ["/anubis/lib/thoth/thothmock/iptoasn.go", "package thothmock\n\nimport (\n\t\"context\"\n\t\"net/netip\"\n\n\tiptoasnv1 \"github.com/TecharoHQ/thoth-proto/gen/techaro/thoth/iptoasn/v1\"\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/status\"\n)\n\nfunc MockIpToASNService() *IpToASNService {\n\tresponses := map[string]*iptoasnv1.LookupResponse{\n\t\t\"127.0.0.1\": {Announced: false},\n\t\t\"::1\": {Announced: false},\n\t\t\"10.10.10.10\": {\n\t\t\tAnnounced: true,\n\t\t\tAsNumber: 13335,\n\t\t\tCidr: []string{\"1.1.1.0/24\"},\n\t\t\tCountryCode: \"US\",\n\t\t\tDescription: \"Cloudflare\",\n\t\t},\n\t\t\"2.2.2.2\": {\n\t\t\tAnnounced: true,\n\t\t\tAsNumber: 420,\n\t\t\tCidr: []string{\"2.2.2.0/24\"},\n\t\t\tCountryCode: \"CA\",\n\t\t\tDescription: \"test canada\",\n\t\t},\n\t\t\"1.1.1.1\": {\n\t\t\tAnnounced: true,\n\t\t\tAsNumber: 13335,\n\t\t\tCidr: []string{\"1.1.1.0/24\"},\n\t\t\tCountryCode: \"US\",\n\t\t\tDescription: \"Cloudflare\",\n\t\t},\n\t}\n\n\treturn &IpToASNService{Responses: responses}\n}\n\ntype IpToASNService struct {\n\tiptoasnv1.UnimplementedIpToASNServiceServer\n\tResponses map[string]*iptoasnv1.LookupResponse\n}\n\nfunc (ip2asn *IpToASNService) Lookup(ctx context.Context, lr *iptoasnv1.LookupRequest, opts ...grpc.CallOption) (*iptoasnv1.LookupResponse, error) {\n\tif _, err := netip.ParseAddr(lr.GetIpAddress()); err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, ok := ip2asn.Responses[lr.GetIpAddress()]\n\tif !ok {\n\t\treturn nil, status.Error(codes.NotFound, \"IP address not found in mock\")\n\t}\n\n\treturn resp, nil\n}\n"], ["/anubis/lib/policy/policy.go", "package policy\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log/slog\"\n\t\"sync/atomic\"\n\n\t\"github.com/TecharoHQ/anubis/lib/policy/checker\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n\t\"github.com/TecharoHQ/anubis/lib/thoth\"\n\t\"github.com/prometheus/client_golang/prometheus\"\n\t\"github.com/prometheus/client_golang/prometheus/promauto\"\n\n\t_ \"github.com/TecharoHQ/anubis/lib/store/all\"\n)\n\nvar (\n\tApplications = promauto.NewCounterVec(prometheus.CounterOpts{\n\t\tName: \"anubis_policy_results\",\n\t\tHelp: \"The results of each policy rule\",\n\t}, []string{\"rule\", \"action\"})\n\n\tErrChallengeRuleHasWrongAlgorithm = errors.New(\"config.Bot.ChallengeRules: algorithm is invalid\")\n\twarnedAboutThresholds = &atomic.Bool{}\n)\n\ntype ParsedConfig struct {\n\torig *config.Config\n\n\tBots []Bot\n\tThresholds []*Threshold\n\tDNSBL bool\n\tImpressum *config.Impressum\n\tOpenGraph config.OpenGraph\n\tDefaultDifficulty int\n\tStatusCodes config.StatusCodes\n\tStore store.Interface\n}\n\nfunc newParsedConfig(orig *config.Config) *ParsedConfig {\n\treturn &ParsedConfig{\n\t\torig: orig,\n\t\tOpenGraph: orig.OpenGraph,\n\t\tStatusCodes: orig.StatusCodes,\n\t}\n}\n\nfunc ParseConfig(ctx context.Context, fin io.Reader, fname string, defaultDifficulty int) (*ParsedConfig, error) {\n\tc, err := config.Load(fin, fname)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar validationErrs []error\n\n\ttc, hasThothClient := thoth.FromContext(ctx)\n\n\tresult := newParsedConfig(c)\n\tresult.DefaultDifficulty = defaultDifficulty\n\n\tfor _, b := range c.Bots {\n\t\tif berr := b.Valid(); berr != nil {\n\t\t\tvalidationErrs = append(validationErrs, berr)\n\t\t\tcontinue\n\t\t}\n\n\t\tparsedBot := Bot{\n\t\t\tName: b.Name,\n\t\t\tAction: b.Action,\n\t\t}\n\n\t\tcl := checker.List{}\n\n\t\tif len(b.RemoteAddr) > 0 {\n\t\t\tc, err := NewRemoteAddrChecker(b.RemoteAddr)\n\t\t\tif err != nil {\n\t\t\t\tvalidationErrs = append(validationErrs, fmt.Errorf(\"while processing rule %s remote addr set: %w\", b.Name, err))\n\t\t\t} else {\n\t\t\t\tcl = append(cl, c)\n\t\t\t}\n\t\t}\n\n\t\tif b.UserAgentRegex != nil {\n\t\t\tc, err := NewUserAgentChecker(*b.UserAgentRegex)\n\t\t\tif err != nil {\n\t\t\t\tvalidationErrs = append(validationErrs, fmt.Errorf(\"while processing rule %s user agent regex: %w\", b.Name, err))\n\t\t\t} else {\n\t\t\t\tcl = append(cl, c)\n\t\t\t}\n\t\t}\n\n\t\tif b.PathRegex != nil {\n\t\t\tc, err := NewPathChecker(*b.PathRegex)\n\t\t\tif err != nil {\n\t\t\t\tvalidationErrs = append(validationErrs, fmt.Errorf(\"while processing rule %s path regex: %w\", b.Name, err))\n\t\t\t} else {\n\t\t\t\tcl = append(cl, c)\n\t\t\t}\n\t\t}\n\n\t\tif len(b.HeadersRegex) > 0 {\n\t\t\tc, err := NewHeadersChecker(b.HeadersRegex)\n\t\t\tif err != nil {\n\t\t\t\tvalidationErrs = append(validationErrs, fmt.Errorf(\"while processing rule %s headers regex map: %w\", b.Name, err))\n\t\t\t} else {\n\t\t\t\tcl = append(cl, c)\n\t\t\t}\n\t\t}\n\n\t\tif b.Expression != nil {\n\t\t\tc, err := NewCELChecker(b.Expression)\n\t\t\tif err != nil {\n\t\t\t\tvalidationErrs = append(validationErrs, fmt.Errorf(\"while processing rule %s expressions: %w\", b.Name, err))\n\t\t\t} else {\n\t\t\t\tcl = append(cl, c)\n\t\t\t}\n\t\t}\n\n\t\tif b.ASNs != nil {\n\t\t\tif !hasThothClient {\n\t\t\t\tslog.Warn(\"You have specified a Thoth specific check but you have no Thoth client configured. Please read https://anubis.techaro.lol/docs/admin/thoth for more information\", \"check\", \"asn\", \"settings\", b.ASNs)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tcl = append(cl, tc.ASNCheckerFor(b.ASNs.Match))\n\t\t}\n\n\t\tif b.GeoIP != nil {\n\t\t\tif !hasThothClient {\n\t\t\t\tslog.Warn(\"You have specified a Thoth specific check but you have no Thoth client configured. Please read https://anubis.techaro.lol/docs/admin/thoth for more information\", \"check\", \"geoip\", \"settings\", b.GeoIP)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tcl = append(cl, tc.GeoIPCheckerFor(b.GeoIP.Countries))\n\t\t}\n\n\t\tif b.Challenge == nil {\n\t\t\tparsedBot.Challenge = &config.ChallengeRules{\n\t\t\t\tDifficulty: defaultDifficulty,\n\t\t\t\tReportAs: defaultDifficulty,\n\t\t\t\tAlgorithm: \"fast\",\n\t\t\t}\n\t\t} else {\n\t\t\tparsedBot.Challenge = b.Challenge\n\t\t\tif parsedBot.Challenge.Algorithm == \"\" {\n\t\t\t\tparsedBot.Challenge.Algorithm = config.DefaultAlgorithm\n\t\t\t}\n\t\t}\n\n\t\tif b.Weight != nil {\n\t\t\tparsedBot.Weight = b.Weight\n\t\t}\n\n\t\tresult.Impressum = c.Impressum\n\n\t\tparsedBot.Rules = cl\n\n\t\tresult.Bots = append(result.Bots, parsedBot)\n\t}\n\n\tfor _, t := range c.Thresholds {\n\t\tif t.Name == \"legacy-anubis-behaviour\" && t.Expression.String() == \"true\" {\n\t\t\tif !warnedAboutThresholds.Load() {\n\t\t\t\tslog.Warn(\"configuration file does not contain thresholds, see docs for details on how to upgrade\", \"fname\", fname, \"docs_url\", \"https://anubis.techaro.lol/docs/admin/configuration/thresholds/\")\n\t\t\t\twarnedAboutThresholds.Store(true)\n\t\t\t}\n\n\t\t\tt.Challenge.Difficulty = defaultDifficulty\n\t\t\tt.Challenge.ReportAs = defaultDifficulty\n\t\t}\n\n\t\tthreshold, err := ParsedThresholdFromConfig(t)\n\t\tif err != nil {\n\t\t\tvalidationErrs = append(validationErrs, fmt.Errorf(\"can't compile threshold config for %s: %w\", t.Name, err))\n\t\t\tcontinue\n\t\t}\n\n\t\tresult.Thresholds = append(result.Thresholds, threshold)\n\t}\n\n\tstFac, ok := store.Get(c.Store.Backend)\n\tswitch ok {\n\tcase true:\n\t\tstore, err := stFac.Build(ctx, c.Store.Parameters)\n\t\tif err != nil {\n\t\t\tvalidationErrs = append(validationErrs, err)\n\t\t} else {\n\t\t\tresult.Store = store\n\t\t}\n\tcase false:\n\t\tvalidationErrs = append(validationErrs, config.ErrUnknownStoreBackend)\n\t}\n\n\tif len(validationErrs) > 0 {\n\t\treturn nil, fmt.Errorf(\"errors validating policy config JSON %s: %w\", fname, errors.Join(validationErrs...))\n\t}\n\n\tresult.DNSBL = c.DNSBL\n\n\treturn result, nil\n}\n"], ["/anubis/lib/http.go", "package lib\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"net/http\"\n\t\"regexp\"\n\t\"slices\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/TecharoHQ/anubis/internal\"\n\t\"github.com/TecharoHQ/anubis/lib/challenge\"\n\t\"github.com/TecharoHQ/anubis/lib/localization\"\n\t\"github.com/TecharoHQ/anubis/lib/policy\"\n\t\"github.com/TecharoHQ/anubis/web\"\n\t\"github.com/a-h/templ\"\n\t\"github.com/golang-jwt/jwt/v5\"\n\t\"golang.org/x/net/publicsuffix\"\n)\n\nvar domainMatchRegexp = regexp.MustCompile(`^((xn--)?[a-z0-9]+(-[a-z0-9]+)*\\.)+[a-z]{2,}$`)\n\ntype CookieOpts struct {\n\tValue string\n\tHost string\n\tPath string\n\tName string\n\tExpiry time.Duration\n}\n\nfunc (s *Server) SetCookie(w http.ResponseWriter, cookieOpts CookieOpts) {\n\tvar domain = s.opts.CookieDomain\n\tvar name = anubis.CookieName\n\tvar path = \"/\"\n\tif cookieOpts.Name != \"\" {\n\t\tname = cookieOpts.Name\n\t}\n\tif cookieOpts.Path != \"\" {\n\t\tpath = cookieOpts.Path\n\t}\n\tif s.opts.CookieDynamicDomain && domainMatchRegexp.MatchString(cookieOpts.Host) {\n\t\tif etld, err := publicsuffix.EffectiveTLDPlusOne(cookieOpts.Host); err == nil {\n\t\t\tdomain = etld\n\t\t}\n\t}\n\n\tif cookieOpts.Expiry == 0 {\n\t\tcookieOpts.Expiry = s.opts.CookieExpiration\n\t}\n\n\thttp.SetCookie(w, &http.Cookie{\n\t\tName: name,\n\t\tValue: cookieOpts.Value,\n\t\tExpires: time.Now().Add(cookieOpts.Expiry),\n\t\tSameSite: http.SameSiteNoneMode,\n\t\tDomain: domain,\n\t\tSecure: s.opts.CookieSecure,\n\t\tPartitioned: s.opts.CookiePartitioned,\n\t\tPath: path,\n\t})\n}\n\nfunc (s *Server) ClearCookie(w http.ResponseWriter, cookieOpts CookieOpts) {\n\tvar domain = s.opts.CookieDomain\n\tvar name = anubis.CookieName\n\tvar path = \"/\"\n\tif cookieOpts.Name != \"\" {\n\t\tname = cookieOpts.Name\n\t}\n\tif cookieOpts.Path != \"\" {\n\t\tpath = cookieOpts.Path\n\t}\n\tif s.opts.CookieDynamicDomain && domainMatchRegexp.MatchString(cookieOpts.Host) {\n\t\tif etld, err := publicsuffix.EffectiveTLDPlusOne(cookieOpts.Host); err == nil {\n\t\t\tdomain = etld\n\t\t}\n\t}\n\n\thttp.SetCookie(w, &http.Cookie{\n\t\tName: name,\n\t\tValue: \"\",\n\t\tMaxAge: -1,\n\t\tExpires: time.Now().Add(-1 * time.Minute),\n\t\tSameSite: http.SameSiteNoneMode,\n\t\tPartitioned: s.opts.CookiePartitioned,\n\t\tDomain: domain,\n\t\tSecure: s.opts.CookieSecure,\n\t\tPath: path,\n\t})\n}\n\n// https://github.com/oauth2-proxy/oauth2-proxy/blob/master/pkg/upstream/http.go#L124\ntype UnixRoundTripper struct {\n\tTransport *http.Transport\n}\n\n// set bare minimum stuff\nfunc (t UnixRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {\n\treq = req.Clone(req.Context())\n\tif req.Host == \"\" {\n\t\treq.Host = \"localhost\"\n\t}\n\treq.URL.Host = req.Host // proxy error: no Host in request URL\n\treq.URL.Scheme = \"http\" // make http.Transport happy and avoid an infinite recursion\n\treturn t.Transport.RoundTrip(req)\n}\n\nfunc randomChance(n int) bool {\n\treturn rand.Intn(n) == 0\n}\n\nfunc (s *Server) RenderIndex(w http.ResponseWriter, r *http.Request, rule *policy.Bot, returnHTTPStatusOnly bool) {\n\tlocalizer := localization.GetLocalizer(r)\n\n\tif returnHTTPStatusOnly {\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\tw.Write([]byte(localizer.T(\"authorization_required\")))\n\t\treturn\n\t}\n\n\tlg := internal.GetRequestLogger(r)\n\n\tif !strings.Contains(r.Header.Get(\"Accept-Encoding\"), \"gzip\") && randomChance(64) {\n\t\tlg.Error(\"client was given a challenge but does not in fact support gzip compression\")\n\t\ts.respondWithError(w, r, localizer.T(\"client_error_browser\"))\n\t}\n\n\tchallengesIssued.WithLabelValues(\"embedded\").Add(1)\n\tchall, err := s.challengeFor(r)\n\tif err != nil {\n\t\tlg.Error(\"can't get challenge\", \"err\", \"err\")\n\t\ts.ClearCookie(w, CookieOpts{Name: anubis.TestCookieName, Host: r.Host})\n\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s: %s\", localizer.T(\"internal_server_error\"), rule.Challenge.Algorithm))\n\t\treturn\n\t}\n\n\tvar ogTags map[string]string = nil\n\tif s.opts.OpenGraph.Enabled {\n\t\tvar err error\n\t\togTags, err = s.OGTags.GetOGTags(r.Context(), r.URL, r.Host)\n\t\tif err != nil {\n\t\t\tlg.Error(\"failed to get OG tags\", \"err\", err)\n\t\t}\n\t}\n\n\ts.SetCookie(w, CookieOpts{\n\t\tValue: chall.ID,\n\t\tHost: r.Host,\n\t\tPath: \"/\",\n\t\tName: anubis.TestCookieName,\n\t\tExpiry: 30 * time.Minute,\n\t})\n\n\timpl, ok := challenge.Get(rule.Challenge.Algorithm)\n\tif !ok {\n\t\tlg.Error(\"check failed\", \"err\", \"can't get algorithm\", \"algorithm\", rule.Challenge.Algorithm)\n\t\ts.ClearCookie(w, CookieOpts{Name: anubis.TestCookieName, Host: r.Host})\n\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s: %s\", localizer.T(\"internal_server_error\"), rule.Challenge.Algorithm))\n\t\treturn\n\t}\n\n\tin := &challenge.IssueInput{\n\t\tImpressum: s.policy.Impressum,\n\t\tRule: rule,\n\t\tChallenge: chall,\n\t\tOGTags: ogTags,\n\t\tStore: s.store,\n\t}\n\n\tcomponent, err := impl.Issue(r, lg, in)\n\tif err != nil {\n\t\tlg.Error(\"[unexpected] render failed, please open an issue\", \"err\", err) // This is likely a bug in the template. Should never be triggered as CI tests for this.\n\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s \\\"RenderIndex\\\"\", localizer.T(\"internal_server_error\")))\n\t\treturn\n\t}\n\n\thandler := internal.GzipMiddleware(1, internal.NoStoreCache(templ.Handler(\n\t\tcomponent,\n\t\ttempl.WithStatus(s.opts.Policy.StatusCodes.Challenge),\n\t)))\n\thandler.ServeHTTP(w, r)\n}\n\nfunc (s *Server) RenderBench(w http.ResponseWriter, r *http.Request) {\n\tlocalizer := localization.GetLocalizer(r)\n\n\ttempl.Handler(\n\t\tweb.Base(localizer.T(\"benchmarking_anubis\"), web.Bench(localizer), s.policy.Impressum, localizer),\n\t).ServeHTTP(w, r)\n}\n\nfunc (s *Server) respondWithError(w http.ResponseWriter, r *http.Request, message string) {\n\ts.respondWithStatus(w, r, message, http.StatusInternalServerError)\n}\n\nfunc (s *Server) respondWithStatus(w http.ResponseWriter, r *http.Request, msg string, status int) {\n\tlocalizer := localization.GetLocalizer(r)\n\n\ttempl.Handler(web.Base(localizer.T(\"oh_noes\"), web.ErrorPage(msg, s.opts.WebmasterEmail, localizer), s.policy.Impressum, localizer), templ.WithStatus(status)).ServeHTTP(w, r)\n}\n\nfunc (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\ts.mux.ServeHTTP(w, r)\n}\n\nfunc (s *Server) stripBasePrefixFromRequest(r *http.Request) *http.Request {\n\tif !s.opts.StripBasePrefix || s.opts.BasePrefix == \"\" {\n\t\treturn r\n\t}\n\n\tbasePrefix := strings.TrimSuffix(s.opts.BasePrefix, \"/\")\n\tpath := r.URL.Path\n\n\tif !strings.HasPrefix(path, basePrefix) {\n\t\treturn r\n\t}\n\n\ttrimmedPath := strings.TrimPrefix(path, basePrefix)\n\tif trimmedPath == \"\" {\n\t\ttrimmedPath = \"/\"\n\t}\n\n\t// Clone the request and URL\n\treqCopy := r.Clone(r.Context())\n\turlCopy := *r.URL\n\turlCopy.Path = trimmedPath\n\treqCopy.URL = &urlCopy\n\n\treturn reqCopy\n}\n\nfunc (s *Server) ServeHTTPNext(w http.ResponseWriter, r *http.Request) {\n\tif s.next == nil {\n\t\tlocalizer := localization.GetLocalizer(r)\n\n\t\tredir := r.FormValue(\"redir\")\n\t\turlParsed, err := r.URL.Parse(redir)\n\t\tif err != nil {\n\t\t\ts.respondWithStatus(w, r, localizer.T(\"redirect_not_parseable\"), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tif (len(urlParsed.Host) > 0 && len(s.opts.RedirectDomains) != 0 && !slices.Contains(s.opts.RedirectDomains, urlParsed.Host)) || urlParsed.Host != r.URL.Host {\n\t\t\ts.respondWithStatus(w, r, localizer.T(\"redirect_domain_not_allowed\"), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tif redir != \"\" {\n\t\t\thttp.Redirect(w, r, redir, http.StatusFound)\n\t\t\treturn\n\t\t}\n\n\t\ttempl.Handler(\n\t\t\tweb.Base(localizer.T(\"you_are_not_a_bot\"), web.StaticHappy(localizer), s.policy.Impressum, localizer),\n\t\t).ServeHTTP(w, r)\n\t} else {\n\t\trequestsProxied.WithLabelValues(r.Host).Inc()\n\t\tr = s.stripBasePrefixFromRequest(r)\n\t\ts.next.ServeHTTP(w, r)\n\t}\n}\n\nfunc (s *Server) signJWT(claims jwt.MapClaims) (string, error) {\n\tclaims[\"iat\"] = time.Now().Unix()\n\tclaims[\"nbf\"] = time.Now().Add(-1 * time.Minute).Unix()\n\tclaims[\"exp\"] = time.Now().Add(s.opts.CookieExpiration).Unix()\n\n\tif len(s.hs512Secret) == 0 {\n\t\treturn jwt.NewWithClaims(jwt.SigningMethodEdDSA, claims).SignedString(s.ed25519Priv)\n\t} else {\n\t\treturn jwt.NewWithClaims(jwt.SigningMethodHS512, claims).SignedString(s.hs512Secret)\n\t}\n}\n"], ["/anubis/cmd/robots2policy/main.go", "package main\n\nimport (\n\t\"bufio\"\n\t\"encoding/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\n\t\"sigs.k8s.io/yaml\"\n)\n\nvar (\n\tinputFile = flag.String(\"input\", \"\", \"path to robots.txt file (use - for stdin)\")\n\toutputFile = flag.String(\"output\", \"\", \"output file path (use - for stdout, defaults to stdout)\")\n\toutputFormat = flag.String(\"format\", \"yaml\", \"output format: yaml or json\")\n\tbaseAction = flag.String(\"action\", \"CHALLENGE\", \"default action for disallowed paths: ALLOW, DENY, CHALLENGE, WEIGH\")\n\tcrawlDelay = flag.Int(\"crawl-delay-weight\", 0, \"if > 0, add weight adjustment for crawl-delay (difficulty adjustment)\")\n\tpolicyName = flag.String(\"name\", \"robots-txt-policy\", \"name for the generated policy\")\n\tuserAgentDeny = flag.String(\"deny-user-agents\", \"DENY\", \"action for specifically blocked user agents: DENY, CHALLENGE\")\n\thelpFlag = flag.Bool(\"help\", false, \"show help\")\n)\n\ntype RobotsRule struct {\n\tUserAgent string\n\tDisallows []string\n\tAllows []string\n\tCrawlDelay int\n\tIsBlacklist bool // true if this is a specifically denied user agent\n}\n\ntype AnubisRule struct {\n\tExpression *config.ExpressionOrList `yaml:\"expression,omitempty\" json:\"expression,omitempty\"`\n\tChallenge *config.ChallengeRules `yaml:\"challenge,omitempty\" json:\"challenge,omitempty\"`\n\tWeight *config.Weight `yaml:\"weight,omitempty\" json:\"weight,omitempty\"`\n\tName string `yaml:\"name\" json:\"name\"`\n\tAction string `yaml:\"action\" json:\"action\"`\n}\n\nfunc init() {\n\tflag.Usage = func() {\n\t\tfmt.Fprintf(os.Stderr, \"Usage of %s:\\n\", os.Args[0])\n\t\tfmt.Fprintf(os.Stderr, \"%s [options] -input \\n\\n\", os.Args[0])\n\t\tflag.PrintDefaults()\n\t\tfmt.Fprintln(os.Stderr, \"\\nExamples:\")\n\t\tfmt.Fprintln(os.Stderr, \" # Convert local robots.txt file\")\n\t\tfmt.Fprintln(os.Stderr, \" robots2policy -input robots.txt -output policy.yaml\")\n\t\tfmt.Fprintln(os.Stderr, \"\")\n\t\tfmt.Fprintln(os.Stderr, \" # Convert from URL\")\n\t\tfmt.Fprintln(os.Stderr, \" robots2policy -input https://example.com/robots.txt -format json\")\n\t\tfmt.Fprintln(os.Stderr, \"\")\n\t\tfmt.Fprintln(os.Stderr, \" # Read from stdin, write to stdout\")\n\t\tfmt.Fprintln(os.Stderr, \" curl https://example.com/robots.txt | robots2policy -input -\")\n\t\tos.Exit(2)\n\t}\n}\n\nfunc main() {\n\tflag.Parse()\n\n\tif len(flag.Args()) > 0 || *helpFlag || *inputFile == \"\" {\n\t\tflag.Usage()\n\t}\n\n\t// Read robots.txt\n\tvar input io.Reader\n\tif *inputFile == \"-\" {\n\t\tinput = os.Stdin\n\t} else if strings.HasPrefix(*inputFile, \"http://\") || strings.HasPrefix(*inputFile, \"https://\") {\n\t\tresp, err := http.Get(*inputFile)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to fetch robots.txt from URL: %v\", err)\n\t\t}\n\t\tdefer resp.Body.Close()\n\t\tinput = resp.Body\n\t} else {\n\t\tfile, err := os.Open(*inputFile)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to open input file: %v\", err)\n\t\t}\n\t\tdefer file.Close()\n\t\tinput = file\n\t}\n\n\t// Parse robots.txt\n\trules, err := parseRobotsTxt(input)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to parse robots.txt: %v\", err)\n\t}\n\n\t// Convert to Anubis rules\n\tanubisRules := convertToAnubisRules(rules)\n\n\t// Check if any rules were generated\n\tif len(anubisRules) == 0 {\n\t\tlog.Fatal(\"no valid rules generated from robots.txt - file may be empty or contain no disallow directives\")\n\t}\n\n\t// Generate output\n\tvar output []byte\n\tswitch strings.ToLower(*outputFormat) {\n\tcase \"yaml\":\n\t\toutput, err = yaml.Marshal(anubisRules)\n\tcase \"json\":\n\t\toutput, err = json.MarshalIndent(anubisRules, \"\", \" \")\n\tdefault:\n\t\tlog.Fatalf(\"unsupported output format: %s (use yaml or json)\", *outputFormat)\n\t}\n\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to marshal output: %v\", err)\n\t}\n\n\t// Write output\n\tif *outputFile == \"\" || *outputFile == \"-\" {\n\t\tfmt.Print(string(output))\n\t} else {\n\t\terr = os.WriteFile(*outputFile, output, 0644)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to write output file: %v\", err)\n\t\t}\n\t\tfmt.Printf(\"Generated Anubis policy written to %s\\n\", *outputFile)\n\t}\n}\n\nfunc parseRobotsTxt(input io.Reader) ([]RobotsRule, error) {\n\tscanner := bufio.NewScanner(input)\n\tvar rules []RobotsRule\n\tvar currentRule *RobotsRule\n\n\tfor scanner.Scan() {\n\t\tline := strings.TrimSpace(scanner.Text())\n\n\t\t// Skip empty lines and comments\n\t\tif line == \"\" || strings.HasPrefix(line, \"#\") {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Split on first colon\n\t\tparts := strings.SplitN(line, \":\", 2)\n\t\tif len(parts) != 2 {\n\t\t\tcontinue\n\t\t}\n\n\t\tdirective := strings.TrimSpace(strings.ToLower(parts[0]))\n\t\tvalue := strings.TrimSpace(parts[1])\n\n\t\tswitch directive {\n\t\tcase \"user-agent\":\n\t\t\t// Start a new rule section\n\t\t\tif currentRule != nil {\n\t\t\t\trules = append(rules, *currentRule)\n\t\t\t}\n\t\t\tcurrentRule = &RobotsRule{\n\t\t\t\tUserAgent: value,\n\t\t\t\tDisallows: make([]string, 0),\n\t\t\t\tAllows: make([]string, 0),\n\t\t\t}\n\n\t\tcase \"disallow\":\n\t\t\tif currentRule != nil && value != \"\" {\n\t\t\t\tcurrentRule.Disallows = append(currentRule.Disallows, value)\n\t\t\t}\n\n\t\tcase \"allow\":\n\t\t\tif currentRule != nil && value != \"\" {\n\t\t\t\tcurrentRule.Allows = append(currentRule.Allows, value)\n\t\t\t}\n\n\t\tcase \"crawl-delay\":\n\t\t\tif currentRule != nil {\n\t\t\t\tif delay, err := parseIntSafe(value); err == nil {\n\t\t\t\t\tcurrentRule.CrawlDelay = delay\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Don't forget the last rule\n\tif currentRule != nil {\n\t\trules = append(rules, *currentRule)\n\t}\n\n\t// Mark blacklisted user agents (those with \"Disallow: /\")\n\tfor i := range rules {\n\t\tfor _, disallow := range rules[i].Disallows {\n\t\t\tif disallow == \"/\" {\n\t\t\t\trules[i].IsBlacklist = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn rules, scanner.Err()\n}\n\nfunc parseIntSafe(s string) (int, error) {\n\tvar result int\n\t_, err := fmt.Sscanf(s, \"%d\", &result)\n\treturn result, err\n}\n\nfunc convertToAnubisRules(robotsRules []RobotsRule) []AnubisRule {\n\tvar anubisRules []AnubisRule\n\truleCounter := 0\n\n\tfor _, robotsRule := range robotsRules {\n\t\tuserAgent := robotsRule.UserAgent\n\n\t\t// Handle crawl delay as weight adjustment (do this first before any continues)\n\t\tif robotsRule.CrawlDelay > 0 && *crawlDelay > 0 {\n\t\t\truleCounter++\n\t\t\trule := AnubisRule{\n\t\t\t\tName: fmt.Sprintf(\"%s-crawl-delay-%d\", *policyName, ruleCounter),\n\t\t\t\tAction: \"WEIGH\",\n\t\t\t\tWeight: &config.Weight{Adjust: *crawlDelay},\n\t\t\t}\n\n\t\t\tif userAgent == \"*\" {\n\t\t\t\trule.Expression = &config.ExpressionOrList{\n\t\t\t\t\tAll: []string{\"true\"}, // Always applies\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\trule.Expression = &config.ExpressionOrList{\n\t\t\t\t\tAll: []string{fmt.Sprintf(\"userAgent.contains(%q)\", userAgent)},\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tanubisRules = append(anubisRules, rule)\n\t\t}\n\n\t\t// Handle blacklisted user agents (complete deny/challenge)\n\t\tif robotsRule.IsBlacklist {\n\t\t\truleCounter++\n\t\t\trule := AnubisRule{\n\t\t\t\tName: fmt.Sprintf(\"%s-blacklist-%d\", *policyName, ruleCounter),\n\t\t\t\tAction: *userAgentDeny,\n\t\t\t}\n\n\t\t\tif userAgent == \"*\" {\n\t\t\t\t// This would block everything - convert to a weight adjustment instead\n\t\t\t\trule.Name = fmt.Sprintf(\"%s-global-restriction-%d\", *policyName, ruleCounter)\n\t\t\t\trule.Action = \"WEIGH\"\n\t\t\t\trule.Weight = &config.Weight{Adjust: 20} // Increase difficulty significantly\n\t\t\t\trule.Expression = &config.ExpressionOrList{\n\t\t\t\t\tAll: []string{\"true\"}, // Always applies\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\trule.Expression = &config.ExpressionOrList{\n\t\t\t\t\tAll: []string{fmt.Sprintf(\"userAgent.contains(%q)\", userAgent)},\n\t\t\t\t}\n\t\t\t}\n\t\t\tanubisRules = append(anubisRules, rule)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Handle specific disallow rules\n\t\tfor _, disallow := range robotsRule.Disallows {\n\t\t\tif disallow == \"/\" {\n\t\t\t\tcontinue // Already handled as blacklist above\n\t\t\t}\n\n\t\t\truleCounter++\n\t\t\trule := AnubisRule{\n\t\t\t\tName: fmt.Sprintf(\"%s-disallow-%d\", *policyName, ruleCounter),\n\t\t\t\tAction: *baseAction,\n\t\t\t}\n\n\t\t\t// Build CEL expression\n\t\t\tvar conditions []string\n\n\t\t\t// Add user agent condition if not wildcard\n\t\t\tif userAgent != \"*\" {\n\t\t\t\tconditions = append(conditions, fmt.Sprintf(\"userAgent.contains(%q)\", userAgent))\n\t\t\t}\n\n\t\t\t// Add path condition\n\t\t\tpathCondition := buildPathCondition(disallow)\n\t\t\tconditions = append(conditions, pathCondition)\n\n\t\t\trule.Expression = &config.ExpressionOrList{\n\t\t\t\tAll: conditions,\n\t\t\t}\n\n\t\t\tanubisRules = append(anubisRules, rule)\n\t\t}\n\n\t}\n\n\treturn anubisRules\n}\n\nfunc buildPathCondition(robotsPath string) string {\n\t// Handle wildcards in robots.txt paths\n\tif strings.Contains(robotsPath, \"*\") || strings.Contains(robotsPath, \"?\") {\n\t\t// Convert robots.txt wildcards to regex\n\t\tregex := regexp.QuoteMeta(robotsPath)\n\t\tregex = strings.ReplaceAll(regex, `\\*`, `.*`) // * becomes .*\n\t\tregex = strings.ReplaceAll(regex, `\\?`, `.`) // ? becomes .\n\t\tregex = \"^\" + regex\n\t\treturn fmt.Sprintf(\"path.matches(%q)\", regex)\n\t}\n\n\t// Simple prefix match for most cases\n\treturn fmt.Sprintf(\"path.startsWith(%q)\", robotsPath)\n}\n"], ["/anubis/internal/ogtags/ogtags.go", "package ogtags\n\nimport (\n\t\"context\"\n\t\"log/slog\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n)\n\nconst (\n\tmaxContentLength = 8 << 20 // 8 MiB is enough for anyone\n\thttpTimeout = 5 * time.Second /*todo: make this configurable?*/\n\n\tschemeSeparatorLength = 3 // Length of \"://\"\n\tquerySeparatorLength = 1 // Length of \"?\" for query strings\n)\n\ntype OGTagCache struct {\n\tcache store.JSON[map[string]string]\n\ttargetURL *url.URL\n\tclient *http.Client\n\n\t// Pre-built strings for optimization\n\tunixPrefix string // \"http://unix\"\n\tapprovedTags []string\n\tapprovedPrefixes []string\n\togTimeToLive time.Duration\n\togCacheConsiderHost bool\n\togPassthrough bool\n\togOverride map[string]string\n}\n\nfunc NewOGTagCache(target string, conf config.OpenGraph, backend store.Interface) *OGTagCache {\n\t// Predefined approved tags and prefixes\n\tdefaultApprovedTags := []string{\"description\", \"keywords\", \"author\"}\n\tdefaultApprovedPrefixes := []string{\"og:\", \"twitter:\", \"fediverse:\"}\n\n\tvar parsedTargetURL *url.URL\n\tvar err error\n\n\tif target == \"\" {\n\t\t// Default to localhost if target is empty\n\t\tparsedTargetURL, _ = url.Parse(\"http://localhost\")\n\t} else {\n\t\tparsedTargetURL, err = url.Parse(target)\n\t\tif err != nil {\n\t\t\tslog.Debug(\"og: failed to parse target URL, treating as non-unix\", \"target\", target, \"error\", err)\n\t\t\t// If parsing fails, treat it as a non-unix target for backward compatibility or default behavior\n\t\t\t// For now, assume it's not a scheme issue but maybe an invalid char, etc.\n\t\t\t// A simple string target might be intended if it's not a full URL.\n\t\t\tparsedTargetURL = &url.URL{Scheme: \"http\", Host: target} // Assume http if scheme missing and host-like\n\t\t\tif !strings.Contains(target, \"://\") && !strings.HasPrefix(target, \"unix:\") {\n\t\t\t\t// If it looks like just a host/host:port (and not unix), prepend http:// (todo: is this bad...? Trace path to see if i can yell at user to do it right)\n\t\t\t\tparsedTargetURL, _ = url.Parse(\"http://\" + target) // fetch cares about scheme but anubis doesn't\n\t\t\t}\n\t\t}\n\t}\n\n\tclient := &http.Client{\n\t\tTimeout: httpTimeout,\n\t}\n\n\t// Configure custom transport for Unix sockets\n\tif parsedTargetURL.Scheme == \"unix\" {\n\t\tsocketPath := parsedTargetURL.Path // For unix scheme, path is the socket path\n\t\tclient.Transport = &http.Transport{\n\t\t\tDialContext: func(_ context.Context, _, _ string) (net.Conn, error) {\n\t\t\t\treturn net.Dial(\"unix\", socketPath)\n\t\t\t},\n\t\t}\n\t}\n\n\treturn &OGTagCache{\n\t\tcache: store.JSON[map[string]string]{\n\t\t\tUnderlying: backend,\n\t\t\tPrefix: \"ogtags:\",\n\t\t},\n\t\ttargetURL: parsedTargetURL,\n\t\togPassthrough: conf.Enabled,\n\t\togTimeToLive: conf.TimeToLive,\n\t\togCacheConsiderHost: conf.ConsiderHost,\n\t\togOverride: conf.Override,\n\t\tapprovedTags: defaultApprovedTags,\n\t\tapprovedPrefixes: defaultApprovedPrefixes,\n\t\tclient: client,\n\t\tunixPrefix: \"http://unix\",\n\t}\n}\n\n// getTarget constructs the target URL string for fetching OG tags.\n// Optimized to minimize allocations by building strings directly.\nfunc (c *OGTagCache) getTarget(u *url.URL) string {\n\tvar escapedPath = u.EscapedPath() // will cause an allocation if path contains special characters\n\tif c.targetURL.Scheme == \"unix\" {\n\t\t// Build URL string directly without creating intermediate URL object\n\t\tvar sb strings.Builder\n\t\tsb.Grow(len(c.unixPrefix) + len(escapedPath) + len(u.RawQuery) + querySeparatorLength) // Pre-allocate\n\t\tsb.WriteString(c.unixPrefix)\n\t\tsb.WriteString(escapedPath)\n\t\tif u.RawQuery != \"\" {\n\t\t\tsb.WriteByte('?')\n\t\t\tsb.WriteString(u.RawQuery)\n\t\t}\n\t\treturn sb.String()\n\t}\n\n\t// For regular http/https targets, build URL string directly\n\tvar sb strings.Builder\n\t// Pre-calculate size: scheme + \"://\" + host + path + \"?\" + query\n\testimatedSize := len(c.targetURL.Scheme) + schemeSeparatorLength + len(c.targetURL.Host) + len(escapedPath) + len(u.RawQuery) + querySeparatorLength\n\tsb.Grow(estimatedSize)\n\n\tsb.WriteString(c.targetURL.Scheme)\n\tsb.WriteString(\"://\")\n\tsb.WriteString(c.targetURL.Host)\n\tsb.WriteString(escapedPath)\n\tif u.RawQuery != \"\" {\n\t\tsb.WriteByte('?')\n\t\tsb.WriteString(u.RawQuery)\n\t}\n\n\treturn sb.String()\n}\n"], ["/anubis/lib/policy/config/expressionorlist.go", "package config\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"slices\"\n\t\"strings\"\n)\n\nvar (\n\tErrExpressionOrListMustBeStringOrObject = errors.New(\"config: this must be a string or an object\")\n\tErrExpressionEmpty = errors.New(\"config: this expression is empty\")\n\tErrExpressionCantHaveBoth = errors.New(\"config: expression block can't contain multiple expression types\")\n)\n\ntype ExpressionOrList struct {\n\tExpression string `json:\"-\" yaml:\"-\"`\n\tAll []string `json:\"all,omitempty\" yaml:\"all,omitempty\"`\n\tAny []string `json:\"any,omitempty\" yaml:\"any,omitempty\"`\n}\n\nfunc (eol ExpressionOrList) String() string {\n\tswitch {\n\tcase len(eol.Expression) != 0:\n\t\treturn eol.Expression\n\tcase len(eol.All) != 0:\n\t\tvar sb strings.Builder\n\t\tfor i, pred := range eol.All {\n\t\t\tif i != 0 {\n\t\t\t\tfmt.Fprintf(&sb, \" && \")\n\t\t\t}\n\t\t\tfmt.Fprintf(&sb, \"( %s )\", pred)\n\t\t}\n\t\treturn sb.String()\n\tcase len(eol.Any) != 0:\n\t\tvar sb strings.Builder\n\t\tfor i, pred := range eol.Any {\n\t\t\tif i != 0 {\n\t\t\t\tfmt.Fprintf(&sb, \" || \")\n\t\t\t}\n\t\t\tfmt.Fprintf(&sb, \"( %s )\", pred)\n\t\t}\n\t\treturn sb.String()\n\t}\n\tpanic(\"this should not happen\")\n}\n\nfunc (eol ExpressionOrList) Equal(rhs *ExpressionOrList) bool {\n\tif eol.Expression != rhs.Expression {\n\t\treturn false\n\t}\n\n\tif !slices.Equal(eol.All, rhs.All) {\n\t\treturn false\n\t}\n\n\tif !slices.Equal(eol.Any, rhs.Any) {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\nfunc (eol *ExpressionOrList) MarshalYAML() (any, error) {\n\tswitch {\n\tcase len(eol.All) == 1 && len(eol.Any) == 0:\n\t\teol.Expression = eol.All[0]\n\t\teol.All = nil\n\tcase len(eol.Any) == 1 && len(eol.All) == 0:\n\t\teol.Expression = eol.Any[0]\n\t\teol.Any = nil\n\t}\n\n\tif eol.Expression != \"\" {\n\t\treturn eol.Expression, nil\n\t}\n\n\ttype RawExpressionOrList ExpressionOrList\n\treturn RawExpressionOrList(*eol), nil\n}\n\nfunc (eol *ExpressionOrList) MarshalJSON() ([]byte, error) {\n\tswitch {\n\tcase len(eol.All) == 1 && len(eol.Any) == 0:\n\t\teol.Expression = eol.All[0]\n\t\teol.All = nil\n\tcase len(eol.Any) == 1 && len(eol.All) == 0:\n\t\teol.Expression = eol.Any[0]\n\t\teol.Any = nil\n\t}\n\n\tif eol.Expression != \"\" {\n\t\treturn json.Marshal(string(eol.Expression))\n\t}\n\n\ttype RawExpressionOrList ExpressionOrList\n\tval := RawExpressionOrList(*eol)\n\treturn json.Marshal(val)\n}\n\nfunc (eol *ExpressionOrList) UnmarshalJSON(data []byte) error {\n\tswitch string(data[0]) {\n\tcase `\"`: // string\n\t\treturn json.Unmarshal(data, &eol.Expression)\n\tcase \"{\": // object\n\t\ttype RawExpressionOrList ExpressionOrList\n\t\tvar val RawExpressionOrList\n\t\tif err := json.Unmarshal(data, &val); err != nil {\n\t\t\treturn err\n\t\t}\n\t\teol.All = val.All\n\t\teol.Any = val.Any\n\n\t\treturn nil\n\t}\n\n\treturn ErrExpressionOrListMustBeStringOrObject\n}\n\nfunc (eol *ExpressionOrList) Valid() error {\n\tif eol.Expression == \"\" && len(eol.All) == 0 && len(eol.Any) == 0 {\n\t\treturn ErrExpressionEmpty\n\t}\n\tif len(eol.All) != 0 && len(eol.Any) != 0 {\n\t\treturn ErrExpressionCantHaveBoth\n\t}\n\n\treturn nil\n}\n"], ["/anubis/lib/thoth/thoth.go", "package thoth\n\nimport (\n\t\"context\"\n\t\"crypto/tls\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\tiptoasnv1 \"github.com/TecharoHQ/thoth-proto/gen/techaro/thoth/iptoasn/v1\"\n\tgrpcprom \"github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus\"\n\t\"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/timeout\"\n\t\"github.com/prometheus/client_golang/prometheus\"\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/credentials\"\n\t\"google.golang.org/grpc/credentials/insecure\"\n\thealthv1 \"google.golang.org/grpc/health/grpc_health_v1\"\n)\n\ntype Client struct {\n\tconn *grpc.ClientConn\n\thealth healthv1.HealthClient\n\tIPToASN iptoasnv1.IpToASNServiceClient\n}\n\nfunc New(ctx context.Context, thothURL, apiToken string, plaintext bool) (*Client, error) {\n\tclMetrics := grpcprom.NewClientMetrics(\n\t\tgrpcprom.WithClientHandlingTimeHistogram(\n\t\t\tgrpcprom.WithHistogramBuckets([]float64{0.001, 0.01, 0.1, 0.3, 0.6, 1, 3, 6, 9, 20, 30, 60, 90, 120}),\n\t\t),\n\t)\n\tprometheus.DefaultRegisterer.Register(clMetrics)\n\n\tdo := []grpc.DialOption{\n\t\tgrpc.WithChainUnaryInterceptor(\n\t\t\ttimeout.UnaryClientInterceptor(500*time.Millisecond),\n\t\t\tclMetrics.UnaryClientInterceptor(),\n\t\t\tauthUnaryClientInterceptor(apiToken),\n\t\t),\n\t\tgrpc.WithChainStreamInterceptor(\n\t\t\tclMetrics.StreamClientInterceptor(),\n\t\t\tauthStreamClientInterceptor(apiToken),\n\t\t),\n\t\tgrpc.WithUserAgent(fmt.Sprint(\"Techaro/anubis:\", anubis.Version)),\n\t}\n\n\tif plaintext {\n\t\tdo = append(do, grpc.WithTransportCredentials(insecure.NewCredentials()))\n\t} else {\n\t\tdo = append(do, grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{})))\n\t}\n\n\tconn, err := grpc.NewClient(\n\t\tthothURL,\n\t\tdo...,\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't dial thoth at %s: %w\", thothURL, err)\n\t}\n\n\thc := healthv1.NewHealthClient(conn)\n\n\treturn &Client{\n\t\tconn: conn,\n\t\thealth: hc,\n\t\tIPToASN: NewIpToASNWithCache(iptoasnv1.NewIpToASNServiceClient(conn)),\n\t}, nil\n}\n\nfunc (c *Client) Close() error {\n\tif c.conn != nil {\n\t\treturn c.conn.Close()\n\t}\n\treturn nil\n}\n\nfunc (c *Client) WithIPToASNService(impl iptoasnv1.IpToASNServiceClient) {\n\tc.IPToASN = impl\n}\n"], ["/anubis/web/index_templ.go", "// Code generated by templ - DO NOT EDIT.\n\n// templ: version: v0.3.906\npackage web\n\n//lint:file-ignore SA4006 This context is only used if a nested component is present.\n\nimport \"github.com/a-h/templ\"\nimport templruntime \"github.com/a-h/templ/runtime\"\n\nimport (\n\t\"fmt\"\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/TecharoHQ/anubis/lib/localization\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/xess\"\n)\n\nfunc base(title string, body templ.Component, impressum *config.Impressum, challenge any, ogTags map[string]string, localizer *localization.SimpleLocalizer) templ.Component {\n\treturn templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {\n\t\ttempl_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context\n\t\tif templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {\n\t\t\treturn templ_7745c5c3_CtxErr\n\t\t}\n\t\ttempl_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)\n\t\tif !templ_7745c5c3_IsBuffer {\n\t\t\tdefer func() {\n\t\t\t\ttempl_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)\n\t\t\t\tif templ_7745c5c3_Err == nil {\n\t\t\t\t\ttempl_7745c5c3_Err = templ_7745c5c3_BufErr\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\tctx = templ.InitializeContext(ctx)\n\t\ttempl_7745c5c3_Var1 := templ.GetChildren(ctx)\n\t\tif templ_7745c5c3_Var1 == nil {\n\t\t\ttempl_7745c5c3_Var1 = templ.NopComponent\n\t\t}\n\t\tctx = templ.ClearChildren(ctx)\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, \"\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var3 string\n\t\ttempl_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(title)\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 15, Col: 17}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 3, \"\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tfor key, value := range ogTags {\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, \"\")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, \"\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templ.JSONScript(\"anubis_version\", anubis.Version).Render(ctx, templ_7745c5c3_Buffer)\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tif challenge != nil {\n\t\t\ttempl_7745c5c3_Err = templ.JSONScript(\"anubis_challenge\", challenge).Render(ctx, templ_7745c5c3_Buffer)\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t}\n\t\ttempl_7745c5c3_Err = templ.JSONScript(\"anubis_base_prefix\", anubis.BasePrefix).Render(ctx, templ_7745c5c3_Buffer)\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var7 string\n\t\ttempl_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(title)\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 68, Col: 47}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 10, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = body.Render(ctx, templ_7745c5c3_Buffer)\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var8 string\n\t\ttempl_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"protected_by\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 73, Col: 36}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, \" Anubis \")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var9 string\n\t\ttempl_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"protected_from\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 73, Col: 127}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, \" Techaro. \")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var10 string\n\t\ttempl_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"made_with\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 75, Col: 40}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 14, \".

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var11 string\n\t\ttempl_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"mascot_design\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 77, Col: 39}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, \" \")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var12 string\n\t\ttempl_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"celphase\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 77, Col: 123}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, \".

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tif impressum != nil {\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, \"

\")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\ttempl_7745c5c3_Err = templ.Raw(impressum.Footer).Render(ctx, templ_7745c5c3_Buffer)\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 18, \"-- Imprint

\")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 20, \"
\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\treturn nil\n\t})\n}\n\nfunc index(localizer *localization.SimpleLocalizer) templ.Component {\n\treturn templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {\n\t\ttempl_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context\n\t\tif templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {\n\t\t\treturn templ_7745c5c3_CtxErr\n\t\t}\n\t\ttempl_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)\n\t\tif !templ_7745c5c3_IsBuffer {\n\t\t\tdefer func() {\n\t\t\t\ttempl_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)\n\t\t\t\tif templ_7745c5c3_Err == nil {\n\t\t\t\t\ttempl_7745c5c3_Err = templ_7745c5c3_BufErr\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\tctx = templ.InitializeContext(ctx)\n\t\ttempl_7745c5c3_Var14 := templ.GetChildren(ctx)\n\t\tif templ_7745c5c3_Var14 == nil {\n\t\t\ttempl_7745c5c3_Var14 = templ.NopComponent\n\t\t}\n\t\tctx = templ.ClearChildren(ctx)\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 21, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var17 string\n\t\ttempl_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"loading\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 95, Col: 41}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var17))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 24, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var19 string\n\t\ttempl_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"why_am_i_seeing\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 101, Col: 44}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var19))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 26, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var20 string\n\t\ttempl_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"ai_companies_explanation\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 103, Col: 45}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var20))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 27, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var21 string\n\t\ttempl_7745c5c3_Var21, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"anubis_compromise\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 106, Col: 38}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var21))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var22 string\n\t\ttempl_7745c5c3_Var22, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"hack_purpose\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 109, Col: 33}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var22))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var23 string\n\t\ttempl_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"jshelter_note\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 112, Col: 34}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var23))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 30, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var24 string\n\t\ttempl_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"version_info\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 114, Col: 35}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var24))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 31, \" \")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var25 string\n\t\ttempl_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinStringErrs(anubis.Version)\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 114, Col: 60}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var25))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 32, \".

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\treturn nil\n\t})\n}\n\nfunc errorPage(message, mail string, localizer *localization.SimpleLocalizer) templ.Component {\n\treturn templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {\n\t\ttempl_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context\n\t\tif templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {\n\t\t\treturn templ_7745c5c3_CtxErr\n\t\t}\n\t\ttempl_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)\n\t\tif !templ_7745c5c3_IsBuffer {\n\t\t\tdefer func() {\n\t\t\t\ttempl_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)\n\t\t\t\tif templ_7745c5c3_Err == nil {\n\t\t\t\t\ttempl_7745c5c3_Err = templ_7745c5c3_BufErr\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\tctx = templ.InitializeContext(ctx)\n\t\ttempl_7745c5c3_Var27 := templ.GetChildren(ctx)\n\t\tif templ_7745c5c3_Var27 == nil {\n\t\t\ttempl_7745c5c3_Var27 = templ.NopComponent\n\t\t}\n\t\tctx = templ.ClearChildren(ctx)\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 34, \"
\\\"Sad

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var29 string\n\t\ttempl_7745c5c3_Var29, templ_7745c5c3_Err = templ.JoinStringErrs(message)\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 128, Col: 14}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var29))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 36, \".

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tif mail != \"\" {\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 37, \"

\")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\tvar templ_7745c5c3_Var30 string\n\t\t\ttempl_7745c5c3_Var30, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"go_home\"))\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 131, Col: 40}\n\t\t\t}\n\t\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var30))\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 38, \" \")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\tvar templ_7745c5c3_Var31 string\n\t\t\ttempl_7745c5c3_Var31, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"contact_webmaster\"))\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 131, Col: 81}\n\t\t\t}\n\t\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var31))\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 39, \" \")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\tvar templ_7745c5c3_Var33 string\n\t\t\ttempl_7745c5c3_Var33, templ_7745c5c3_Err = templ.JoinStringErrs(mail)\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 133, Col: 11}\n\t\t\t}\n\t\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var33))\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 41, \"

\")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t} else {\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 42, \"

\")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\tvar templ_7745c5c3_Var34 string\n\t\t\ttempl_7745c5c3_Var34, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"go_home\"))\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 137, Col: 42}\n\t\t\t}\n\t\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var34))\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 43, \"

\")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 44, \"
\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\treturn nil\n\t})\n}\n\nfunc StaticHappy(localizer *localization.SimpleLocalizer) templ.Component {\n\treturn templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {\n\t\ttempl_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context\n\t\tif templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {\n\t\t\treturn templ_7745c5c3_CtxErr\n\t\t}\n\t\ttempl_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)\n\t\tif !templ_7745c5c3_IsBuffer {\n\t\t\tdefer func() {\n\t\t\t\ttempl_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)\n\t\t\t\tif templ_7745c5c3_Err == nil {\n\t\t\t\t\ttempl_7745c5c3_Err = templ_7745c5c3_BufErr\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\tctx = templ.InitializeContext(ctx)\n\t\ttempl_7745c5c3_Var35 := templ.GetChildren(ctx)\n\t\tif templ_7745c5c3_Var35 == nil {\n\t\t\ttempl_7745c5c3_Var35 = templ.NopComponent\n\t\t}\n\t\tctx = templ.ClearChildren(ctx)\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 45, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var37 string\n\t\ttempl_7745c5c3_Var37, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"static_check_endpoint\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 150, Col: 43}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var37))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 47, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\treturn nil\n\t})\n}\n\nfunc bench(localizer *localization.SimpleLocalizer) templ.Component {\n\treturn templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {\n\t\ttempl_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context\n\t\tif templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {\n\t\t\treturn templ_7745c5c3_CtxErr\n\t\t}\n\t\ttempl_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)\n\t\tif !templ_7745c5c3_IsBuffer {\n\t\t\tdefer func() {\n\t\t\t\ttempl_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)\n\t\t\t\tif templ_7745c5c3_Err == nil {\n\t\t\t\t\ttempl_7745c5c3_Err = templ_7745c5c3_BufErr\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\tctx = templ.InitializeContext(ctx)\n\t\ttempl_7745c5c3_Var38 := templ.GetChildren(ctx)\n\t\tif templ_7745c5c3_Var38 == nil {\n\t\t\ttempl_7745c5c3_Var38 = templ.NopComponent\n\t\t}\n\t\tctx = templ.ClearChildren(ctx)\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 48, \"
\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var39 string\n\t\ttempl_7745c5c3_Var39, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"time\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 161, Col: 51}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var39))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 49, \"\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var40 string\n\t\ttempl_7745c5c3_Var40, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"iters\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 162, Col: 50}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var40))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 50, \"
\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var41 string\n\t\ttempl_7745c5c3_Var41, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"time_a\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 165, Col: 53}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var41))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 51, \"\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var42 string\n\t\ttempl_7745c5c3_Var42, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"iters_a\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 166, Col: 52}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var42))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 52, \"\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var43 string\n\t\ttempl_7745c5c3_Var43, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"time_b\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 167, Col: 53}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var43))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 53, \"\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var44 string\n\t\ttempl_7745c5c3_Var44, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"iters_b\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 168, Col: 52}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var44))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 54, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var46 string\n\t\ttempl_7745c5c3_Var46, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"loading\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 178, Col: 66}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var46))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 56, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\treturn nil\n\t})\n}\n\nvar _ = templruntime.GeneratedTemplate\n"], ["/anubis/lib/challenge/metarefresh/metarefresh_templ.go", "// Code generated by templ - DO NOT EDIT.\n\n// templ: version: v0.3.906\npackage metarefresh\n\n//lint:file-ignore SA4006 This context is only used if a nested component is present.\n\nimport \"github.com/a-h/templ\"\nimport templruntime \"github.com/a-h/templ/runtime\"\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/TecharoHQ/anubis/lib/localization\"\n)\n\nfunc page(redir string, difficulty int, loc *localization.SimpleLocalizer) templ.Component {\n\treturn templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {\n\t\ttempl_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context\n\t\tif templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {\n\t\t\treturn templ_7745c5c3_CtxErr\n\t\t}\n\t\ttempl_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)\n\t\tif !templ_7745c5c3_IsBuffer {\n\t\t\tdefer func() {\n\t\t\t\ttempl_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)\n\t\t\t\tif templ_7745c5c3_Err == nil {\n\t\t\t\t\ttempl_7745c5c3_Err = templ_7745c5c3_BufErr\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\tctx = templ.InitializeContext(ctx)\n\t\ttempl_7745c5c3_Var1 := templ.GetChildren(ctx)\n\t\tif templ_7745c5c3_Var1 == nil {\n\t\t\ttempl_7745c5c3_Var1 = templ.NopComponent\n\t\t}\n\t\tctx = templ.ClearChildren(ctx)\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var4 string\n\t\ttempl_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(loc.T(\"loading\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `metarefresh.templ`, Line: 14, Col: 35}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var5 string\n\t\ttempl_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(loc.T(\"connection_security\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `metarefresh.templ`, Line: 15, Col: 35}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\treturn nil\n\t})\n}\n\nvar _ = templruntime.GeneratedTemplate\n"], ["/anubis/lib/config.go", "package lib\n\nimport (\n\t\"context\"\n\t\"crypto/ed25519\"\n\t\"crypto/rand\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log/slog\"\n\t\"net/http\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/TecharoHQ/anubis/data\"\n\t\"github.com/TecharoHQ/anubis/internal\"\n\t\"github.com/TecharoHQ/anubis/internal/ogtags\"\n\t\"github.com/TecharoHQ/anubis/lib/challenge\"\n\t\"github.com/TecharoHQ/anubis/lib/localization\"\n\t\"github.com/TecharoHQ/anubis/lib/policy\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/web\"\n\t\"github.com/TecharoHQ/anubis/xess\"\n\t\"github.com/a-h/templ\"\n)\n\ntype Options struct {\n\tNext http.Handler\n\tPolicy *policy.ParsedConfig\n\tTarget string\n\tCookieDynamicDomain bool\n\tCookieDomain string\n\tCookieExpiration time.Duration\n\tCookiePartitioned bool\n\tBasePrefix string\n\tWebmasterEmail string\n\tRedirectDomains []string\n\tED25519PrivateKey ed25519.PrivateKey\n\tHS512Secret []byte\n\tStripBasePrefix bool\n\tOpenGraph config.OpenGraph\n\tServeRobotsTXT bool\n\tCookieSecure bool\n}\n\nfunc LoadPoliciesOrDefault(ctx context.Context, fname string, defaultDifficulty int) (*policy.ParsedConfig, error) {\n\tvar fin io.ReadCloser\n\tvar err error\n\n\tif fname != \"\" {\n\t\tfin, err = os.Open(fname)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"can't parse policy file %s: %w\", fname, err)\n\t\t}\n\t} else {\n\t\tfname = \"(data)/botPolicies.yaml\"\n\t\tfin, err = data.BotPolicies.Open(\"botPolicies.yaml\")\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"[unexpected] can't parse builtin policy file %s: %w\", fname, err)\n\t\t}\n\t}\n\n\tdefer func(fin io.ReadCloser) {\n\t\terr := fin.Close()\n\t\tif err != nil {\n\t\t\tslog.Error(\"failed to close policy file\", \"file\", fname, \"err\", err)\n\t\t}\n\t}(fin)\n\n\tanubisPolicy, err := policy.ParseConfig(ctx, fin, fname, defaultDifficulty)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't parse policy file %s: %w\", fname, err)\n\t}\n\tvar validationErrs []error\n\n\tfor _, b := range anubisPolicy.Bots {\n\t\tif _, ok := challenge.Get(b.Challenge.Algorithm); !ok {\n\t\t\tvalidationErrs = append(validationErrs, fmt.Errorf(\"%w %s\", policy.ErrChallengeRuleHasWrongAlgorithm, b.Challenge.Algorithm))\n\t\t}\n\t}\n\n\tif len(validationErrs) != 0 {\n\t\treturn nil, fmt.Errorf(\"can't do final validation of Anubis config: %w\", errors.Join(validationErrs...))\n\t}\n\n\treturn anubisPolicy, err\n}\n\nfunc New(opts Options) (*Server, error) {\n\tif opts.ED25519PrivateKey == nil && opts.HS512Secret == nil {\n\t\tslog.Debug(\"opts.PrivateKey not set, generating a new one\")\n\t\t_, priv, err := ed25519.GenerateKey(rand.Reader)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"lib: can't generate private key: %v\", err)\n\t\t}\n\t\topts.ED25519PrivateKey = priv\n\t}\n\n\tanubis.BasePrefix = opts.BasePrefix\n\n\tresult := &Server{\n\t\tnext: opts.Next,\n\t\ted25519Priv: opts.ED25519PrivateKey,\n\t\ths512Secret: opts.HS512Secret,\n\t\tpolicy: opts.Policy,\n\t\topts: opts,\n\t\tOGTags: ogtags.NewOGTagCache(opts.Target, opts.Policy.OpenGraph, opts.Policy.Store),\n\t\tstore: opts.Policy.Store,\n\t}\n\n\tmux := http.NewServeMux()\n\txess.Mount(mux)\n\n\t// Helper to add global prefix\n\tregisterWithPrefix := func(pattern string, handler http.Handler, method string) {\n\t\tif method != \"\" {\n\t\t\tmethod = method + \" \" // methods must end with a space to register with them\n\t\t}\n\n\t\t// Ensure there's no double slash when concatenating BasePrefix and pattern\n\t\tbasePrefix := strings.TrimSuffix(anubis.BasePrefix, \"/\")\n\t\tprefix := method + basePrefix\n\n\t\t// If pattern doesn't start with a slash, add one\n\t\tif !strings.HasPrefix(pattern, \"/\") {\n\t\t\tpattern = \"/\" + pattern\n\t\t}\n\n\t\tmux.Handle(prefix+pattern, handler)\n\t}\n\n\t// Ensure there's no double slash when concatenating BasePrefix and StaticPath\n\tstripPrefix := strings.TrimSuffix(anubis.BasePrefix, \"/\") + anubis.StaticPath\n\tregisterWithPrefix(anubis.StaticPath, internal.UnchangingCache(internal.NoBrowsing(http.StripPrefix(stripPrefix, http.FileServerFS(web.Static)))), \"\")\n\n\tif opts.ServeRobotsTXT {\n\t\tregisterWithPrefix(\"/robots.txt\", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\thttp.ServeFileFS(w, r, web.Static, \"static/robots.txt\")\n\t\t}), \"GET\")\n\t\tregisterWithPrefix(\"/.well-known/robots.txt\", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\thttp.ServeFileFS(w, r, web.Static, \"static/robots.txt\")\n\t\t}), \"GET\")\n\t}\n\n\tif opts.Policy.Impressum != nil {\n\t\tregisterWithPrefix(anubis.APIPrefix+\"imprint\", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\ttempl.Handler(\n\t\t\t\tweb.Base(opts.Policy.Impressum.Page.Title, opts.Policy.Impressum.Page, opts.Policy.Impressum, localization.GetLocalizer(r)),\n\t\t\t).ServeHTTP(w, r)\n\t\t}), \"GET\")\n\t}\n\n\tregisterWithPrefix(anubis.APIPrefix+\"pass-challenge\", http.HandlerFunc(result.PassChallenge), \"GET\")\n\tregisterWithPrefix(anubis.APIPrefix+\"check\", http.HandlerFunc(result.maybeReverseProxyHttpStatusOnly), \"\")\n\tregisterWithPrefix(\"/\", http.HandlerFunc(result.maybeReverseProxyOrPage), \"\")\n\n\t//goland:noinspection GoBoolExpressions\n\tif anubis.Version == \"devel\" {\n\t\t// make-challenge is only used in tests. Only enable while version is devel\n\t\tregisterWithPrefix(anubis.APIPrefix+\"make-challenge\", http.HandlerFunc(result.MakeChallenge), \"POST\")\n\t}\n\n\tfor _, implKind := range challenge.Methods() {\n\t\timpl, _ := challenge.Get(implKind)\n\t\timpl.Setup(mux)\n\t}\n\n\tresult.mux = mux\n\n\treturn result, nil\n}\n"], ["/anubis/lib/store/bbolt/bbolt.go", "package bbolt\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n\t\"go.etcd.io/bbolt\"\n)\n\n// Sentinel error values used for testing and in admin-visible error messages.\nvar (\n\tErrBucketDoesNotExist = errors.New(\"bbolt: bucket does not exist\")\n\tErrNotExists = errors.New(\"bbolt: value does not exist in store\")\n)\n\n// Store implements store.Interface backed by bbolt[1].\n//\n// In essence, bbolt is a hierarchical key/value store with a twist: every value\n// needs to belong to a bucket. Buckets can contain an infinite number of\n// buckets. As such, Anubis nests values in buckets. Each value in the store\n// is given its own bucket with two keys:\n//\n// 1. data - The raw data, usually in JSON\n// 2. expiry - The expiry time formatted as a time.RFC3339Nano timestamp string\n//\n// When Anubis stores a new bit of data, it creates a new bucket for that value.\n// This allows the cleanup phase to iterate over every bucket in the database and\n// only scan the expiry times without having to decode the entire record.\n//\n// bbolt is not suitable for environments where multiple instance of Anubis need\n// to read from and write to the same backend store. For that, use the valkey\n// storage backend.\n//\n// [1]: https://github.com/etcd-io/bbolt\ntype Store struct {\n\tbdb *bbolt.DB\n}\n\n// Delete a key from the datastore. If the key does not exist, return an error.\nfunc (s *Store) Delete(ctx context.Context, key string) error {\n\treturn s.bdb.Update(func(tx *bbolt.Tx) error {\n\t\tif tx.Bucket([]byte(key)) == nil {\n\t\t\treturn fmt.Errorf(\"%w: %q\", ErrNotExists, key)\n\t\t}\n\n\t\treturn tx.DeleteBucket([]byte(key))\n\t})\n}\n\n// Get a value from the datastore.\n//\n// Because each value is stored in its own bucket with data and expiry keys,\n// two get operations are required:\n//\n// 1. Get the expiry key, parse as time.RFC3339Nano. If the key has expired, run deletion in the background and return a \"key not found\" error.\n// 2. Get the data key, copy into the result byteslice, return it.\nfunc (s *Store) Get(ctx context.Context, key string) ([]byte, error) {\n\tvar result []byte\n\n\tif err := s.bdb.View(func(tx *bbolt.Tx) error {\n\t\titemBucket := tx.Bucket([]byte(key))\n\t\tif itemBucket == nil {\n\t\t\treturn fmt.Errorf(\"%w: %q\", store.ErrNotFound, key)\n\t\t}\n\n\t\texpiryStr := itemBucket.Get([]byte(\"expiry\"))\n\t\tif expiryStr == nil {\n\t\t\treturn fmt.Errorf(\"[unexpected] %w: %q (expiry is nil)\", store.ErrNotFound, key)\n\t\t}\n\n\t\texpiry, err := time.Parse(time.RFC3339Nano, string(expiryStr))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"[unexpected] %w: %w\", store.ErrCantDecode, err)\n\t\t}\n\n\t\tif time.Now().After(expiry) {\n\t\t\tgo s.Delete(context.Background(), key)\n\t\t\treturn fmt.Errorf(\"%w: %q\", store.ErrNotFound, key)\n\t\t}\n\n\t\tdataStr := itemBucket.Get([]byte(\"data\"))\n\t\tif dataStr == nil {\n\t\t\treturn fmt.Errorf(\"[unexpected] %w: %q (data is nil)\", store.ErrNotFound, key)\n\t\t}\n\n\t\tresult = make([]byte, len(dataStr))\n\t\tif n := copy(result, dataStr); n != len(dataStr) {\n\t\t\treturn fmt.Errorf(\"[unexpected] %w: %d bytes copied of %d\", store.ErrCantDecode, n, len(dataStr))\n\t\t}\n\n\t\treturn nil\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn result, nil\n}\n\n// Set a value into the store with a given expiry.\nfunc (s *Store) Set(ctx context.Context, key string, value []byte, expiry time.Duration) error {\n\texpires := time.Now().Add(expiry)\n\n\treturn s.bdb.Update(func(tx *bbolt.Tx) error {\n\t\tvalueBkt, err := tx.CreateBucketIfNotExists([]byte(key))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"%w: %w: %q (create bucket)\", store.ErrCantEncode, err, key)\n\t\t}\n\n\t\tif err := valueBkt.Put([]byte(\"expiry\"), []byte(expires.Format(time.RFC3339Nano))); err != nil {\n\t\t\treturn fmt.Errorf(\"%w: %q (expiry)\", store.ErrCantEncode, key)\n\t\t}\n\n\t\tif err := valueBkt.Put([]byte(\"data\"), value); err != nil {\n\t\t\treturn fmt.Errorf(\"%w: %q (data)\", store.ErrCantEncode, key)\n\t\t}\n\n\t\treturn nil\n\t})\n}\n\nfunc (s *Store) cleanup(ctx context.Context) error {\n\tnow := time.Now()\n\n\treturn s.bdb.Update(func(tx *bbolt.Tx) error {\n\t\treturn tx.ForEach(func(key []byte, valueBkt *bbolt.Bucket) error {\n\t\t\tvar expiry time.Time\n\t\t\tvar err error\n\n\t\t\texpiryStr := valueBkt.Get([]byte(\"expiry\"))\n\t\t\tif expiryStr == nil {\n\t\t\t\tslog.Warn(\"while running cleanup, expiry is not set somehow, file a bug?\", \"key\", string(key))\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\texpiry, err = time.Parse(time.RFC3339Nano, string(expiryStr))\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"[unexpected] %w in bucket %q: %w\", store.ErrCantDecode, string(key), err)\n\t\t\t}\n\n\t\t\tif now.After(expiry) {\n\t\t\t\treturn tx.DeleteBucket(key)\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\t})\n}\n\nfunc (s *Store) cleanupThread(ctx context.Context) {\n\tt := time.NewTicker(time.Hour)\n\tdefer t.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase <-t.C:\n\t\t\tif err := s.cleanup(ctx); err != nil {\n\t\t\t\tslog.Error(\"error during bbolt cleanup\", \"err\", err)\n\t\t\t}\n\t\t}\n\t}\n}\n"], ["/anubis/lib/policy/config/asn.go", "package config\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\nvar (\n\tErrPrivateASN = errors.New(\"bot.ASNs: you have specified a private use ASN\")\n)\n\ntype ASNs struct {\n\tMatch []uint32 `json:\"match\"`\n}\n\nfunc (a *ASNs) Valid() error {\n\tvar errs []error\n\n\tfor _, asn := range a.Match {\n\t\tif isPrivateASN(asn) {\n\t\t\terrs = append(errs, fmt.Errorf(\"%w: %d is private (see RFC 6996)\", ErrPrivateASN, asn))\n\t\t}\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"bot.ASNs: invalid ASN settings: %w\", errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n\n// isPrivateASN checks if an ASN is in the private use area.\n//\n// Based on RFC 6996 and IANA allocations.\nfunc isPrivateASN(asn uint32) bool {\n\tswitch {\n\tcase asn >= 64512 && asn <= 65534:\n\t\treturn true\n\tcase asn >= 4200000000 && asn <= 4294967294:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n"], ["/anubis/lib/policy/config/impressum.go", "package config\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n)\n\nvar ErrMissingValue = errors.New(\"config: missing value\")\n\ntype Impressum struct {\n\tFooter string `json:\"footer\" yaml:\"footer\"`\n\tPage ImpressumPage `json:\"page\" yaml:\"page\"`\n}\n\nfunc (i Impressum) Render(_ context.Context, w io.Writer) error {\n\tif _, err := fmt.Fprint(w, i.Footer); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (i Impressum) Valid() error {\n\tvar errs []error\n\n\tif len(i.Footer) == 0 {\n\t\terrs = append(errs, fmt.Errorf(\"%w: impressum footer must be defined\", ErrMissingValue))\n\t}\n\n\tif err := i.Page.Valid(); err != nil {\n\t\terrs = append(errs, err)\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn errors.Join(errs...)\n\t}\n\n\treturn nil\n}\n\ntype ImpressumPage struct {\n\tTitle string `json:\"title\" yaml:\"title\"`\n\tBody string `json:\"body\" yaml:\"body\"`\n}\n\nfunc (ip ImpressumPage) Render(_ context.Context, w io.Writer) error {\n\tif _, err := fmt.Fprint(w, ip.Body); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (ip ImpressumPage) Valid() error {\n\tvar errs []error\n\n\tif len(ip.Title) == 0 {\n\t\terrs = append(errs, fmt.Errorf(\"%w: impressum page title must be defined\", ErrMissingValue))\n\t}\n\n\tif len(ip.Body) == 0 {\n\t\terrs = append(errs, fmt.Errorf(\"%w: impressum body title must be defined\", ErrMissingValue))\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn errors.Join(errs...)\n\t}\n\n\treturn nil\n}\n"], ["/anubis/internal/ogtags/fetch.go", "package ogtags\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log/slog\"\n\t\"mime\"\n\t\"net\"\n\t\"net/http\"\n\n\t\"golang.org/x/net/html\"\n)\n\nvar (\n\tErrOgHandled = errors.New(\"og: handled error\") // used to indicate that the error was handled and should not be logged\n\temptyMap = map[string]string{} // used to indicate an empty result in the cache. Can't use nil as it would be a cache miss.\n)\n\n// fetchHTMLDocumentWithCache fetches the HTML document from the given URL string,\n// preserving the original host header.\nfunc (c *OGTagCache) fetchHTMLDocumentWithCache(ctx context.Context, urlStr string, originalHost string, cacheKey string) (*html.Node, error) {\n\treq, err := http.NewRequestWithContext(ctx, \"GET\", urlStr, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create http request: %w\", err)\n\t}\n\n\t// Set the Host header to the original host\n\tif originalHost != \"\" {\n\t\treq.Host = originalHost\n\t}\n\n\t// Add proxy headers\n\treq.Header.Set(\"X-Forwarded-Proto\", \"https\")\n\treq.Header.Set(\"User-Agent\", \"Anubis-OGTag-Fetcher/1.0\") // For tracking purposes\n\n\t// Send the request\n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\tvar netErr net.Error\n\t\tif errors.As(err, &netErr) && netErr.Timeout() {\n\t\t\tslog.Debug(\"og: request timed out\", \"url\", urlStr)\n\t\t\tc.cache.Set(ctx, cacheKey, emptyMap, c.ogTimeToLive/2) // Cache empty result for half the TTL to not spam the server\n\t\t}\n\t\treturn nil, fmt.Errorf(\"http get failed: %w\", err)\n\t}\n\n\t// Ensure the response body is closed\n\tdefer func(Body io.ReadCloser) {\n\t\terr := Body.Close()\n\t\tif err != nil {\n\t\t\tslog.Debug(\"og: error closing response body\", \"url\", urlStr, \"error\", err)\n\t\t}\n\t}(resp.Body)\n\n\tif resp.StatusCode != http.StatusOK {\n\t\tslog.Debug(\"og: received non-OK status code\", \"url\", urlStr, \"status\", resp.StatusCode)\n\t\tc.cache.Set(ctx, cacheKey, emptyMap, c.ogTimeToLive) // Cache empty result for non-successful status codes\n\t\treturn nil, fmt.Errorf(\"%w: page not found\", ErrOgHandled)\n\t}\n\n\t// Check content type\n\tct := resp.Header.Get(\"Content-Type\")\n\tif ct == \"\" {\n\t\treturn nil, fmt.Errorf(\"missing Content-Type header\")\n\t} else {\n\t\tmediaType, _, err := mime.ParseMediaType(ct)\n\t\tif err != nil {\n\t\t\tslog.Debug(\"og: malformed Content-Type header\", \"url\", urlStr, \"contentType\", ct)\n\t\t\treturn nil, fmt.Errorf(\"%w malformed Content-Type header: %w\", ErrOgHandled, err)\n\t\t}\n\n\t\tif mediaType != \"text/html\" && mediaType != \"application/xhtml+xml\" {\n\t\t\tslog.Debug(\"og: unsupported Content-Type\", \"url\", urlStr, \"contentType\", mediaType)\n\t\t\treturn nil, fmt.Errorf(\"%w unsupported Content-Type: %s\", ErrOgHandled, mediaType)\n\t\t}\n\t}\n\n\tresp.Body = http.MaxBytesReader(nil, resp.Body, maxContentLength)\n\n\tdoc, err := html.Parse(resp.Body)\n\tif err != nil {\n\t\t// Check if the error is specifically because the limit was exceeded\n\t\tvar maxBytesErr *http.MaxBytesError\n\t\tif errors.As(err, &maxBytesErr) {\n\t\t\tslog.Debug(\"og: content exceeded max length\", \"url\", urlStr, \"limit\", maxContentLength)\n\t\t\treturn nil, fmt.Errorf(\"content too large: exceeded %d bytes\", maxContentLength)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"failed to parse HTML: %w\", err)\n\t}\n\n\treturn doc, nil\n}\n"], ["/anubis/cmd/robots2policy/batch/batch_process.go", "/*\nBatch process robots.txt files from archives like https://github.com/nrjones8/robots-dot-txt-archive-bot/tree/master/data/cleaned\ninto Anubis CEL policies. Usage: go run batch_process.go \n*/\npackage main\n\nimport (\n\t\"fmt\"\n\t\"io/fs\"\n\t\"log\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\nfunc main() {\n\tif len(os.Args) < 2 {\n\t\tfmt.Println(\"Usage: go run batch_process.go \")\n\t\tfmt.Println(\"Example: go run batch_process.go ./cleaned\")\n\t\tos.Exit(1)\n\t}\n\n\tcleanedDir := os.Args[1]\n\toutputDir := \"generated_policies\"\n\n\t// Create output directory\n\tif err := os.MkdirAll(outputDir, 0755); err != nil {\n\t\tlog.Fatalf(\"Failed to create output directory: %v\", err)\n\t}\n\n\tcount := 0\n\terr := filepath.WalkDir(cleanedDir, func(path string, d fs.DirEntry, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Skip directories\n\t\tif d.IsDir() {\n\t\t\treturn nil\n\t\t}\n\n\t\t// Generate policy name from file path\n\t\trelPath, _ := filepath.Rel(cleanedDir, path)\n\t\tpolicyName := strings.ReplaceAll(relPath, \"/\", \"-\")\n\t\tpolicyName = strings.TrimSuffix(policyName, \"-robots.txt\")\n\t\tpolicyName = strings.ReplaceAll(policyName, \".\", \"-\")\n\n\t\toutputFile := filepath.Join(outputDir, policyName+\".yaml\")\n\n\t\tcmd := exec.Command(\"go\", \"run\", \"main.go\",\n\t\t\t\"-input\", path,\n\t\t\t\"-output\", outputFile,\n\t\t\t\"-name\", policyName,\n\t\t\t\"-format\", \"yaml\")\n\n\t\tif err := cmd.Run(); err != nil {\n\t\t\tfmt.Printf(\"Warning: Failed to process %s: %v\\n\", path, err)\n\t\t\treturn nil // Continue processing other files\n\t\t}\n\n\t\tcount++\n\t\tif count%100 == 0 {\n\t\t\tfmt.Printf(\"Processed %d files...\\n\", count)\n\t\t} else if count%10 == 0 {\n\t\t\tfmt.Print(\".\")\n\t\t}\n\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\tlog.Fatalf(\"Error walking directory: %v\", err)\n\t}\n\n\tfmt.Printf(\"Successfully processed %d robots.txt files\\n\", count)\n\tfmt.Printf(\"Generated policies saved to: %s/\\n\", outputDir)\n}\n"], ["/anubis/internal/health.go", "package internal\n\nimport (\n\t\"context\"\n\n\t\"google.golang.org/grpc/health\"\n\thealthv1 \"google.golang.org/grpc/health/grpc_health_v1\"\n)\n\nvar HealthSrv = health.NewServer()\n\nfunc SetHealth(svc string, status healthv1.HealthCheckResponse_ServingStatus) {\n\tHealthSrv.SetServingStatus(svc, status)\n}\n\nfunc GetHealth(svc string) (healthv1.HealthCheckResponse_ServingStatus, bool) {\n\tst, err := HealthSrv.Check(context.Background(), &healthv1.HealthCheckRequest{\n\t\tService: svc,\n\t})\n\tif err != nil {\n\t\treturn healthv1.HealthCheckResponse_UNKNOWN, false\n\t}\n\n\treturn st.GetStatus(), true\n}\n"], ["/anubis/lib/policy/checker.go", "package policy\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/netip\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com/TecharoHQ/anubis/internal\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/checker\"\n\t\"github.com/gaissmai/bart\"\n)\n\nvar (\n\tErrMisconfiguration = errors.New(\"[unexpected] policy: administrator misconfiguration\")\n)\n\ntype RemoteAddrChecker struct {\n\tprefixTable *bart.Lite\n\thash string\n}\n\nfunc NewRemoteAddrChecker(cidrs []string) (checker.Impl, error) {\n\ttable := new(bart.Lite)\n\n\tfor _, cidr := range cidrs {\n\t\tprefix, err := netip.ParsePrefix(cidr)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"%w: range %s not parsing: %w\", ErrMisconfiguration, cidr, err)\n\t\t}\n\n\t\ttable.Insert(prefix)\n\t}\n\n\treturn &RemoteAddrChecker{\n\t\tprefixTable: table,\n\t\thash: internal.FastHash(strings.Join(cidrs, \",\")),\n\t}, nil\n}\n\nfunc (rac *RemoteAddrChecker) Check(r *http.Request) (bool, error) {\n\thost := r.Header.Get(\"X-Real-Ip\")\n\tif host == \"\" {\n\t\treturn false, fmt.Errorf(\"%w: header X-Real-Ip is not set\", ErrMisconfiguration)\n\t}\n\n\taddr, err := netip.ParseAddr(host)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"%w: %s is not an IP address: %w\", ErrMisconfiguration, host, err)\n\t}\n\n\treturn rac.prefixTable.Contains(addr), nil\n}\n\nfunc (rac *RemoteAddrChecker) Hash() string {\n\treturn rac.hash\n}\n\ntype HeaderMatchesChecker struct {\n\theader string\n\tregexp *regexp.Regexp\n\thash string\n}\n\nfunc NewUserAgentChecker(rexStr string) (checker.Impl, error) {\n\treturn NewHeaderMatchesChecker(\"User-Agent\", rexStr)\n}\n\nfunc NewHeaderMatchesChecker(header, rexStr string) (checker.Impl, error) {\n\trex, err := regexp.Compile(strings.TrimSpace(rexStr))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: regex %s failed parse: %w\", ErrMisconfiguration, rexStr, err)\n\t}\n\treturn &HeaderMatchesChecker{strings.TrimSpace(header), rex, internal.FastHash(header + \": \" + rexStr)}, nil\n}\n\nfunc (hmc *HeaderMatchesChecker) Check(r *http.Request) (bool, error) {\n\tif hmc.regexp.MatchString(r.Header.Get(hmc.header)) {\n\t\treturn true, nil\n\t}\n\n\treturn false, nil\n}\n\nfunc (hmc *HeaderMatchesChecker) Hash() string {\n\treturn hmc.hash\n}\n\ntype PathChecker struct {\n\tregexp *regexp.Regexp\n\thash string\n}\n\nfunc NewPathChecker(rexStr string) (checker.Impl, error) {\n\trex, err := regexp.Compile(strings.TrimSpace(rexStr))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: regex %s failed parse: %w\", ErrMisconfiguration, rexStr, err)\n\t}\n\treturn &PathChecker{rex, internal.FastHash(rexStr)}, nil\n}\n\nfunc (pc *PathChecker) Check(r *http.Request) (bool, error) {\n\tif pc.regexp.MatchString(r.URL.Path) {\n\t\treturn true, nil\n\t}\n\n\treturn false, nil\n}\n\nfunc (pc *PathChecker) Hash() string {\n\treturn pc.hash\n}\n\nfunc NewHeaderExistsChecker(key string) checker.Impl {\n\treturn headerExistsChecker{strings.TrimSpace(key)}\n}\n\ntype headerExistsChecker struct {\n\theader string\n}\n\nfunc (hec headerExistsChecker) Check(r *http.Request) (bool, error) {\n\tif r.Header.Get(hec.header) != \"\" {\n\t\treturn true, nil\n\t}\n\n\treturn false, nil\n}\n\nfunc (hec headerExistsChecker) Hash() string {\n\treturn internal.FastHash(hec.header)\n}\n\nfunc NewHeadersChecker(headermap map[string]string) (checker.Impl, error) {\n\tvar result checker.List\n\tvar errs []error\n\n\tfor key, rexStr := range headermap {\n\t\tif rexStr == \".*\" {\n\t\t\tresult = append(result, headerExistsChecker{strings.TrimSpace(key)})\n\t\t\tcontinue\n\t\t}\n\n\t\trex, err := regexp.Compile(strings.TrimSpace(rexStr))\n\t\tif err != nil {\n\t\t\terrs = append(errs, fmt.Errorf(\"while compiling header %s regex %s: %w\", key, rexStr, err))\n\t\t\tcontinue\n\t\t}\n\n\t\tresult = append(result, &HeaderMatchesChecker{key, rex, internal.FastHash(key + \": \" + rexStr)})\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn nil, errors.Join(errs...)\n\t}\n\n\treturn result, nil\n}\n"], ["/anubis/lib/policy/config/opengraph.go", "package config\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"time\"\n)\n\nvar (\n\tErrInvalidOpenGraphConfig = errors.New(\"config.OpenGraph: invalid OpenGraph configuration\")\n\tErrOpenGraphTTLDoesNotParse = errors.New(\"config.OpenGraph: ttl does not parse as a Duration, see https://pkg.go.dev/time#ParseDuration (formatted like 5m -> 5 minutes, 2h -> 2 hours, etc)\")\n\tErrOpenGraphMissingProperty = errors.New(\"config.OpenGraph: default opengraph tags missing a property\")\n)\n\ntype openGraphFileConfig struct {\n\tEnabled bool `json:\"enabled\" yaml:\"enabled\"`\n\tConsiderHost bool `json:\"considerHost\" yaml:\"enabled\"`\n\tTimeToLive string `json:\"ttl\" yaml:\"ttl\"`\n\tOverride map[string]string `json:\"override,omitempty\" yaml:\"override,omitempty\"`\n}\n\ntype OpenGraph struct {\n\tEnabled bool `json:\"enabled\" yaml:\"enabled\"`\n\tConsiderHost bool `json:\"considerHost\" yaml:\"enabled\"`\n\tOverride map[string]string `json:\"override,omitempty\" yaml:\"override,omitempty\"`\n\tTimeToLive time.Duration `json:\"ttl\" yaml:\"ttl\"`\n}\n\nfunc (og *openGraphFileConfig) Valid() error {\n\tvar errs []error\n\n\tif _, err := time.ParseDuration(og.TimeToLive); err != nil {\n\t\terrs = append(errs, fmt.Errorf(\"%w: ParseDuration(%q) returned: %w\", ErrOpenGraphTTLDoesNotParse, og.TimeToLive, err))\n\t}\n\n\tif len(og.Override) != 0 {\n\t\tfor _, tag := range []string{\n\t\t\t\"og:title\",\n\t\t} {\n\t\t\tif _, ok := og.Override[tag]; !ok {\n\t\t\t\terrs = append(errs, fmt.Errorf(\"%w: %s\", ErrOpenGraphMissingProperty, tag))\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn errors.Join(ErrInvalidOpenGraphConfig, errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n"], ["/anubis/lib/policy/config/threshold.go", "package config\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com/TecharoHQ/anubis\"\n)\n\nvar (\n\tErrNoThresholdRulesDefined = errors.New(\"config: no thresholds defined\")\n\tErrThresholdMustHaveName = errors.New(\"config.Threshold: must set name\")\n\tErrThresholdMustHaveExpression = errors.New(\"config.Threshold: must set expression\")\n\tErrThresholdChallengeMustHaveChallenge = errors.New(\"config.Threshold: a threshold with the CHALLENGE action must have challenge set\")\n\tErrThresholdCannotHaveWeighAction = errors.New(\"config.Threshold: a threshold cannot have the WEIGH action\")\n\n\tDefaultThresholds = []Threshold{\n\t\t{\n\t\t\tName: \"legacy-anubis-behaviour\",\n\t\t\tExpression: &ExpressionOrList{\n\t\t\t\tExpression: \"weight > 0\",\n\t\t\t},\n\t\t\tAction: RuleChallenge,\n\t\t\tChallenge: &ChallengeRules{\n\t\t\t\tAlgorithm: \"fast\",\n\t\t\t\tDifficulty: anubis.DefaultDifficulty,\n\t\t\t\tReportAs: anubis.DefaultDifficulty,\n\t\t\t},\n\t\t},\n\t}\n)\n\ntype Threshold struct {\n\tName string `json:\"name\" yaml:\"name\"`\n\tExpression *ExpressionOrList `json:\"expression\" yaml:\"expression\"`\n\tAction Rule `json:\"action\" yaml:\"action\"`\n\tChallenge *ChallengeRules `json:\"challenge\" yaml:\"challenge\"`\n}\n\nfunc (t Threshold) Valid() error {\n\tvar errs []error\n\n\tif len(t.Name) == 0 {\n\t\terrs = append(errs, ErrThresholdMustHaveName)\n\t}\n\n\tif t.Expression == nil {\n\t\terrs = append(errs, ErrThresholdMustHaveExpression)\n\t}\n\n\tif t.Expression != nil {\n\t\tif err := t.Expression.Valid(); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\tif err := t.Action.Valid(); err != nil {\n\t\terrs = append(errs, err)\n\t}\n\n\tif t.Action == RuleWeigh {\n\t\terrs = append(errs, ErrThresholdCannotHaveWeighAction)\n\t}\n\n\tif t.Action == RuleChallenge && t.Challenge == nil {\n\t\terrs = append(errs, ErrThresholdChallengeMustHaveChallenge)\n\t}\n\n\tif t.Challenge != nil {\n\t\tif err := t.Challenge.Valid(); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"config: threshold entry for %q is not valid:\\n%w\", t.Name, errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n"], ["/anubis/lib/localization/localization.go", "package localization\n\nimport (\n\t\"embed\"\n\t\"encoding/json\"\n\t\"net/http\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/nicksnyder/go-i18n/v2/i18n\"\n\t\"golang.org/x/text/language\"\n)\n\n//go:embed locales/*.json\nvar localeFS embed.FS\n\ntype LocalizationService struct {\n\tbundle *i18n.Bundle\n}\n\nvar (\n\tglobalService *LocalizationService\n\tonce sync.Once\n)\n\nfunc NewLocalizationService() *LocalizationService {\n\tonce.Do(func() {\n\t\tbundle := i18n.NewBundle(language.English)\n\t\tbundle.RegisterUnmarshalFunc(\"json\", json.Unmarshal)\n\n\t\t// Read all JSON files from the locales directory\n\t\tentries, err := localeFS.ReadDir(\"locales\")\n\t\tif err != nil {\n\t\t\t// Try fallback - create a minimal service with default messages\n\t\t\tglobalService = &LocalizationService{bundle: bundle}\n\t\t\treturn\n\t\t}\n\n\t\tloadedAny := false\n\t\tfor _, entry := range entries {\n\t\t\tif !entry.IsDir() && strings.HasSuffix(entry.Name(), \".json\") {\n\t\t\t\tfilePath := \"locales/\" + entry.Name()\n\t\t\t\t_, err := bundle.LoadMessageFileFS(localeFS, filePath)\n\t\t\t\tif err != nil {\n\t\t\t\t\t// Log error but continue with other files\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tloadedAny = true\n\t\t\t}\n\t\t}\n\n\t\tif !loadedAny {\n\t\t\t// If no files were loaded successfully, create minimal service\n\t\t\tglobalService = &LocalizationService{bundle: bundle}\n\t\t\treturn\n\t\t}\n\n\t\tglobalService = &LocalizationService{bundle: bundle}\n\t})\n\n\t// Safety check - if globalService is still nil, create a minimal one\n\tif globalService == nil {\n\t\tbundle := i18n.NewBundle(language.English)\n\t\tbundle.RegisterUnmarshalFunc(\"json\", json.Unmarshal)\n\t\tglobalService = &LocalizationService{bundle: bundle}\n\t}\n\n\treturn globalService\n}\n\nfunc (ls *LocalizationService) GetLocalizer(lang string) *i18n.Localizer {\n\treturn i18n.NewLocalizer(ls.bundle, lang)\n}\n\nfunc (ls *LocalizationService) GetLocalizerFromRequest(r *http.Request) *i18n.Localizer {\n\tif ls == nil || ls.bundle == nil {\n\t\t// Fallback to a basic bundle if service is not properly initialized\n\t\tbundle := i18n.NewBundle(language.English)\n\t\tbundle.RegisterUnmarshalFunc(\"json\", json.Unmarshal)\n\t\treturn i18n.NewLocalizer(bundle, \"en\")\n\t}\n\tacceptLanguage := r.Header.Get(\"Accept-Language\")\n\treturn i18n.NewLocalizer(ls.bundle, acceptLanguage, \"en\")\n}\n\n// SimpleLocalizer wraps i18n.Localizer with a more convenient API\ntype SimpleLocalizer struct {\n\tLocalizer *i18n.Localizer\n}\n\n// T provides a concise way to localize messages\nfunc (sl *SimpleLocalizer) T(messageID string) string {\n\treturn sl.Localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: messageID})\n}\n\n// Get the language that is used by the localizer by retrieving a well-known string that is required to be present\nfunc (sl *SimpleLocalizer) GetLang() string {\n\t_, tag, err := sl.Localizer.LocalizeWithTag(&i18n.LocalizeConfig{MessageID: \"loading\"})\n\tif err != nil {\n\t\treturn \"en\"\n\t}\n\treturn tag.String()\n}\n\n// GetLocalizer creates a localizer based on the request's Accept-Language header or forcedLanguage option\nfunc GetLocalizer(r *http.Request) *SimpleLocalizer {\n\tvar localizer *i18n.Localizer\n\tif anubis.ForcedLanguage == \"\" {\n\t\tlocalizer = NewLocalizationService().GetLocalizerFromRequest(r)\n\t} else {\n\t\tlocalizer = NewLocalizationService().GetLocalizer(anubis.ForcedLanguage)\n\t}\n\treturn &SimpleLocalizer{Localizer: localizer}\n}\n"], ["/anubis/lib/policy/config/geoip.go", "package config\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"regexp\"\n\t\"strings\"\n)\n\nvar (\n\tcountryCodeRegexp = regexp.MustCompile(`^[a-zA-Z]{2}$`)\n\n\tErrNotCountryCode = errors.New(\"config.Bot: invalid country code\")\n)\n\ntype GeoIP struct {\n\tCountries []string `json:\"countries\"`\n}\n\nfunc (g *GeoIP) Valid() error {\n\tvar errs []error\n\n\tfor i, cc := range g.Countries {\n\t\tif !countryCodeRegexp.MatchString(cc) {\n\t\t\terrs = append(errs, fmt.Errorf(\"%w: %s\", ErrNotCountryCode, cc))\n\t\t}\n\n\t\tg.Countries[i] = strings.ToLower(cc)\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"bot.GeoIP: invalid GeoIP settings: %w\", errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n"], ["/anubis/utils/cmd/backoff-retry/main.go", "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"os\"\n\t\"os/exec\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar (\n\tstartWait = flag.Duration(\"start-wait\", 250*time.Millisecond, \"amount of time to start with exponential backoff\")\n\ttryCount = flag.Int(\"try-count\", 5, \"number of retries\")\n)\n\nfunc main() {\n\tflag.Parse()\n\n\tcmdStr := strings.Join(flag.Args(), \" \")\n\twait := *startWait\n\n\tfor i := range make([]struct{}, *tryCount) {\n\t\tslog.Info(\"executing\", \"try\", i+1, \"wait\", wait, \"cmd\", cmdStr)\n\n\t\tcmd := exec.Command(\"sh\", \"-c\", cmdStr)\n\t\tcmd.Stdin = nil\n\t\tcmd.Stdout = os.Stdout\n\t\tcmd.Stderr = os.Stderr\n\n\t\tif err := cmd.Run(); err != nil {\n\t\t\ttime.Sleep(wait)\n\t\t\twait = wait * 2\n\t\t} else {\n\t\t\tos.Exit(0)\n\t\t}\n\t}\n\n\tfmt.Printf(\"giving up after %d tries\\n\", *tryCount)\n\tos.Exit(1)\n}\n"], ["/anubis/internal/gzip.go", "package internal\n\nimport (\n\t\"compress/gzip\"\n\t\"net/http\"\n\t\"strings\"\n)\n\nfunc GzipMiddleware(level int, next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif !strings.Contains(r.Header.Get(\"Accept-Encoding\"), \"gzip\") {\n\t\t\tnext.ServeHTTP(w, r)\n\t\t\treturn\n\t\t}\n\n\t\tw.Header().Set(\"Content-Encoding\", \"gzip\")\n\t\tgz, err := gzip.NewWriterLevel(w, level)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tdefer gz.Close()\n\n\t\tgrw := gzipResponseWriter{ResponseWriter: w, sink: gz}\n\t\tnext.ServeHTTP(grw, r)\n\t})\n}\n\ntype gzipResponseWriter struct {\n\thttp.ResponseWriter\n\tsink *gzip.Writer\n}\n\nfunc (w gzipResponseWriter) Write(b []byte) (int, error) {\n\treturn w.sink.Write(b)\n}\n"], ["/anubis/lib/store/bbolt/factory.go", "package bbolt\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n\t\"go.etcd.io/bbolt\"\n)\n\nvar (\n\tErrMissingPath = errors.New(\"bbolt: path is missing from config\")\n\tErrCantWriteToPath = errors.New(\"bbolt: can't write to path\")\n)\n\nfunc init() {\n\tstore.Register(\"bbolt\", Factory{})\n}\n\n// Factory builds new instances of the bbolt storage backend according to\n// configuration passed via a json.RawMessage.\ntype Factory struct{}\n\n// Build parses and validates the bbolt storage backend Config and creates\n// a new instance of it.\nfunc (Factory) Build(ctx context.Context, data json.RawMessage) (store.Interface, error) {\n\tvar config Config\n\tif err := json.Unmarshal([]byte(data), &config); err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\tif err := config.Valid(); err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\tbdb, err := bbolt.Open(config.Path, 0600, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't open bbolt database %s: %w\", config.Path, err)\n\t}\n\n\tresult := &Store{\n\t\tbdb: bdb,\n\t}\n\n\tgo result.cleanupThread(ctx)\n\n\treturn result, nil\n}\n\n// Valid parses and validates the bbolt store Config or returns\n// an error.\nfunc (Factory) Valid(data json.RawMessage) error {\n\tvar config Config\n\tif err := json.Unmarshal([]byte(data), &config); err != nil {\n\t\treturn fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\tif err := config.Valid(); err != nil {\n\t\treturn fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\treturn nil\n}\n\n// Config is the bbolt storage backend configuration.\ntype Config struct {\n\t// Path is the filesystem path of the database. The folder must be writable to Anubis.\n\tPath string `json:\"path\"`\n}\n\n// Valid validates the configuration including checking if its containing folder is writable.\nfunc (c Config) Valid() error {\n\tvar errs []error\n\n\tif c.Path == \"\" {\n\t\terrs = append(errs, ErrMissingPath)\n\t} else {\n\t\tdir := filepath.Dir(c.Path)\n\t\tif err := os.WriteFile(filepath.Join(dir, \".test-file\"), []byte(\"\"), 0600); err != nil {\n\t\t\terrs = append(errs, ErrCantWriteToPath)\n\t\t}\n\t\tos.Remove(filepath.Join(dir, \".test-file\"))\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn errors.Join(errs...)\n\t}\n\n\treturn nil\n}\n"], ["/anubis/lib/policy/expressions/environment.go", "package expressions\n\nimport (\n\t\"math/rand/v2\"\n\t\"strings\"\n\n\t\"github.com/google/cel-go/cel\"\n\t\"github.com/google/cel-go/common/types\"\n\t\"github.com/google/cel-go/common/types/ref\"\n\t\"github.com/google/cel-go/common/types/traits\"\n\t\"github.com/google/cel-go/ext\"\n)\n\n// BotEnvironment creates a new CEL environment, this is the set of\n// variables and functions that are passed into the CEL scope so that\n// Anubis can fail loudly and early when something is invalid instead\n// of blowing up at runtime.\nfunc BotEnvironment() (*cel.Env, error) {\n\treturn New(\n\t\t// Variables exposed to CEL programs:\n\t\tcel.Variable(\"remoteAddress\", cel.StringType),\n\t\tcel.Variable(\"host\", cel.StringType),\n\t\tcel.Variable(\"method\", cel.StringType),\n\t\tcel.Variable(\"userAgent\", cel.StringType),\n\t\tcel.Variable(\"path\", cel.StringType),\n\t\tcel.Variable(\"query\", cel.MapType(cel.StringType, cel.StringType)),\n\t\tcel.Variable(\"headers\", cel.MapType(cel.StringType, cel.StringType)),\n\t\tcel.Variable(\"load_1m\", cel.DoubleType),\n\t\tcel.Variable(\"load_5m\", cel.DoubleType),\n\t\tcel.Variable(\"load_15m\", cel.DoubleType),\n\n\t\t// Bot-specific functions:\n\t\tcel.Function(\"missingHeader\",\n\t\t\tcel.Overload(\"missingHeader_map_string_string_string\",\n\t\t\t\t[]*cel.Type{cel.MapType(cel.StringType, cel.StringType), cel.StringType},\n\t\t\t\tcel.BoolType,\n\t\t\t\tcel.BinaryBinding(func(headers, key ref.Val) ref.Val {\n\t\t\t\t\t// Convert headers to a trait that supports Find\n\t\t\t\t\theadersMap, ok := headers.(traits.Indexer)\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn types.ValOrErr(headers, \"headers is not a map, but is %T\", headers)\n\t\t\t\t\t}\n\n\t\t\t\t\tkeyStr, ok := key.(types.String)\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn types.ValOrErr(key, \"key is not a string, but is %T\", key)\n\t\t\t\t\t}\n\n\t\t\t\t\tval := headersMap.Get(keyStr)\n\t\t\t\t\t// Check if the key is missing by testing for an error\n\t\t\t\t\tif types.IsError(val) {\n\t\t\t\t\t\treturn types.Bool(true) // header is missing\n\t\t\t\t\t}\n\t\t\t\t\treturn types.Bool(false) // header is present\n\t\t\t\t}),\n\t\t\t),\n\t\t),\n\n\t\tcel.Function(\"segments\",\n\t\t\tcel.Overload(\"segments_string_list_string\",\n\t\t\t\t[]*cel.Type{cel.StringType},\n\t\t\t\tcel.ListType(cel.StringType),\n\t\t\t\tcel.UnaryBinding(func(path ref.Val) ref.Val {\n\t\t\t\t\tpathStrType, ok := path.(types.String)\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn types.ValOrErr(path, \"path is not a string, but is %T\", path)\n\t\t\t\t\t}\n\n\t\t\t\t\tpathStr := string(pathStrType)\n\t\t\t\t\tif !strings.HasPrefix(pathStr, \"/\") {\n\t\t\t\t\t\treturn types.ValOrErr(path, \"path does not start with /\")\n\t\t\t\t\t}\n\n\t\t\t\t\tpathList := strings.Split(string(pathStr), \"/\")[1:]\n\n\t\t\t\t\treturn types.NewStringList(types.DefaultTypeAdapter, pathList)\n\t\t\t\t}),\n\t\t\t),\n\t\t),\n\t)\n}\n\n// NewThreshold creates a new CEL environment for threshold checking.\nfunc ThresholdEnvironment() (*cel.Env, error) {\n\treturn New(\n\t\tcel.Variable(\"weight\", cel.IntType),\n\t)\n}\n\nfunc New(opts ...cel.EnvOption) (*cel.Env, error) {\n\targs := []cel.EnvOption{\n\t\text.Strings(\n\t\t\text.StringsLocale(\"en_US\"),\n\t\t\text.StringsValidateFormatCalls(true),\n\t\t),\n\n\t\t// default all timestamps to UTC\n\t\tcel.DefaultUTCTimeZone(true),\n\n\t\t// Functions exposed to all CEL programs:\n\t\tcel.Function(\"randInt\",\n\t\t\tcel.Overload(\"randInt_int\",\n\t\t\t\t[]*cel.Type{cel.IntType},\n\t\t\t\tcel.IntType,\n\t\t\t\tcel.UnaryBinding(func(val ref.Val) ref.Val {\n\t\t\t\t\tn, ok := val.(types.Int)\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn types.ValOrErr(val, \"value is not an integer, but is %T\", val)\n\t\t\t\t\t}\n\n\t\t\t\t\treturn types.Int(rand.IntN(int(n)))\n\t\t\t\t}),\n\t\t\t),\n\t\t),\n\t}\n\n\targs = append(args, opts...)\n\treturn cel.NewEnv(args...)\n}\n\n// Compile takes CEL environment and syntax tree then emits an optimized\n// Program for execution.\nfunc Compile(env *cel.Env, src string) (cel.Program, error) {\n\tintermediate, iss := env.Compile(src)\n\tif iss != nil {\n\t\treturn nil, iss.Err()\n\t}\n\n\tast, iss := env.Check(intermediate)\n\tif iss != nil {\n\t\treturn nil, iss.Err()\n\t}\n\n\treturn env.Program(\n\t\tast,\n\t\tcel.EvalOptions(\n\t\t\t// optimize regular expressions right now instead of on the fly\n\t\t\tcel.OptOptimize,\n\t\t),\n\t)\n}\n"], ["/anubis/lib/challenge/proofofwork/proofofwork.go", "package proofofwork\n\nimport (\n\t\"crypto/subtle\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net/http\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com/TecharoHQ/anubis/internal\"\n\tchall \"github.com/TecharoHQ/anubis/lib/challenge\"\n\t\"github.com/TecharoHQ/anubis/lib/localization\"\n\t\"github.com/TecharoHQ/anubis/web\"\n\t\"github.com/a-h/templ\"\n)\n\nfunc init() {\n\tchall.Register(\"fast\", &Impl{Algorithm: \"fast\"})\n\tchall.Register(\"slow\", &Impl{Algorithm: \"slow\"})\n}\n\ntype Impl struct {\n\tAlgorithm string\n}\n\nfunc (i *Impl) Setup(mux *http.ServeMux) {\n\t/* no implementation required */\n}\n\nfunc (i *Impl) Issue(r *http.Request, lg *slog.Logger, in *chall.IssueInput) (templ.Component, error) {\n\tloc := localization.GetLocalizer(r)\n\tcomponent, err := web.BaseWithChallengeAndOGTags(loc.T(\"making_sure_not_bot\"), web.Index(loc), in.Impressum, in.Challenge.RandomData, in.Rule.Challenge, in.OGTags, loc)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't render page: %w\", err)\n\t}\n\n\treturn component, nil\n}\n\nfunc (i *Impl) Validate(r *http.Request, lg *slog.Logger, in *chall.ValidateInput) error {\n\trule := in.Rule\n\tchallenge := in.Challenge.RandomData\n\n\tnonceStr := r.FormValue(\"nonce\")\n\tif nonceStr == \"\" {\n\t\treturn chall.NewError(\"validate\", \"invalid response\", fmt.Errorf(\"%w nonce\", chall.ErrMissingField))\n\t}\n\n\tnonce, err := strconv.Atoi(nonceStr)\n\tif err != nil {\n\t\treturn chall.NewError(\"validate\", \"invalid response\", fmt.Errorf(\"%w: nonce: %w\", chall.ErrInvalidFormat, err))\n\n\t}\n\n\telapsedTimeStr := r.FormValue(\"elapsedTime\")\n\tif elapsedTimeStr == \"\" {\n\t\treturn chall.NewError(\"validate\", \"invalid response\", fmt.Errorf(\"%w elapsedTime\", chall.ErrMissingField))\n\t}\n\n\telapsedTime, err := strconv.ParseFloat(elapsedTimeStr, 64)\n\tif err != nil {\n\t\treturn chall.NewError(\"validate\", \"invalid response\", fmt.Errorf(\"%w: elapsedTime: %w\", chall.ErrInvalidFormat, err))\n\t}\n\n\tresponse := r.FormValue(\"response\")\n\tif response == \"\" {\n\t\treturn chall.NewError(\"validate\", \"invalid response\", fmt.Errorf(\"%w response\", chall.ErrMissingField))\n\t}\n\n\tcalcString := fmt.Sprintf(\"%s%d\", challenge, nonce)\n\tcalculated := internal.SHA256sum(calcString)\n\n\tif subtle.ConstantTimeCompare([]byte(response), []byte(calculated)) != 1 {\n\t\treturn chall.NewError(\"validate\", \"invalid response\", fmt.Errorf(\"%w: wanted response %s but got %s\", chall.ErrFailed, calculated, response))\n\t}\n\n\t// compare the leading zeroes\n\tif !strings.HasPrefix(response, strings.Repeat(\"0\", rule.Challenge.Difficulty)) {\n\t\treturn chall.NewError(\"validate\", \"invalid response\", fmt.Errorf(\"%w: wanted %d leading zeros but got %s\", chall.ErrFailed, rule.Challenge.Difficulty, response))\n\t}\n\n\tlg.Debug(\"challenge took\", \"elapsedTime\", elapsedTime)\n\tchall.TimeTaken.WithLabelValues(i.Algorithm).Observe(elapsedTime)\n\n\treturn nil\n}\n"], ["/anubis/lib/policy/expressions/loadavg.go", "package expressions\n\nimport (\n\t\"context\"\n\t\"log/slog\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/shirou/gopsutil/v4/load\"\n)\n\ntype loadAvg struct {\n\tlock sync.RWMutex\n\tdata *load.AvgStat\n}\n\nfunc (l *loadAvg) updateThread(ctx context.Context) {\n\tticker := time.NewTicker(15 * time.Second)\n\tdefer ticker.Stop()\n\n\tl.update()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tl.update()\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (l *loadAvg) update() {\n\tl.lock.Lock()\n\tdefer l.lock.Unlock()\n\n\tvar err error\n\tl.data, err = load.Avg()\n\tif err != nil {\n\t\tslog.Debug(\"can't get load average\", \"err\", err)\n\t}\n}\n\nvar (\n\tglobalLoadAvg *loadAvg\n)\n\nfunc init() {\n\tglobalLoadAvg = &loadAvg{}\n\tgo globalLoadAvg.updateThread(context.Background())\n}\n\nfunc Load1() float64 {\n\tglobalLoadAvg.lock.RLock()\n\tdefer globalLoadAvg.lock.RUnlock()\n\treturn globalLoadAvg.data.Load1\n}\n\nfunc Load5() float64 {\n\tglobalLoadAvg.lock.RLock()\n\tdefer globalLoadAvg.lock.RUnlock()\n\treturn globalLoadAvg.data.Load5\n}\n\nfunc Load15() float64 {\n\tglobalLoadAvg.lock.RLock()\n\tdefer globalLoadAvg.lock.RUnlock()\n\treturn globalLoadAvg.data.Load15\n}\n"], ["/anubis/lib/policy/celchecker.go", "package policy\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/TecharoHQ/anubis/internal\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/expressions\"\n\t\"github.com/google/cel-go/cel\"\n\t\"github.com/google/cel-go/common/types\"\n)\n\ntype CELChecker struct {\n\tprogram cel.Program\n\tsrc string\n}\n\nfunc NewCELChecker(cfg *config.ExpressionOrList) (*CELChecker, error) {\n\tenv, err := expressions.BotEnvironment()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tprogram, err := expressions.Compile(env, cfg.String())\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't compile CEL program: %w\", err)\n\t}\n\n\treturn &CELChecker{\n\t\tsrc: cfg.String(),\n\t\tprogram: program,\n\t}, nil\n}\n\nfunc (cc *CELChecker) Hash() string {\n\treturn internal.FastHash(cc.src)\n}\n\nfunc (cc *CELChecker) Check(r *http.Request) (bool, error) {\n\tresult, _, err := cc.program.ContextEval(r.Context(), &CELRequest{r})\n\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tif val, ok := result.(types.Bool); ok {\n\t\treturn bool(val), nil\n\t}\n\n\treturn false, nil\n}\n\ntype CELRequest struct {\n\t*http.Request\n}\n\nfunc (cr *CELRequest) Parent() cel.Activation { return nil }\n\nfunc (cr *CELRequest) ResolveName(name string) (any, bool) {\n\tswitch name {\n\tcase \"remoteAddress\":\n\t\treturn cr.Header.Get(\"X-Real-Ip\"), true\n\tcase \"host\":\n\t\treturn cr.Host, true\n\tcase \"method\":\n\t\treturn cr.Method, true\n\tcase \"userAgent\":\n\t\treturn cr.UserAgent(), true\n\tcase \"path\":\n\t\treturn cr.URL.Path, true\n\tcase \"query\":\n\t\treturn expressions.URLValues{Values: cr.URL.Query()}, true\n\tcase \"headers\":\n\t\treturn expressions.HTTPHeaders{Header: cr.Header}, true\n\tcase \"load_1m\":\n\t\treturn expressions.Load1(), true\n\tcase \"load_5m\":\n\t\treturn expressions.Load5(), true\n\tcase \"load_15m\":\n\t\treturn expressions.Load15(), true\n\tdefault:\n\t\treturn nil, false\n\t}\n}\n"], ["/anubis/lib/challenge/metarefresh/metarefresh.go", "package metarefresh\n\nimport (\n\t\"crypto/subtle\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net/http\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/TecharoHQ/anubis/lib/challenge\"\n\t\"github.com/TecharoHQ/anubis/lib/localization\"\n\t\"github.com/TecharoHQ/anubis/web\"\n\t\"github.com/a-h/templ\"\n)\n\n//go:generate go tool github.com/a-h/templ/cmd/templ generate\n\nfunc init() {\n\tchallenge.Register(\"metarefresh\", &Impl{})\n}\n\ntype Impl struct{}\n\nfunc (i *Impl) Setup(mux *http.ServeMux) {}\n\nfunc (i *Impl) Issue(r *http.Request, lg *slog.Logger, in *challenge.IssueInput) (templ.Component, error) {\n\tu, err := r.URL.Parse(anubis.BasePrefix + \"/.within.website/x/cmd/anubis/api/pass-challenge\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't render page: %w\", err)\n\t}\n\n\tq := u.Query()\n\tq.Set(\"redir\", r.URL.String())\n\tq.Set(\"challenge\", in.Challenge.RandomData)\n\tu.RawQuery = q.Encode()\n\n\tloc := localization.GetLocalizer(r)\n\tcomponent, err := web.BaseWithChallengeAndOGTags(loc.T(\"making_sure_not_bot\"), page(u.String(), in.Rule.Challenge.Difficulty, loc), in.Impressum, in.Challenge.RandomData, in.Rule.Challenge, in.OGTags, loc)\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't render page: %w\", err)\n\t}\n\n\treturn component, nil\n}\n\nfunc (i *Impl) Validate(r *http.Request, lg *slog.Logger, in *challenge.ValidateInput) error {\n\tgotChallenge := r.FormValue(\"challenge\")\n\n\tif subtle.ConstantTimeCompare([]byte(in.Challenge.RandomData), []byte(gotChallenge)) != 1 {\n\t\treturn challenge.NewError(\"validate\", \"invalid response\", fmt.Errorf(\"%w: wanted response %s but got %s\", challenge.ErrFailed, in.Challenge.RandomData, gotChallenge))\n\t}\n\n\treturn nil\n}\n"], ["/anubis/lib/policy/config/store.go", "package config\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n\t_ \"github.com/TecharoHQ/anubis/lib/store/all\"\n)\n\nvar (\n\tErrNoStoreBackend = errors.New(\"config.Store: no backend defined\")\n\tErrUnknownStoreBackend = errors.New(\"config.Store: unknown backend\")\n)\n\ntype Store struct {\n\tBackend string `json:\"backend\"`\n\tParameters json.RawMessage `json:\"parameters\"`\n}\n\nfunc (s *Store) Valid() error {\n\tvar errs []error\n\n\tif len(s.Backend) == 0 {\n\t\terrs = append(errs, ErrNoStoreBackend)\n\t}\n\n\tfac, ok := store.Get(s.Backend)\n\tswitch ok {\n\tcase true:\n\t\tif err := fac.Valid(s.Parameters); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\tcase false:\n\t\terrs = append(errs, fmt.Errorf(\"%w: %q\", ErrUnknownStoreBackend, s.Backend))\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn errors.Join(errs...)\n\t}\n\n\treturn nil\n}\n"], ["/anubis/lib/store/valkey/factory.go", "package valkey\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n\tvalkey \"github.com/redis/go-redis/v9\"\n)\n\nvar (\n\tErrNoURL = errors.New(\"valkey.Config: no URL defined\")\n\tErrBadURL = errors.New(\"valkey.Config: URL is invalid\")\n)\n\nfunc init() {\n\tstore.Register(\"valkey\", Factory{})\n}\n\ntype Factory struct{}\n\nfunc (Factory) Build(ctx context.Context, data json.RawMessage) (store.Interface, error) {\n\tvar config Config\n\n\tif err := json.Unmarshal([]byte(data), &config); err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\tif err := config.Valid(); err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\topts, err := valkey.ParseURL(config.URL)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\trdb := valkey.NewClient(opts)\n\n\tif _, err := rdb.Ping(ctx).Result(); err != nil {\n\t\treturn nil, fmt.Errorf(\"can't ping valkey instance: %w\", err)\n\t}\n\n\treturn &Store{\n\t\trdb: rdb,\n\t}, nil\n}\n\nfunc (Factory) Valid(data json.RawMessage) error {\n\tvar config Config\n\tif err := json.Unmarshal([]byte(data), &config); err != nil {\n\t\treturn fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\tif err := config.Valid(); err != nil {\n\t\treturn fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\treturn nil\n}\n\ntype Config struct {\n\tURL string `json:\"url\"`\n}\n\nfunc (c Config) Valid() error {\n\tvar errs []error\n\n\tif c.URL == \"\" {\n\t\terrs = append(errs, ErrNoURL)\n\t}\n\n\tif _, err := valkey.ParseURL(c.URL); err != nil {\n\t\terrs = append(errs, ErrBadURL)\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"valkey.Config: invalid config: %w\", errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n"], ["/anubis/internal/log.go", "package internal\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"log/slog\"\n\t\"net/http\"\n\t\"os\"\n\t\"strings\"\n)\n\nfunc InitSlog(level string) {\n\tvar programLevel slog.Level\n\tif err := (&programLevel).UnmarshalText([]byte(level)); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"invalid log level %s: %v, using info\\n\", level, err)\n\t\tprogramLevel = slog.LevelInfo\n\t}\n\n\tleveler := &slog.LevelVar{}\n\tleveler.Set(programLevel)\n\n\th := slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{\n\t\tAddSource: true,\n\t\tLevel: leveler,\n\t})\n\tslog.SetDefault(slog.New(h))\n}\n\nfunc GetRequestLogger(r *http.Request) *slog.Logger {\n\treturn slog.With(\n\t\t\"user_agent\", r.UserAgent(),\n\t\t\"accept_language\", r.Header.Get(\"Accept-Language\"),\n\t\t\"priority\", r.Header.Get(\"Priority\"),\n\t\t\"x-forwarded-for\",\n\t\tr.Header.Get(\"X-Forwarded-For\"),\n\t\t\"x-real-ip\", r.Header.Get(\"X-Real-Ip\"),\n\t)\n}\n\n// ErrorLogFilter is used to suppress \"context canceled\" logs from the http server when a request is canceled (e.g., when a client disconnects).\ntype ErrorLogFilter struct {\n\tUnwrap *log.Logger\n}\n\nfunc (elf *ErrorLogFilter) Write(p []byte) (n int, err error) {\n\tlogMessage := string(p)\n\tif strings.Contains(logMessage, \"context canceled\") {\n\t\treturn len(p), nil // Suppress the log by doing nothing\n\t}\n\tif elf.Unwrap != nil {\n\t\treturn elf.Unwrap.Writer().Write(p)\n\t}\n\treturn len(p), nil\n}\n\nfunc GetFilteredHTTPLogger() *log.Logger {\n\tstdErrLogger := log.New(os.Stderr, \"\", log.LstdFlags) // essentially what the default logger is.\n\treturn log.New(&ErrorLogFilter{Unwrap: stdErrLogger}, \"\", 0)\n}\n"], ["/anubis/decaymap/decaymap.go", "package decaymap\n\nimport (\n\t\"sync\"\n\t\"time\"\n)\n\nfunc Zilch[T any]() T {\n\tvar zero T\n\treturn zero\n}\n\n// Impl is a lazy key->value map. It's a wrapper around a map and a mutex. If values exceed their time-to-live, they are pruned at Get time.\ntype Impl[K comparable, V any] struct {\n\tdata map[K]decayMapEntry[V]\n\tlock sync.RWMutex\n}\n\ntype decayMapEntry[V any] struct {\n\tValue V\n\texpiry time.Time\n}\n\n// New creates a new DecayMap of key type K and value type V.\n//\n// Key types must be comparable to work with maps.\nfunc New[K comparable, V any]() *Impl[K, V] {\n\treturn &Impl[K, V]{\n\t\tdata: make(map[K]decayMapEntry[V]),\n\t}\n}\n\n// expire forcibly expires a key by setting its time-to-live one second in the past.\nfunc (m *Impl[K, V]) expire(key K) bool {\n\tm.lock.RLock()\n\tval, ok := m.data[key]\n\tm.lock.RUnlock()\n\n\tif !ok {\n\t\treturn false\n\t}\n\n\tm.lock.Lock()\n\tval.expiry = time.Now().Add(-1 * time.Second)\n\tm.data[key] = val\n\tm.lock.Unlock()\n\n\treturn true\n}\n\n// Delete a value from the DecayMap by key.\n//\n// If the value does not exist, return false. Return true after\n// deletion.\nfunc (m *Impl[K, V]) Delete(key K) bool {\n\tm.lock.RLock()\n\t_, ok := m.data[key]\n\tm.lock.RUnlock()\n\n\tif !ok {\n\t\treturn false\n\t}\n\n\tm.lock.Lock()\n\tdelete(m.data, key)\n\tm.lock.Unlock()\n\n\treturn true\n}\n\n// Get gets a value from the DecayMap by key.\n//\n// If a value has expired, forcibly delete it if it was not updated.\nfunc (m *Impl[K, V]) Get(key K) (V, bool) {\n\tm.lock.RLock()\n\tvalue, ok := m.data[key]\n\tm.lock.RUnlock()\n\n\tif !ok {\n\t\treturn Zilch[V](), false\n\t}\n\n\tif time.Now().After(value.expiry) {\n\t\tm.lock.Lock()\n\t\t// Since previously reading m.data[key], the value may have been updated.\n\t\t// Delete the entry only if the expiry time is still the same.\n\t\tif m.data[key].expiry.Equal(value.expiry) {\n\t\t\tdelete(m.data, key)\n\t\t}\n\t\tm.lock.Unlock()\n\n\t\treturn Zilch[V](), false\n\t}\n\n\treturn value.Value, true\n}\n\n// Set sets a key value pair in the map.\nfunc (m *Impl[K, V]) Set(key K, value V, ttl time.Duration) {\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\n\tm.data[key] = decayMapEntry[V]{\n\t\tValue: value,\n\t\texpiry: time.Now().Add(ttl),\n\t}\n}\n\n// Cleanup removes all expired entries from the DecayMap.\nfunc (m *Impl[K, V]) Cleanup() {\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\n\tnow := time.Now()\n\tfor key, entry := range m.data {\n\t\tif now.After(entry.expiry) {\n\t\t\tdelete(m.data, key)\n\t\t}\n\t}\n}\n\n// Len returns the number of entries in the DecayMap.\nfunc (m *Impl[K, V]) Len() int {\n\tm.lock.RLock()\n\tdefer m.lock.RUnlock()\n\treturn len(m.data)\n}\n"], ["/anubis/internal/hash.go", "package internal\n\nimport (\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"strconv\"\n\n\t\"github.com/cespare/xxhash/v2\"\n)\n\n// SHA256sum computes a cryptographic hash. Still used for proof-of-work challenges\n// where we need the security properties of a cryptographic hash function.\nfunc SHA256sum(text string) string {\n\thash := sha256.New()\n\thash.Write([]byte(text))\n\treturn hex.EncodeToString(hash.Sum(nil))\n}\n\n// FastHash is a high-performance non-cryptographic hash function suitable for\n// internal caching, policy rule identification, and other performance-critical\n// use cases where cryptographic security is not required.\nfunc FastHash(text string) string {\n\th := xxhash.Sum64String(text)\n\treturn strconv.FormatUint(h, 16)\n}\n"], ["/anubis/internal/ogtags/cache.go", "package ogtags\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"log/slog\"\n\t\"net/url\"\n\t\"syscall\"\n)\n\n// GetOGTags is the main function that retrieves Open Graph tags for a URL\nfunc (c *OGTagCache) GetOGTags(ctx context.Context, url *url.URL, originalHost string) (map[string]string, error) {\n\tif url == nil {\n\t\treturn nil, errors.New(\"nil URL provided, cannot fetch OG tags\")\n\t}\n\n\tif len(c.ogOverride) != 0 {\n\t\treturn c.ogOverride, nil\n\t}\n\n\ttarget := c.getTarget(url)\n\tcacheKey := c.generateCacheKey(target, originalHost)\n\n\t// Check cache first\n\tif cachedTags := c.checkCache(ctx, cacheKey); cachedTags != nil {\n\t\treturn cachedTags, nil\n\t}\n\n\t// Fetch HTML content, passing the original host\n\tdoc, err := c.fetchHTMLDocumentWithCache(ctx, target, originalHost, cacheKey)\n\tif errors.Is(err, syscall.ECONNREFUSED) {\n\t\tslog.Debug(\"Connection refused, returning empty tags\")\n\t\treturn nil, nil\n\t} else if errors.Is(err, ErrOgHandled) {\n\t\t// Error was handled in fetchHTMLDocument, return empty tags\n\t\treturn nil, nil\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Extract OG tags\n\togTags := c.extractOGTags(doc)\n\n\t// Store in cache\n\tc.cache.Set(ctx, cacheKey, ogTags, c.ogTimeToLive)\n\n\treturn ogTags, nil\n}\n\nfunc (c *OGTagCache) generateCacheKey(target string, originalHost string) string {\n\tvar cacheKey string\n\n\tif c.ogCacheConsiderHost {\n\t\tcacheKey = target + \"|\" + originalHost\n\t} else {\n\t\tcacheKey = target\n\t}\n\treturn cacheKey\n}\n\n// checkCache checks if we have the tags cached and returns them if so\nfunc (c *OGTagCache) checkCache(ctx context.Context, cacheKey string) map[string]string {\n\tif cachedTags, err := c.cache.Get(ctx, cacheKey); err == nil {\n\t\tslog.Debug(\"cache hit\", \"tags\", cachedTags)\n\t\treturn cachedTags\n\t}\n\tslog.Debug(\"cache miss\", \"url\", cacheKey)\n\treturn nil\n}\n"], ["/anubis/internal/ogtags/parse.go", "package ogtags\n\nimport (\n\t\"strings\"\n\n\t\"golang.org/x/net/html\"\n)\n\n// extractOGTags traverses the HTML document and extracts approved Open Graph tags\nfunc (c *OGTagCache) extractOGTags(doc *html.Node) map[string]string {\n\togTags := make(map[string]string)\n\n\tvar traverseNodes func(*html.Node)\n\ttraverseNodes = func(n *html.Node) {\n\t\tif isOGMetaTag(n) {\n\t\t\tproperty, content := c.extractMetaTagInfo(n)\n\t\t\tif property != \"\" {\n\t\t\t\togTags[property] = content\n\t\t\t}\n\t\t}\n\t\tfor child := n.FirstChild; child != nil; child = child.NextSibling {\n\t\t\ttraverseNodes(child)\n\t\t}\n\t}\n\n\ttraverseNodes(doc)\n\treturn ogTags\n}\n\n// isOGMetaTag checks if a node is *any* meta tag\nfunc isOGMetaTag(n *html.Node) bool {\n\tif n == nil {\n\t\treturn false\n\t}\n\treturn n.Type == html.ElementNode && n.Data == \"meta\"\n}\n\n// extractMetaTagInfo extracts property and content from a meta tag\nfunc (c *OGTagCache) extractMetaTagInfo(n *html.Node) (property, content string) {\n\tvar propertyKey string\n\n\t// Single pass through attributes, using range to avoid bounds checking\n\tfor _, attr := range n.Attr {\n\t\tswitch attr.Key {\n\t\tcase \"property\", \"name\":\n\t\t\tpropertyKey = attr.Val\n\t\tcase \"content\":\n\t\t\tcontent = attr.Val\n\t\t}\n\t\t// Early exit if we have both\n\t\tif propertyKey != \"\" && content != \"\" {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif propertyKey == \"\" {\n\t\treturn \"\", content\n\t}\n\n\t// Check prefixes first (more common case)\n\tfor _, prefix := range c.approvedPrefixes {\n\t\tif strings.HasPrefix(propertyKey, prefix) {\n\t\t\treturn propertyKey, content\n\t\t}\n\t}\n\n\t// Check exact matches\n\tfor _, tag := range c.approvedTags {\n\t\tif propertyKey == tag {\n\t\t\treturn propertyKey, content\n\t\t}\n\t}\n\n\treturn \"\", content\n}\n"], ["/anubis/lib/store/interface.go", "package store\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"time\"\n)\n\nvar (\n\t// ErrNotFound is returned when the store implementation cannot find the value\n\t// for a given key.\n\tErrNotFound = errors.New(\"store: key not found\")\n\n\t// ErrCantDecode is returned when a store adaptor cannot decode the store format\n\t// to a value used by the code.\n\tErrCantDecode = errors.New(\"store: can't decode value\")\n\n\t// ErrCantEncode is returned when a store adaptor cannot encode the value into\n\t// the format that the store uses.\n\tErrCantEncode = errors.New(\"store: can't encode value\")\n\n\t// ErrBadConfig is returned when a store adaptor's configuration is invalid.\n\tErrBadConfig = errors.New(\"store: configuration is invalid\")\n)\n\n// Interface defines the calls that Anubis uses for storage in a local or remote\n// datastore. This can be implemented with an in-memory, on-disk, or in-database\n// storage backend.\ntype Interface interface {\n\t// Delete removes a value from the store by key.\n\tDelete(ctx context.Context, key string) error\n\n\t// Get returns the value of a key assuming that value exists and has not expired.\n\tGet(ctx context.Context, key string) ([]byte, error)\n\n\t// Set puts a value into the store that expires according to its expiry.\n\tSet(ctx context.Context, key string, value []byte, expiry time.Duration) error\n}\n\nfunc z[T any]() T { return *new(T) }\n\ntype JSON[T any] struct {\n\tUnderlying Interface\n\tPrefix string\n}\n\nfunc (j *JSON[T]) Delete(ctx context.Context, key string) error {\n\tif j.Prefix != \"\" {\n\t\tkey = j.Prefix + key\n\t}\n\n\treturn j.Underlying.Delete(ctx, key)\n}\n\nfunc (j *JSON[T]) Get(ctx context.Context, key string) (T, error) {\n\tif j.Prefix != \"\" {\n\t\tkey = j.Prefix + key\n\t}\n\n\tdata, err := j.Underlying.Get(ctx, key)\n\tif err != nil {\n\t\treturn z[T](), err\n\t}\n\n\tvar result T\n\tif err := json.Unmarshal(data, &result); err != nil {\n\t\treturn z[T](), fmt.Errorf(\"%w: %w\", ErrCantDecode, err)\n\t}\n\n\treturn result, nil\n}\n\nfunc (j *JSON[T]) Set(ctx context.Context, key string, value T, expiry time.Duration) error {\n\tif j.Prefix != \"\" {\n\t\tkey = j.Prefix + key\n\t}\n\n\tdata, err := json.Marshal(value)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%w: %w\", ErrCantEncode, err)\n\t}\n\n\tif err := j.Underlying.Set(ctx, key, data, expiry); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n"], ["/anubis/lib/policy/expressions/url_values.go", "package expressions\n\nimport (\n\t\"errors\"\n\t\"net/url\"\n\t\"reflect\"\n\t\"strings\"\n\n\t\"github.com/google/cel-go/common/types\"\n\t\"github.com/google/cel-go/common/types/ref\"\n\t\"github.com/google/cel-go/common/types/traits\"\n)\n\nvar ErrNotImplemented = errors.New(\"expressions: not implemented\")\n\n// URLValues is a type wrapper to expose url.Values into CEL programs.\ntype URLValues struct {\n\turl.Values\n}\n\nfunc (u URLValues) ConvertToNative(typeDesc reflect.Type) (any, error) {\n\treturn nil, ErrNotImplemented\n}\n\nfunc (u URLValues) ConvertToType(typeVal ref.Type) ref.Val {\n\tswitch typeVal {\n\tcase types.MapType:\n\t\treturn u\n\tcase types.TypeType:\n\t\treturn types.MapType\n\t}\n\n\treturn types.NewErr(\"can't convert from %q to %q\", types.MapType, typeVal)\n}\n\nfunc (u URLValues) Equal(other ref.Val) ref.Val {\n\treturn types.Bool(false) // We don't want to compare header maps\n}\n\nfunc (u URLValues) Type() ref.Type {\n\treturn types.MapType\n}\n\nfunc (u URLValues) Value() any { return u }\n\nfunc (u URLValues) Find(key ref.Val) (ref.Val, bool) {\n\tk, ok := key.(types.String)\n\tif !ok {\n\t\treturn nil, false\n\t}\n\n\tif _, ok := u.Values[string(k)]; !ok {\n\t\treturn nil, false\n\t}\n\n\treturn types.String(strings.Join(u.Values[string(k)], \",\")), true\n}\n\nfunc (u URLValues) Contains(key ref.Val) ref.Val {\n\t_, ok := u.Find(key)\n\treturn types.Bool(ok)\n}\n\nfunc (u URLValues) Get(key ref.Val) ref.Val {\n\tresult, ok := u.Find(key)\n\tif !ok {\n\t\treturn types.ValOrErr(result, \"no such key: %v\", key)\n\t}\n\treturn result\n}\n\nfunc (u URLValues) Iterator() traits.Iterator { panic(\"TODO(Xe): implement me\") }\n\nfunc (u URLValues) IsZeroValue() bool {\n\treturn len(u.Values) == 0\n}\n\nfunc (u URLValues) Size() ref.Val { return types.Int(len(u.Values)) }\n"], ["/anubis/lib/policy/checker/checker.go", "// Package checker defines the Checker interface and a helper utility to avoid import cycles.\npackage checker\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"strings\"\n\n\t\"github.com/TecharoHQ/anubis/internal\"\n)\n\ntype Impl interface {\n\tCheck(*http.Request) (bool, error)\n\tHash() string\n}\n\ntype List []Impl\n\nfunc (l List) Check(r *http.Request) (bool, error) {\n\tfor _, c := range l {\n\t\tok, err := c.Check(r)\n\t\tif err != nil {\n\t\t\treturn ok, err\n\t\t}\n\t\tif ok {\n\t\t\treturn ok, nil\n\t\t}\n\t}\n\n\treturn false, nil\n}\n\nfunc (l List) Hash() string {\n\tvar sb strings.Builder\n\n\tfor _, c := range l {\n\t\tfmt.Fprintln(&sb, c.Hash())\n\t}\n\n\treturn internal.FastHash(sb.String())\n}\n"], ["/anubis/lib/store/valkey/valkey.go", "package valkey\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n\tvalkey \"github.com/redis/go-redis/v9\"\n)\n\ntype Store struct {\n\trdb *valkey.Client\n}\n\nfunc (s *Store) Delete(ctx context.Context, key string) error {\n\tn, err := s.rdb.Del(ctx, key).Result()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"can't delete from valkey: %w\", err)\n\t}\n\n\tswitch n {\n\tcase 0:\n\t\treturn fmt.Errorf(\"%w: %d key(s) deleted\", store.ErrNotFound, n)\n\tdefault:\n\t\treturn nil\n\t}\n}\n\nfunc (s *Store) Get(ctx context.Context, key string) ([]byte, error) {\n\tresult, err := s.rdb.Get(ctx, key).Result()\n\tif err != nil {\n\t\tif valkey.HasErrorPrefix(err, \"redis: nil\") {\n\t\t\treturn nil, fmt.Errorf(\"%w: %w\", store.ErrNotFound, err)\n\t\t}\n\n\t\treturn nil, fmt.Errorf(\"can't fetch from valkey: %w\", err)\n\t}\n\n\treturn []byte(result), nil\n}\n\nfunc (s *Store) Set(ctx context.Context, key string, value []byte, expiry time.Duration) error {\n\tif _, err := s.rdb.Set(ctx, key, string(value), expiry).Result(); err != nil {\n\t\treturn fmt.Errorf(\"can't set %q in valkey: %w\", key, err)\n\t}\n\n\treturn nil\n}\n"], ["/anubis/lib/challenge/interface.go", "package challenge\n\nimport (\n\t\"log/slog\"\n\t\"net/http\"\n\t\"sort\"\n\t\"sync\"\n\n\t\"github.com/TecharoHQ/anubis/lib/policy\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n\t\"github.com/a-h/templ\"\n)\n\nvar (\n\tregistry map[string]Impl = map[string]Impl{}\n\tregLock sync.RWMutex\n)\n\nfunc Register(name string, impl Impl) {\n\tregLock.Lock()\n\tdefer regLock.Unlock()\n\n\tregistry[name] = impl\n}\n\nfunc Get(name string) (Impl, bool) {\n\tregLock.RLock()\n\tdefer regLock.RUnlock()\n\tresult, ok := registry[name]\n\treturn result, ok\n}\n\nfunc Methods() []string {\n\tregLock.RLock()\n\tdefer regLock.RUnlock()\n\tvar result []string\n\tfor method := range registry {\n\t\tresult = append(result, method)\n\t}\n\tsort.Strings(result)\n\treturn result\n}\n\ntype IssueInput struct {\n\tImpressum *config.Impressum\n\tRule *policy.Bot\n\tChallenge *Challenge\n\tOGTags map[string]string\n\tStore store.Interface\n}\n\ntype ValidateInput struct {\n\tRule *policy.Bot\n\tChallenge *Challenge\n\tStore store.Interface\n}\n\ntype Impl interface {\n\t// Setup registers any additional routes with the Impl for assets or API routes.\n\tSetup(mux *http.ServeMux)\n\n\t// Issue a new challenge to the user, called by the Anubis.\n\tIssue(r *http.Request, lg *slog.Logger, in *IssueInput) (templ.Component, error)\n\n\t// Validate a challenge, making sure that it passes muster.\n\tValidate(r *http.Request, lg *slog.Logger, in *ValidateInput) error\n}\n"], ["/anubis/lib/store/memory/memory.go", "package memory\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis/decaymap\"\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n)\n\ntype factory struct{}\n\nfunc (factory) Build(ctx context.Context, _ json.RawMessage) (store.Interface, error) {\n\treturn New(ctx), nil\n}\n\nfunc (factory) Valid(json.RawMessage) error { return nil }\n\nfunc init() {\n\tstore.Register(\"memory\", factory{})\n}\n\ntype impl struct {\n\tstore *decaymap.Impl[string, []byte]\n}\n\nfunc (i *impl) Delete(_ context.Context, key string) error {\n\tif !i.store.Delete(key) {\n\t\treturn fmt.Errorf(\"%w: %q\", store.ErrNotFound, key)\n\t}\n\n\treturn nil\n}\n\nfunc (i *impl) Get(_ context.Context, key string) ([]byte, error) {\n\tresult, ok := i.store.Get(key)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"%w: %q\", store.ErrNotFound, key)\n\t}\n\n\treturn result, nil\n}\n\nfunc (i *impl) Set(_ context.Context, key string, value []byte, expiry time.Duration) error {\n\ti.store.Set(key, value, expiry)\n\treturn nil\n}\n\nfunc (i *impl) cleanupThread(ctx context.Context) {\n\tt := time.NewTicker(5 * time.Minute)\n\tdefer t.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase <-t.C:\n\t\t\ti.store.Cleanup()\n\t\t}\n\t}\n}\n\n// New creates a simple in-memory store. This will not scale to multiple Anubis instances.\nfunc New(ctx context.Context) store.Interface {\n\tresult := &impl{\n\t\tstore: decaymap.New[string, []byte](),\n\t}\n\n\tgo result.cleanupThread(ctx)\n\n\treturn result\n}\n"], ["/anubis/lib/challenge/error.go", "package challenge\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net/http\"\n)\n\nvar (\n\tErrFailed = errors.New(\"challenge: user failed challenge\")\n\tErrMissingField = errors.New(\"challenge: missing field\")\n\tErrInvalidFormat = errors.New(\"challenge: field has invalid format\")\n)\n\nfunc NewError(verb, publicReason string, privateReason error) *Error {\n\treturn &Error{\n\t\tVerb: verb,\n\t\tPublicReason: publicReason,\n\t\tPrivateReason: privateReason,\n\t\tStatusCode: http.StatusForbidden,\n\t}\n}\n\ntype Error struct {\n\tPrivateReason error\n\tVerb string\n\tPublicReason string\n\tStatusCode int\n}\n\nfunc (e *Error) Error() string {\n\treturn fmt.Sprintf(\"challenge: error when processing challenge: %s: %v\", e.Verb, e.PrivateReason)\n}\n\nfunc (e *Error) Unwrap() error {\n\treturn e.PrivateReason\n}\n"], ["/anubis/anubis.go", "// Package anubis contains the version number of Anubis.\npackage anubis\n\nimport \"time\"\n\n// Version is the current version of Anubis.\n//\n// This variable is set at build time using the -X linker flag. If not set,\n// it defaults to \"devel\".\nvar Version = \"devel\"\n\n// CookieName is the name of the cookie that Anubis uses in order to validate\n// access.\nvar CookieName = \"techaro.lol-anubis-auth\"\n\n// TestCookieName is the name of the cookie that Anubis uses in order to check\n// if cookies are enabled on the client's browser.\nvar TestCookieName = \"techaro.lol-anubis-cookie-verification\"\n\n// CookieDefaultExpirationTime is the amount of time before the cookie/JWT expires.\nconst CookieDefaultExpirationTime = 7 * 24 * time.Hour\n\n// BasePrefix is a global prefix for all Anubis endpoints. Can be emptied to remove the prefix entirely.\nvar BasePrefix = \"\"\n\n// StaticPath is the location where all static Anubis assets are located.\nconst StaticPath = \"/.within.website/x/cmd/anubis/\"\n\n// APIPrefix is the location where all Anubis API endpoints are located.\nconst APIPrefix = \"/.within.website/x/cmd/anubis/api/\"\n\n// DefaultDifficulty is the default \"difficulty\" (number of leading zeroes)\n// that must be met by the client in order to pass the challenge.\nconst DefaultDifficulty = 4\n\n// ForcedLanguage is the language being used instead of the one of the request's Accept-Language header\n// if being set.\nvar ForcedLanguage = \"\"\n"], ["/anubis/lib/policy/expressions/http_headers.go", "package expressions\n\nimport (\n\t\"net/http\"\n\t\"reflect\"\n\t\"strings\"\n\n\t\"github.com/google/cel-go/common/types\"\n\t\"github.com/google/cel-go/common/types/ref\"\n\t\"github.com/google/cel-go/common/types/traits\"\n)\n\n// HTTPHeaders is a type wrapper to expose HTTP headers into CEL programs.\ntype HTTPHeaders struct {\n\thttp.Header\n}\n\nfunc (h HTTPHeaders) ConvertToNative(typeDesc reflect.Type) (any, error) {\n\treturn nil, ErrNotImplemented\n}\n\nfunc (h HTTPHeaders) ConvertToType(typeVal ref.Type) ref.Val {\n\tswitch typeVal {\n\tcase types.MapType:\n\t\treturn h\n\tcase types.TypeType:\n\t\treturn types.MapType\n\t}\n\n\treturn types.NewErr(\"can't convert from %q to %q\", types.MapType, typeVal)\n}\n\nfunc (h HTTPHeaders) Equal(other ref.Val) ref.Val {\n\treturn types.Bool(false) // We don't want to compare header maps\n}\n\nfunc (h HTTPHeaders) Type() ref.Type {\n\treturn types.MapType\n}\n\nfunc (h HTTPHeaders) Value() any { return h }\n\nfunc (h HTTPHeaders) Find(key ref.Val) (ref.Val, bool) {\n\tk, ok := key.(types.String)\n\tif !ok {\n\t\treturn nil, false\n\t}\n\n\tif _, ok := h.Header[string(k)]; !ok {\n\t\treturn nil, false\n\t}\n\n\treturn types.String(strings.Join(h.Header.Values(string(k)), \",\")), true\n}\n\nfunc (h HTTPHeaders) Contains(key ref.Val) ref.Val {\n\t_, ok := h.Find(key)\n\treturn types.Bool(ok)\n}\n\nfunc (h HTTPHeaders) Get(key ref.Val) ref.Val {\n\tresult, ok := h.Find(key)\n\tif !ok {\n\t\treturn types.ValOrErr(result, \"no such key: %v\", key)\n\t}\n\treturn result\n}\n\nfunc (h HTTPHeaders) Iterator() traits.Iterator { panic(\"TODO(Xe): implement me\") }\n\nfunc (h HTTPHeaders) IsZeroValue() bool {\n\treturn len(h.Header) == 0\n}\n\nfunc (h HTTPHeaders) Size() ref.Val { return types.Int(len(h.Header)) }\n"], ["/anubis/lib/store/registry.go", "package store\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"sort\"\n\t\"sync\"\n)\n\nvar (\n\tregistry map[string]Factory = map[string]Factory{}\n\tregLock sync.RWMutex\n)\n\ntype Factory interface {\n\tBuild(ctx context.Context, config json.RawMessage) (Interface, error)\n\tValid(config json.RawMessage) error\n}\n\nfunc Register(name string, impl Factory) {\n\tregLock.Lock()\n\tdefer regLock.Unlock()\n\n\tregistry[name] = impl\n}\n\nfunc Get(name string) (Factory, bool) {\n\tregLock.RLock()\n\tdefer regLock.RUnlock()\n\tresult, ok := registry[name]\n\treturn result, ok\n}\n\nfunc Methods() []string {\n\tregLock.RLock()\n\tdefer regLock.RUnlock()\n\tvar result []string\n\tfor method := range registry {\n\t\tresult = append(result, method)\n\t}\n\tsort.Strings(result)\n\treturn result\n}\n"], ["/anubis/xess/xess.go", "// Package xess vendors a copy of Xess and makes it available at /.xess/xess.css\n//\n// This is intended to be used as a vendored package in other projects.\npackage xess\n\nimport (\n\t\"embed\"\n\t\"net/http\"\n\t\"path/filepath\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/TecharoHQ/anubis/internal\"\n)\n\nvar (\n\t//go:embed *.css static\n\tStatic embed.FS\n\n\tURL = \"/.within.website/x/xess/xess.css\"\n)\n\nfunc init() {\n\tMount(http.DefaultServeMux)\n\n\t//goland:noinspection GoBoolExpressions\n\tif anubis.Version != \"devel\" {\n\t\tURL = filepath.Join(filepath.Dir(URL), \"xess.min.css\")\n\t}\n\n\tURL = URL + \"?cachebuster=\" + anubis.Version\n}\n\n// Mount registers the xess static file handlers on the given mux\nfunc Mount(mux *http.ServeMux) {\n\tprefix := anubis.BasePrefix + \"/.within.website/x/xess/\"\n\n\tmux.Handle(prefix, internal.UnchangingCache(http.StripPrefix(prefix, http.FileServerFS(Static))))\n}\n"], ["/anubis/lib/challenge/metrics.go", "package challenge\n\nimport (\n\t\"math\"\n\n\t\"github.com/prometheus/client_golang/prometheus\"\n\t\"github.com/prometheus/client_golang/prometheus/promauto\"\n)\n\nvar TimeTaken = promauto.NewHistogramVec(prometheus.HistogramOpts{\n\tName: \"anubis_time_taken\",\n\tHelp: \"The time taken for a browser to generate a response (milliseconds)\",\n\tBuckets: prometheus.ExponentialBucketsRange(1, math.Pow(2, 20), 20),\n}, []string{\"method\"})\n"], ["/anubis/lib/policy/thresholds.go", "package policy\n\nimport (\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/expressions\"\n\t\"github.com/google/cel-go/cel\"\n)\n\ntype Threshold struct {\n\tconfig.Threshold\n\tProgram cel.Program\n}\n\nfunc ParsedThresholdFromConfig(t config.Threshold) (*Threshold, error) {\n\tresult := &Threshold{\n\t\tThreshold: t,\n\t}\n\n\tenv, err := expressions.ThresholdEnvironment()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tprogram, err := expressions.Compile(env, t.Expression.String())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult.Program = program\n\n\treturn result, nil\n}\n\ntype ThresholdRequest struct {\n\tWeight int\n}\n\nfunc (tr *ThresholdRequest) Parent() cel.Activation { return nil }\n\nfunc (tr *ThresholdRequest) ResolveName(name string) (any, bool) {\n\tswitch name {\n\tcase \"weight\":\n\t\treturn tr.Weight, true\n\tdefault:\n\t\treturn nil, false\n\t}\n}\n"], ["/anubis/lib/thoth/auth.go", "package thoth\n\nimport (\n\t\"context\"\n\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/metadata\"\n)\n\nfunc authUnaryClientInterceptor(token string) grpc.UnaryClientInterceptor {\n\treturn func(\n\t\tctx context.Context,\n\t\tmethod string,\n\t\treq interface{},\n\t\treply interface{},\n\t\tcc *grpc.ClientConn,\n\t\tinvoker grpc.UnaryInvoker,\n\t\topts ...grpc.CallOption,\n\t) error {\n\t\tmd := metadata.Pairs(\"authorization\", \"Bearer \"+token)\n\t\tctx = metadata.NewOutgoingContext(ctx, md)\n\t\treturn invoker(ctx, method, req, reply, cc, opts...)\n\t}\n}\n\nfunc authStreamClientInterceptor(token string) grpc.StreamClientInterceptor {\n\treturn func(\n\t\tctx context.Context,\n\t\tdesc *grpc.StreamDesc,\n\t\tcc *grpc.ClientConn,\n\t\tmethod string,\n\t\tstreamer grpc.Streamer,\n\t\topts ...grpc.CallOption,\n\t) (grpc.ClientStream, error) {\n\t\tmd := metadata.Pairs(\"authorization\", \"Bearer \"+token)\n\t\tctx = metadata.NewOutgoingContext(ctx, md)\n\t\treturn streamer(ctx, desc, cc, method, opts...)\n\t}\n}\n"], ["/anubis/lib/policy/bot.go", "package policy\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/TecharoHQ/anubis/internal\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/checker\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n)\n\ntype Bot struct {\n\tRules checker.Impl\n\tChallenge *config.ChallengeRules\n\tWeight *config.Weight\n\tName string\n\tAction config.Rule\n}\n\nfunc (b Bot) Hash() string {\n\treturn internal.FastHash(fmt.Sprintf(\"%s::%s\", b.Name, b.Rules.Hash()))\n}\n"], ["/anubis/internal/ja4h.go", "package internal\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/lum8rjack/go-ja4h\"\n)\n\nfunc JA4H(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tr.Header.Add(\"X-Http-Fingerprint-JA4H\", ja4h.JA4H(r))\n\t\tnext.ServeHTTP(w, r)\n\t})\n}\n"], ["/anubis/lib/policy/checkresult.go", "package policy\n\nimport (\n\t\"log/slog\"\n\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n)\n\ntype CheckResult struct {\n\tName string\n\tRule config.Rule\n\tWeight int\n}\n\nfunc (cr CheckResult) LogValue() slog.Value {\n\treturn slog.GroupValue(\n\t\tslog.String(\"name\", cr.Name),\n\t\tslog.String(\"rule\", string(cr.Rule)),\n\t\tslog.Int(\"weight\", cr.Weight),\n\t)\n}\n"], ["/anubis/lib/thoth/thothmock/withthothmock.go", "package thothmock\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/TecharoHQ/anubis/lib/thoth\"\n)\n\nfunc WithMockThoth(t *testing.T) context.Context {\n\tt.Helper()\n\n\tthothCli := &thoth.Client{}\n\tthothCli.WithIPToASNService(MockIpToASNService())\n\tctx := thoth.With(t.Context(), thothCli)\n\treturn ctx\n}\n"], ["/anubis/web/embed.go", "package web\n\nimport \"embed\"\n\n//go:generate go tool github.com/a-h/templ/cmd/templ generate\n\nvar (\n\t//go:embed static\n\tStatic embed.FS\n)\n"], ["/anubis/web/index.go", "package web\n\nimport (\n\t\"github.com/a-h/templ\"\n\n\t\"github.com/TecharoHQ/anubis/lib/localization\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n)\n\nfunc Base(title string, body templ.Component, impressum *config.Impressum, localizer *localization.SimpleLocalizer) templ.Component {\n\treturn base(title, body, impressum, nil, nil, localizer)\n}\n\nfunc BaseWithChallengeAndOGTags(title string, body templ.Component, impressum *config.Impressum, challenge string, rules *config.ChallengeRules, ogTags map[string]string, localizer *localization.SimpleLocalizer) (templ.Component, error) {\n\treturn base(title, body, impressum, struct {\n\t\tRules *config.ChallengeRules `json:\"rules\"`\n\t\tChallenge string `json:\"challenge\"`\n\t}{\n\t\tChallenge: challenge,\n\t\tRules: rules,\n\t}, ogTags, localizer), nil\n}\n\nfunc Index(localizer *localization.SimpleLocalizer) templ.Component {\n\treturn index(localizer)\n}\n\nfunc ErrorPage(msg, mail string, localizer *localization.SimpleLocalizer) templ.Component {\n\treturn errorPage(msg, mail, localizer)\n}\n\nfunc Bench(localizer *localization.SimpleLocalizer) templ.Component {\n\treturn bench(localizer)\n}\n"], ["/anubis/internal/unbreakdocker.go", "package internal\n\nimport (\n\t\"os\"\n\t\"os/exec\"\n)\n\nfunc UnbreakDocker() {\n\t// XXX(Xe): This is bad code. Do not do this.\n\t//\n\t// I have to do this because I'm running from inside the context of a dev\n\t// container. This dev container runs in a different docker network than\n\t// the valkey test container runs in. In order to let my dev container\n\t// connect to the test container, they need to share a network in common.\n\t// The easiest network to use for this is the default \"bridge\" network.\n\t//\n\t// This is a horrifying monstrosity, but the part that scares me the most\n\t// is the fact that it works.\n\tif hostname, err := os.Hostname(); err == nil {\n\t\texec.Command(\"docker\", \"network\", \"connect\", \"bridge\", hostname).Run()\n\t}\n}\n"], ["/anubis/lib/challenge/challenge.go", "package challenge\n\nimport \"time\"\n\n// Challenge is the metadata about a single challenge issuance.\ntype Challenge struct {\n\tID string `json:\"id\"` // UUID identifying the challenge\n\tRandomData string `json:\"randomData\"` // The random data the client processes\n\tIssuedAt time.Time `json:\"issuedAt\"` // When the challenge was issued\n\tMetadata map[string]string `json:\"metadata\"` // Challenge metadata such as IP address and user agent\n}\n"], ["/anubis/data/embed.go", "package data\n\nimport \"embed\"\n\nvar (\n\t//go:embed botPolicies.yaml botPolicies.json all:apps all:bots all:clients all:common all:crawlers all:meta\n\tBotPolicies embed.FS\n)\n"], ["/anubis/lib/thoth/context.go", "package thoth\n\nimport \"context\"\n\ntype ctxKey struct{}\n\nfunc With(ctx context.Context, cli *Client) context.Context {\n\treturn context.WithValue(ctx, ctxKey{}, cli)\n}\n\nfunc FromContext(ctx context.Context) (*Client, bool) {\n\tcli, ok := ctx.Value(ctxKey{}).(*Client)\n\treturn cli, ok\n}\n"], ["/anubis/lib/store/all/all.go", "// Package all is a meta-package that imports all store implementations.\n//\n// This is a HACK to make tests work consistently.\npackage all\n\nimport (\n\t_ \"github.com/TecharoHQ/anubis/lib/store/bbolt\"\n\t_ \"github.com/TecharoHQ/anubis/lib/store/memory\"\n\t_ \"github.com/TecharoHQ/anubis/lib/store/valkey\"\n)\n"], ["/anubis/lib/policy/config/weight.go", "package config\n\ntype Weight struct {\n\tAdjust int `json:\"adjust\" yaml:\"adjust\"`\n}\n"], ["/anubis/internal/mimetype.go", "package internal\n\nimport \"mime\"\n\nfunc init() {\n\tmime.AddExtensionType(\".mjs\", \"text/javascript\")\n}\n"]], "task_instance_info": {"created_time": "2025-08-20 20:50:29", "created_task_model": "DeepSeek-R1", "function_skeleton": "func reverse6 (ip net.IP) string {}", "code_description": "This code segment functions to: Reverse the byte order of an IPv6 address for DNS query formatting and convert each byte into two hexadecimal nibbles separated by periods."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```go\n[TASK_BEGIN]\nfunc reverse6(ip net.IP) string {\n\tipv6 := ip.To16()\n\tvar segments [8]string\n\t\n\t// Split into eight 2-byte segments and format each as 4 hex digits\n\tfor i := 0; i < 8; i++ {\n\t\tsegments[i] = fmt.Sprintf(\"%02x%02x\", ipv6[i*2], ipv6[i*2+1])\n\t}\n\t\n\t// Combine into single string and reverse characters\n\tfull := strings.Join(segments[:], \"\")\n\trunes := []rune(full)\n\tfor i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {\n\t\trunes[i], runes[j] = runes[j], runes[i]\n\t}\n\t\n\t// Insert dots between each character\n\treturn strings.Join(strings.Split(string(runes), \"\"), \".\")\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 20-51-49"}, "editdistance_info": {"edit_distance": 19.5946, "calculate_time": "2025-08-20 20:51:49", "true_code_clean": "func reverse6(ip net.IP) string {\n\tipBytes := []byte(ip)\n\tvar sb strings.Builder\n\tfor i := len(ipBytes) - 1; i >= 0; i-- {\n\t\thighNibble := ipBytes[i] >> 4\n\t\tlowNibble := ipBytes[i] & 0x0F\n\t\tsb.WriteString(fmt.Sprintf(\"%x.%x.\", lowNibble, highNibble))\n\t}\n\treturn sb.String()[:len(sb.String())-1]\n}", "predict_code_clean": "func reverse6(ip net.IP) string {\n\tipv6 := ip.To16()\n\tvar segments [8]string\n\tfor i := 0; i < 8; i++ {\n\t\tsegments[i] = fmt.Sprintf(\"%02x%02x\", ipv6[i*2], ipv6[i*2+1])\n\t}\n\tfull := strings.Join(segments[:], \"\")\n\trunes := []rune(full)\n\tfor i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {\n\t\trunes[i], runes[j] = runes[j], runes[i]\n\t}\n\treturn strings.Join(strings.Split(string(runes), \"\"), \".\")\n}"}} {"repo_name": "anubis", "file_name": "/anubis/internal/ogtags/fetch.go", "inference_info": {"prefix_code": "package ogtags\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log/slog\"\n\t\"mime\"\n\t\"net\"\n\t\"net/http\"\n\n\t\"golang.org/x/net/html\"\n)\n\nvar (\n\tErrOgHandled = errors.New(\"og: handled error\") // used to indicate that the error was handled and should not be logged\n\temptyMap = map[string]string{} // used to indicate an empty result in the cache. Can't use nil as it would be a cache miss.\n)\n\n// fetchHTMLDocumentWithCache fetches the HTML document from the given URL string,\n// preserving the original host header.\n", "suffix_code": "\n", "middle_code": "func (c *OGTagCache) fetchHTMLDocumentWithCache(ctx context.Context, urlStr string, originalHost string, cacheKey string) (*html.Node, error) {\n\treq, err := http.NewRequestWithContext(ctx, \"GET\", urlStr, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create http request: %w\", err)\n\t}\n\tif originalHost != \"\" {\n\t\treq.Host = originalHost\n\t}\n\treq.Header.Set(\"X-Forwarded-Proto\", \"https\")\n\treq.Header.Set(\"User-Agent\", \"Anubis-OGTag-Fetcher/1.0\") \n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\tvar netErr net.Error\n\t\tif errors.As(err, &netErr) && netErr.Timeout() {\n\t\t\tslog.Debug(\"og: request timed out\", \"url\", urlStr)\n\t\t\tc.cache.Set(ctx, cacheKey, emptyMap, c.ogTimeToLive/2) \n\t\t}\n\t\treturn nil, fmt.Errorf(\"http get failed: %w\", err)\n\t}\n\tdefer func(Body io.ReadCloser) {\n\t\terr := Body.Close()\n\t\tif err != nil {\n\t\t\tslog.Debug(\"og: error closing response body\", \"url\", urlStr, \"error\", err)\n\t\t}\n\t}(resp.Body)\n\tif resp.StatusCode != http.StatusOK {\n\t\tslog.Debug(\"og: received non-OK status code\", \"url\", urlStr, \"status\", resp.StatusCode)\n\t\tc.cache.Set(ctx, cacheKey, emptyMap, c.ogTimeToLive) \n\t\treturn nil, fmt.Errorf(\"%w: page not found\", ErrOgHandled)\n\t}\n\tct := resp.Header.Get(\"Content-Type\")\n\tif ct == \"\" {\n\t\treturn nil, fmt.Errorf(\"missing Content-Type header\")\n\t} else {\n\t\tmediaType, _, err := mime.ParseMediaType(ct)\n\t\tif err != nil {\n\t\t\tslog.Debug(\"og: malformed Content-Type header\", \"url\", urlStr, \"contentType\", ct)\n\t\t\treturn nil, fmt.Errorf(\"%w malformed Content-Type header: %w\", ErrOgHandled, err)\n\t\t}\n\t\tif mediaType != \"text/html\" && mediaType != \"application/xhtml+xml\" {\n\t\t\tslog.Debug(\"og: unsupported Content-Type\", \"url\", urlStr, \"contentType\", mediaType)\n\t\t\treturn nil, fmt.Errorf(\"%w unsupported Content-Type: %s\", ErrOgHandled, mediaType)\n\t\t}\n\t}\n\tresp.Body = http.MaxBytesReader(nil, resp.Body, maxContentLength)\n\tdoc, err := html.Parse(resp.Body)\n\tif err != nil {\n\t\tvar maxBytesErr *http.MaxBytesError\n\t\tif errors.As(err, &maxBytesErr) {\n\t\t\tslog.Debug(\"og: content exceeded max length\", \"url\", urlStr, \"limit\", maxContentLength)\n\t\t\treturn nil, fmt.Errorf(\"content too large: exceeded %d bytes\", maxContentLength)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"failed to parse HTML: %w\", err)\n\t}\n\treturn doc, nil\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "go", "sub_task_type": null}, "context_code": [["/anubis/internal/ogtags/cache.go", "package ogtags\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"log/slog\"\n\t\"net/url\"\n\t\"syscall\"\n)\n\n// GetOGTags is the main function that retrieves Open Graph tags for a URL\nfunc (c *OGTagCache) GetOGTags(ctx context.Context, url *url.URL, originalHost string) (map[string]string, error) {\n\tif url == nil {\n\t\treturn nil, errors.New(\"nil URL provided, cannot fetch OG tags\")\n\t}\n\n\tif len(c.ogOverride) != 0 {\n\t\treturn c.ogOverride, nil\n\t}\n\n\ttarget := c.getTarget(url)\n\tcacheKey := c.generateCacheKey(target, originalHost)\n\n\t// Check cache first\n\tif cachedTags := c.checkCache(ctx, cacheKey); cachedTags != nil {\n\t\treturn cachedTags, nil\n\t}\n\n\t// Fetch HTML content, passing the original host\n\tdoc, err := c.fetchHTMLDocumentWithCache(ctx, target, originalHost, cacheKey)\n\tif errors.Is(err, syscall.ECONNREFUSED) {\n\t\tslog.Debug(\"Connection refused, returning empty tags\")\n\t\treturn nil, nil\n\t} else if errors.Is(err, ErrOgHandled) {\n\t\t// Error was handled in fetchHTMLDocument, return empty tags\n\t\treturn nil, nil\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Extract OG tags\n\togTags := c.extractOGTags(doc)\n\n\t// Store in cache\n\tc.cache.Set(ctx, cacheKey, ogTags, c.ogTimeToLive)\n\n\treturn ogTags, nil\n}\n\nfunc (c *OGTagCache) generateCacheKey(target string, originalHost string) string {\n\tvar cacheKey string\n\n\tif c.ogCacheConsiderHost {\n\t\tcacheKey = target + \"|\" + originalHost\n\t} else {\n\t\tcacheKey = target\n\t}\n\treturn cacheKey\n}\n\n// checkCache checks if we have the tags cached and returns them if so\nfunc (c *OGTagCache) checkCache(ctx context.Context, cacheKey string) map[string]string {\n\tif cachedTags, err := c.cache.Get(ctx, cacheKey); err == nil {\n\t\tslog.Debug(\"cache hit\", \"tags\", cachedTags)\n\t\treturn cachedTags\n\t}\n\tslog.Debug(\"cache miss\", \"url\", cacheKey)\n\treturn nil\n}\n"], ["/anubis/cmd/anubis/main.go", "package main\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"crypto/ed25519\"\n\t\"crypto/rand\"\n\t\"crypto/tls\"\n\t\"embed\"\n\t\"encoding/hex\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io/fs\"\n\t\"log\"\n\t\"log/slog\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/http/httputil\"\n\t\"net/url\"\n\t\"os\"\n\t\"os/signal\"\n\t\"path/filepath\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/TecharoHQ/anubis/data\"\n\t\"github.com/TecharoHQ/anubis/internal\"\n\tlibanubis \"github.com/TecharoHQ/anubis/lib\"\n\tbotPolicy \"github.com/TecharoHQ/anubis/lib/policy\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/lib/thoth\"\n\t\"github.com/TecharoHQ/anubis/web\"\n\t\"github.com/facebookgo/flagenv\"\n\t_ \"github.com/joho/godotenv/autoload\"\n\t\"github.com/prometheus/client_golang/prometheus/promhttp\"\n\thealthv1 \"google.golang.org/grpc/health/grpc_health_v1\"\n)\n\nvar (\n\tbasePrefix = flag.String(\"base-prefix\", \"\", \"base prefix (root URL) the application is served under e.g. /myapp\")\n\tbind = flag.String(\"bind\", \":8923\", \"network address to bind HTTP to\")\n\tbindNetwork = flag.String(\"bind-network\", \"tcp\", \"network family to bind HTTP to, e.g. unix, tcp\")\n\tchallengeDifficulty = flag.Int(\"difficulty\", anubis.DefaultDifficulty, \"difficulty of the challenge\")\n\tcookieDomain = flag.String(\"cookie-domain\", \"\", \"if set, the top-level domain that the Anubis cookie will be valid for\")\n\tcookieDynamicDomain = flag.Bool(\"cookie-dynamic-domain\", false, \"if set, automatically set the cookie Domain value based on the request domain\")\n\tcookieExpiration = flag.Duration(\"cookie-expiration-time\", anubis.CookieDefaultExpirationTime, \"The amount of time the authorization cookie is valid for\")\n\tcookiePrefix = flag.String(\"cookie-prefix\", \"techaro.lol-anubis\", \"prefix for browser cookies created by Anubis\")\n\tcookiePartitioned = flag.Bool(\"cookie-partitioned\", false, \"if true, sets the partitioned flag on Anubis cookies, enabling CHIPS support\")\n\tforcedLanguage = flag.String(\"forced-language\", \"\", \"if set, this language is being used instead of the one from the request's Accept-Language header\")\n\ths512Secret = flag.String(\"hs512-secret\", \"\", \"secret used to sign JWTs, uses ed25519 if not set\")\n\tcookieSecure = flag.Bool(\"cookie-secure\", true, \"if true, sets the secure flag on Anubis cookies\")\n\ted25519PrivateKeyHex = flag.String(\"ed25519-private-key-hex\", \"\", \"private key used to sign JWTs, if not set a random one will be assigned\")\n\ted25519PrivateKeyHexFile = flag.String(\"ed25519-private-key-hex-file\", \"\", \"file name containing value for ed25519-private-key-hex\")\n\tmetricsBind = flag.String(\"metrics-bind\", \":9090\", \"network address to bind metrics to\")\n\tmetricsBindNetwork = flag.String(\"metrics-bind-network\", \"tcp\", \"network family for the metrics server to bind to\")\n\tsocketMode = flag.String(\"socket-mode\", \"0770\", \"socket mode (permissions) for unix domain sockets.\")\n\trobotsTxt = flag.Bool(\"serve-robots-txt\", false, \"serve a robots.txt file that disallows all robots\")\n\tpolicyFname = flag.String(\"policy-fname\", \"\", \"full path to anubis policy document (defaults to a sensible built-in policy)\")\n\tredirectDomains = flag.String(\"redirect-domains\", \"\", \"list of domains separated by commas which anubis is allowed to redirect to. Leaving this unset allows any domain.\")\n\tslogLevel = flag.String(\"slog-level\", \"INFO\", \"logging level (see https://pkg.go.dev/log/slog#hdr-Levels)\")\n\tstripBasePrefix = flag.Bool(\"strip-base-prefix\", false, \"if true, strips the base prefix from requests forwarded to the target server\")\n\ttarget = flag.String(\"target\", \"http://localhost:3923\", \"target to reverse proxy to, set to an empty string to disable proxying when only using auth request\")\n\ttargetSNI = flag.String(\"target-sni\", \"\", \"if set, the value of the TLS handshake hostname when forwarding requests to the target\")\n\ttargetHost = flag.String(\"target-host\", \"\", \"if set, the value of the Host header when forwarding requests to the target\")\n\ttargetInsecureSkipVerify = flag.Bool(\"target-insecure-skip-verify\", false, \"if true, skips TLS validation for the backend\")\n\thealthcheck = flag.Bool(\"healthcheck\", false, \"run a health check against Anubis\")\n\tuseRemoteAddress = flag.Bool(\"use-remote-address\", false, \"read the client's IP address from the network request, useful for debugging and running Anubis on bare metal\")\n\tdebugBenchmarkJS = flag.Bool(\"debug-benchmark-js\", false, \"respond to every request with a challenge for benchmarking hashrate\")\n\togPassthrough = flag.Bool(\"og-passthrough\", false, \"enable Open Graph tag passthrough\")\n\togTimeToLive = flag.Duration(\"og-expiry-time\", 24*time.Hour, \"Open Graph tag cache expiration time\")\n\togCacheConsiderHost = flag.Bool(\"og-cache-consider-host\", false, \"enable or disable the use of the host in the Open Graph tag cache\")\n\textractResources = flag.String(\"extract-resources\", \"\", \"if set, extract the static resources to the specified folder\")\n\twebmasterEmail = flag.String(\"webmaster-email\", \"\", \"if set, displays webmaster's email on the reject page for appeals\")\n\tversionFlag = flag.Bool(\"version\", false, \"print Anubis version\")\n\txffStripPrivate = flag.Bool(\"xff-strip-private\", true, \"if set, strip private addresses from X-Forwarded-For\")\n\n\tthothInsecure = flag.Bool(\"thoth-insecure\", false, \"if set, connect to Thoth over plain HTTP/2, don't enable this unless support told you to\")\n\tthothURL = flag.String(\"thoth-url\", \"\", \"if set, URL for Thoth, the IP reputation database for Anubis\")\n\tthothToken = flag.String(\"thoth-token\", \"\", \"if set, API token for Thoth, the IP reputation database for Anubis\")\n)\n\nfunc keyFromHex(value string) (ed25519.PrivateKey, error) {\n\tkeyBytes, err := hex.DecodeString(value)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"supplied key is not hex-encoded: %w\", err)\n\t}\n\n\tif len(keyBytes) != ed25519.SeedSize {\n\t\treturn nil, fmt.Errorf(\"supplied key is not %d bytes long, got %d bytes\", ed25519.SeedSize, len(keyBytes))\n\t}\n\n\treturn ed25519.NewKeyFromSeed(keyBytes), nil\n}\n\nfunc doHealthCheck() error {\n\tresp, err := http.Get(\"http://localhost\" + *metricsBind + \"/healthz\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to fetch metrics: %w\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn fmt.Errorf(\"unexpected status code: %d\", resp.StatusCode)\n\t}\n\n\treturn nil\n}\n\n// parseBindNetFromAddr determine bind network and address based on the given network and address.\nfunc parseBindNetFromAddr(address string) (string, string) {\n\tdefaultScheme := \"http://\"\n\tif !strings.Contains(address, \"://\") {\n\t\tif strings.HasPrefix(address, \":\") {\n\t\t\taddress = defaultScheme + \"localhost\" + address\n\t\t} else {\n\t\t\taddress = defaultScheme + address\n\t\t}\n\t}\n\n\tbindUri, err := url.Parse(address)\n\tif err != nil {\n\t\tlog.Fatal(fmt.Errorf(\"failed to parse bind URL: %w\", err))\n\t}\n\n\tswitch bindUri.Scheme {\n\tcase \"unix\":\n\t\treturn \"unix\", bindUri.Path\n\tcase \"tcp\", \"http\", \"https\":\n\t\treturn \"tcp\", bindUri.Host\n\tdefault:\n\t\tlog.Fatal(fmt.Errorf(\"unsupported network scheme %s in address %s\", bindUri.Scheme, address))\n\t}\n\treturn \"\", address\n}\n\nfunc setupListener(network string, address string) (net.Listener, string) {\n\tformattedAddress := \"\"\n\n\tif network == \"\" {\n\t\t// keep compatibility\n\t\tnetwork, address = parseBindNetFromAddr(address)\n\t}\n\n\tswitch network {\n\tcase \"unix\":\n\t\tformattedAddress = \"unix:\" + address\n\tcase \"tcp\":\n\t\tif strings.HasPrefix(address, \":\") { // assume it's just a port e.g. :4259\n\t\t\tformattedAddress = \"http://localhost\" + address\n\t\t} else {\n\t\t\tformattedAddress = \"http://\" + address\n\t\t}\n\tdefault:\n\t\tformattedAddress = fmt.Sprintf(`(%s) %s`, network, address)\n\t}\n\n\tlistener, err := net.Listen(network, address)\n\tif err != nil {\n\t\tlog.Fatal(fmt.Errorf(\"failed to bind to %s: %w\", formattedAddress, err))\n\t}\n\n\t// additional permission handling for unix sockets\n\tif network == \"unix\" {\n\t\tmode, err := strconv.ParseUint(*socketMode, 8, 0)\n\t\tif err != nil {\n\t\t\tlistener.Close()\n\t\t\tlog.Fatal(fmt.Errorf(\"could not parse socket mode %s: %w\", *socketMode, err))\n\t\t}\n\n\t\terr = os.Chmod(address, os.FileMode(mode))\n\t\tif err != nil {\n\t\t\terr := listener.Close()\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"failed to close listener: %v\", err)\n\t\t\t}\n\t\t\tlog.Fatal(fmt.Errorf(\"could not change socket mode: %w\", err))\n\t\t}\n\t}\n\n\treturn listener, formattedAddress\n}\n\nfunc makeReverseProxy(target string, targetSNI string, targetHost string, insecureSkipVerify bool) (http.Handler, error) {\n\ttargetUri, err := url.Parse(target)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to parse target URL: %w\", err)\n\t}\n\n\ttransport := http.DefaultTransport.(*http.Transport).Clone()\n\n\t// https://github.com/oauth2-proxy/oauth2-proxy/blob/4e2100a2879ef06aea1411790327019c1a09217c/pkg/upstream/http.go#L124\n\tif targetUri.Scheme == \"unix\" {\n\t\t// clean path up so we don't use the socket path in proxied requests\n\t\taddr := targetUri.Path\n\t\ttargetUri.Path = \"\"\n\t\t// tell transport how to dial unix sockets\n\t\ttransport.DialContext = func(ctx context.Context, _, _ string) (net.Conn, error) {\n\t\t\tdialer := net.Dialer{}\n\t\t\treturn dialer.DialContext(ctx, \"unix\", addr)\n\t\t}\n\t\t// tell transport how to handle the unix url scheme\n\t\ttransport.RegisterProtocol(\"unix\", libanubis.UnixRoundTripper{Transport: transport})\n\t}\n\n\tif insecureSkipVerify || targetSNI != \"\" {\n\t\ttransport.TLSClientConfig = &tls.Config{}\n\t\tif insecureSkipVerify {\n\t\t\tslog.Warn(\"TARGET_INSECURE_SKIP_VERIFY is set to true, TLS certificate validation will not be performed\", \"target\", target)\n\t\t\ttransport.TLSClientConfig.InsecureSkipVerify = true\n\t\t}\n\t\tif targetSNI != \"\" {\n\t\t\ttransport.TLSClientConfig.ServerName = targetSNI\n\t\t}\n\t}\n\n\trp := httputil.NewSingleHostReverseProxy(targetUri)\n\trp.Transport = transport\n\n\tif targetHost != \"\" {\n\t\toriginalDirector := rp.Director\n\t\trp.Director = func(req *http.Request) {\n\t\t\toriginalDirector(req)\n\t\t\treq.Host = targetHost\n\t\t}\n\t}\n\n\treturn rp, nil\n}\n\nfunc main() {\n\tflagenv.Parse()\n\tflag.Parse()\n\n\tif *versionFlag {\n\t\tfmt.Println(\"Anubis\", anubis.Version)\n\t\treturn\n\t}\n\n\tinternal.InitSlog(*slogLevel)\n\tinternal.SetHealth(\"anubis\", healthv1.HealthCheckResponse_NOT_SERVING)\n\n\tif *healthcheck {\n\t\tlog.Println(\"running healthcheck\")\n\t\tif err := doHealthCheck(); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\treturn\n\t}\n\n\tif *extractResources != \"\" {\n\t\tif err := extractEmbedFS(data.BotPolicies, \".\", *extractResources); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tif err := extractEmbedFS(web.Static, \"static\", *extractResources); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Printf(\"Extracted embedded static files to %s\\n\", *extractResources)\n\t\treturn\n\t}\n\n\t// install signal handler\n\tctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)\n\tdefer stop()\n\n\twg := new(sync.WaitGroup)\n\n\tif *metricsBind != \"\" {\n\t\twg.Add(1)\n\t\tgo metricsServer(ctx, wg.Done)\n\t}\n\n\tvar rp http.Handler\n\t// when using anubis via Systemd and environment variables, then it is not possible to set targe to an empty string but only to space\n\tif strings.TrimSpace(*target) != \"\" {\n\t\tvar err error\n\t\trp, err = makeReverseProxy(*target, *targetSNI, *targetHost, *targetInsecureSkipVerify)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"can't make reverse proxy: %v\", err)\n\t\t}\n\t}\n\n\tif *cookieDomain != \"\" && *cookieDynamicDomain {\n\t\tlog.Fatalf(\"you can't set COOKIE_DOMAIN and COOKIE_DYNAMIC_DOMAIN at the same time\")\n\t}\n\n\t// Thoth configuration\n\tswitch {\n\tcase *thothURL != \"\" && *thothToken == \"\":\n\t\tslog.Warn(\"THOTH_URL is set but no THOTH_TOKEN is set\")\n\tcase *thothURL == \"\" && *thothToken != \"\":\n\t\tslog.Warn(\"THOTH_TOKEN is set but no THOTH_URL is set\")\n\tcase *thothURL != \"\" && *thothToken != \"\":\n\t\tslog.Debug(\"connecting to Thoth\")\n\t\tthothClient, err := thoth.New(ctx, *thothURL, *thothToken, *thothInsecure)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"can't dial thoth at %s: %v\", *thothURL, err)\n\t\t}\n\n\t\tctx = thoth.With(ctx, thothClient)\n\t}\n\n\tpolicy, err := libanubis.LoadPoliciesOrDefault(ctx, *policyFname, *challengeDifficulty)\n\tif err != nil {\n\t\tlog.Fatalf(\"can't parse policy file: %v\", err)\n\t}\n\n\truleErrorIDs := make(map[string]string)\n\tfor _, rule := range policy.Bots {\n\t\tif rule.Action != config.RuleDeny {\n\t\t\tcontinue\n\t\t}\n\n\t\thash := rule.Hash()\n\t\truleErrorIDs[rule.Name] = hash\n\t}\n\n\t// replace the bot policy rules with a single rule that always benchmarks\n\tif *debugBenchmarkJS {\n\t\tpolicy.Bots = []botPolicy.Bot{{\n\t\t\tName: \"\",\n\t\t\tRules: botPolicy.NewHeaderExistsChecker(\"User-Agent\"),\n\t\t\tAction: config.RuleBenchmark,\n\t\t}}\n\t}\n\tif *basePrefix != \"\" && !strings.HasPrefix(*basePrefix, \"/\") {\n\t\tlog.Fatalf(\"[misconfiguration] base-prefix must start with a slash, eg: /%s\", *basePrefix)\n\t} else if strings.HasSuffix(*basePrefix, \"/\") {\n\t\tlog.Fatalf(\"[misconfiguration] base-prefix must not end with a slash\")\n\t}\n\tif *stripBasePrefix && *basePrefix == \"\" {\n\t\tlog.Fatalf(\"[misconfiguration] strip-base-prefix is set to true, but base-prefix is not set, \" +\n\t\t\t\"this may result in unexpected behavior\")\n\t}\n\n\tvar ed25519Priv ed25519.PrivateKey\n\tif *hs512Secret != \"\" && (*ed25519PrivateKeyHex != \"\" || *ed25519PrivateKeyHexFile != \"\") {\n\t\tlog.Fatal(\"do not specify both HS512 and ED25519 secrets\")\n\t} else if *hs512Secret != \"\" {\n\t\ted25519Priv = ed25519.PrivateKey(*hs512Secret)\n\t} else if *ed25519PrivateKeyHex != \"\" && *ed25519PrivateKeyHexFile != \"\" {\n\t\tlog.Fatal(\"do not specify both ED25519_PRIVATE_KEY_HEX and ED25519_PRIVATE_KEY_HEX_FILE\")\n\t} else if *ed25519PrivateKeyHex != \"\" {\n\t\ted25519Priv, err = keyFromHex(*ed25519PrivateKeyHex)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to parse and validate ED25519_PRIVATE_KEY_HEX: %v\", err)\n\t\t}\n\t} else if *ed25519PrivateKeyHexFile != \"\" {\n\t\thexFile, err := os.ReadFile(*ed25519PrivateKeyHexFile)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to read ED25519_PRIVATE_KEY_HEX_FILE %s: %v\", *ed25519PrivateKeyHexFile, err)\n\t\t}\n\n\t\ted25519Priv, err = keyFromHex(string(bytes.TrimSpace(hexFile)))\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to parse and validate content of ED25519_PRIVATE_KEY_HEX_FILE: %v\", err)\n\t\t}\n\t} else {\n\t\t_, ed25519Priv, err = ed25519.GenerateKey(rand.Reader)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to generate ed25519 key: %v\", err)\n\t\t}\n\n\t\tslog.Warn(\"generating random key, Anubis will have strange behavior when multiple instances are behind the same load balancer target, for more information: see https://anubis.techaro.lol/docs/admin/installation#key-generation\")\n\t}\n\n\tvar redirectDomainsList []string\n\tif *redirectDomains != \"\" {\n\t\tdomains := strings.Split(*redirectDomains, \",\")\n\t\tfor _, domain := range domains {\n\t\t\t_, err = url.Parse(domain)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"cannot parse redirect-domain %q: %s\", domain, err.Error())\n\t\t\t}\n\t\t\tredirectDomainsList = append(redirectDomainsList, strings.TrimSpace(domain))\n\t\t}\n\t} else {\n\t\tslog.Warn(\"REDIRECT_DOMAINS is not set, Anubis will only redirect to the same domain a request is coming from, see https://anubis.techaro.lol/docs/admin/configuration/redirect-domains\")\n\t}\n\n\tanubis.CookieName = *cookiePrefix + \"-auth\"\n\tanubis.TestCookieName = *cookiePrefix + \"-cookie-verification\"\n\tanubis.ForcedLanguage = *forcedLanguage\n\n\t// If OpenGraph configuration values are not set in the config file, use the\n\t// values from flags / envvars.\n\tif !policy.OpenGraph.Enabled {\n\t\tpolicy.OpenGraph.Enabled = *ogPassthrough\n\t\tpolicy.OpenGraph.ConsiderHost = *ogCacheConsiderHost\n\t\tpolicy.OpenGraph.TimeToLive = *ogTimeToLive\n\t\tpolicy.OpenGraph.Override = map[string]string{}\n\t}\n\n\ts, err := libanubis.New(libanubis.Options{\n\t\tBasePrefix: *basePrefix,\n\t\tStripBasePrefix: *stripBasePrefix,\n\t\tNext: rp,\n\t\tPolicy: policy,\n\t\tServeRobotsTXT: *robotsTxt,\n\t\tED25519PrivateKey: ed25519Priv,\n\t\tHS512Secret: []byte(*hs512Secret),\n\t\tCookieDomain: *cookieDomain,\n\t\tCookieDynamicDomain: *cookieDynamicDomain,\n\t\tCookieExpiration: *cookieExpiration,\n\t\tCookiePartitioned: *cookiePartitioned,\n\t\tRedirectDomains: redirectDomainsList,\n\t\tTarget: *target,\n\t\tWebmasterEmail: *webmasterEmail,\n\t\tOpenGraph: policy.OpenGraph,\n\t\tCookieSecure: *cookieSecure,\n\t})\n\tif err != nil {\n\t\tlog.Fatalf(\"can't construct libanubis.Server: %v\", err)\n\t}\n\n\tvar h http.Handler\n\th = s\n\th = internal.RemoteXRealIP(*useRemoteAddress, *bindNetwork, h)\n\th = internal.XForwardedForToXRealIP(h)\n\th = internal.XForwardedForUpdate(*xffStripPrivate, h)\n\th = internal.JA4H(h)\n\n\tsrv := http.Server{Handler: h, ErrorLog: internal.GetFilteredHTTPLogger()}\n\tlistener, listenerUrl := setupListener(*bindNetwork, *bind)\n\tslog.Info(\n\t\t\"listening\",\n\t\t\"url\", listenerUrl,\n\t\t\"difficulty\", *challengeDifficulty,\n\t\t\"serveRobotsTXT\", *robotsTxt,\n\t\t\"target\", *target,\n\t\t\"version\", anubis.Version,\n\t\t\"use-remote-address\", *useRemoteAddress,\n\t\t\"debug-benchmark-js\", *debugBenchmarkJS,\n\t\t\"og-passthrough\", *ogPassthrough,\n\t\t\"og-expiry-time\", *ogTimeToLive,\n\t\t\"base-prefix\", *basePrefix,\n\t\t\"cookie-expiration-time\", *cookieExpiration,\n\t\t\"rule-error-ids\", ruleErrorIDs,\n\t)\n\n\tgo func() {\n\t\t<-ctx.Done()\n\t\tc, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\t\tdefer cancel()\n\t\tif err := srv.Shutdown(c); err != nil {\n\t\t\tlog.Printf(\"cannot shut down: %v\", err)\n\t\t}\n\t}()\n\n\tinternal.SetHealth(\"anubis\", healthv1.HealthCheckResponse_SERVING)\n\n\tif err := srv.Serve(listener); !errors.Is(err, http.ErrServerClosed) {\n\t\tlog.Fatal(err)\n\t}\n\twg.Wait()\n}\n\nfunc metricsServer(ctx context.Context, done func()) {\n\tdefer done()\n\n\tmux := http.NewServeMux()\n\tmux.Handle(\"/metrics\", promhttp.Handler())\n\tmux.HandleFunc(\"/healthz\", func(w http.ResponseWriter, r *http.Request) {\n\t\tst, ok := internal.GetHealth(\"anubis\")\n\t\tif !ok {\n\t\t\tslog.Error(\"health service anubis does not exist, file a bug\")\n\t\t}\n\n\t\tswitch st {\n\t\tcase healthv1.HealthCheckResponse_NOT_SERVING:\n\t\t\thttp.Error(w, \"NOT OK\", http.StatusInternalServerError)\n\t\t\treturn\n\t\tcase healthv1.HealthCheckResponse_SERVING:\n\t\t\tfmt.Fprintln(w, \"OK\")\n\t\t\treturn\n\t\tdefault:\n\t\t\thttp.Error(w, \"UNKNOWN\", http.StatusFailedDependency)\n\t\t\treturn\n\t\t}\n\t})\n\n\tsrv := http.Server{Handler: mux, ErrorLog: internal.GetFilteredHTTPLogger()}\n\tlistener, metricsUrl := setupListener(*metricsBindNetwork, *metricsBind)\n\tslog.Debug(\"listening for metrics\", \"url\", metricsUrl)\n\n\tgo func() {\n\t\t<-ctx.Done()\n\t\tc, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\t\tdefer cancel()\n\t\tif err := srv.Shutdown(c); err != nil {\n\t\t\tlog.Printf(\"cannot shut down: %v\", err)\n\t\t}\n\t}()\n\n\tif err := srv.Serve(listener); !errors.Is(err, http.ErrServerClosed) {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc extractEmbedFS(fsys embed.FS, root string, destDir string) error {\n\treturn fs.WalkDir(fsys, root, func(path string, d fs.DirEntry, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\trelPath, err := filepath.Rel(root, path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdestPath := filepath.Join(destDir, root, relPath)\n\n\t\tif d.IsDir() {\n\t\t\treturn os.MkdirAll(destPath, 0o700)\n\t\t}\n\n\t\tembeddedData, err := fs.ReadFile(fsys, path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn os.WriteFile(destPath, embeddedData, 0o644)\n\t})\n}\n"], ["/anubis/internal/ogtags/ogtags.go", "package ogtags\n\nimport (\n\t\"context\"\n\t\"log/slog\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n)\n\nconst (\n\tmaxContentLength = 8 << 20 // 8 MiB is enough for anyone\n\thttpTimeout = 5 * time.Second /*todo: make this configurable?*/\n\n\tschemeSeparatorLength = 3 // Length of \"://\"\n\tquerySeparatorLength = 1 // Length of \"?\" for query strings\n)\n\ntype OGTagCache struct {\n\tcache store.JSON[map[string]string]\n\ttargetURL *url.URL\n\tclient *http.Client\n\n\t// Pre-built strings for optimization\n\tunixPrefix string // \"http://unix\"\n\tapprovedTags []string\n\tapprovedPrefixes []string\n\togTimeToLive time.Duration\n\togCacheConsiderHost bool\n\togPassthrough bool\n\togOverride map[string]string\n}\n\nfunc NewOGTagCache(target string, conf config.OpenGraph, backend store.Interface) *OGTagCache {\n\t// Predefined approved tags and prefixes\n\tdefaultApprovedTags := []string{\"description\", \"keywords\", \"author\"}\n\tdefaultApprovedPrefixes := []string{\"og:\", \"twitter:\", \"fediverse:\"}\n\n\tvar parsedTargetURL *url.URL\n\tvar err error\n\n\tif target == \"\" {\n\t\t// Default to localhost if target is empty\n\t\tparsedTargetURL, _ = url.Parse(\"http://localhost\")\n\t} else {\n\t\tparsedTargetURL, err = url.Parse(target)\n\t\tif err != nil {\n\t\t\tslog.Debug(\"og: failed to parse target URL, treating as non-unix\", \"target\", target, \"error\", err)\n\t\t\t// If parsing fails, treat it as a non-unix target for backward compatibility or default behavior\n\t\t\t// For now, assume it's not a scheme issue but maybe an invalid char, etc.\n\t\t\t// A simple string target might be intended if it's not a full URL.\n\t\t\tparsedTargetURL = &url.URL{Scheme: \"http\", Host: target} // Assume http if scheme missing and host-like\n\t\t\tif !strings.Contains(target, \"://\") && !strings.HasPrefix(target, \"unix:\") {\n\t\t\t\t// If it looks like just a host/host:port (and not unix), prepend http:// (todo: is this bad...? Trace path to see if i can yell at user to do it right)\n\t\t\t\tparsedTargetURL, _ = url.Parse(\"http://\" + target) // fetch cares about scheme but anubis doesn't\n\t\t\t}\n\t\t}\n\t}\n\n\tclient := &http.Client{\n\t\tTimeout: httpTimeout,\n\t}\n\n\t// Configure custom transport for Unix sockets\n\tif parsedTargetURL.Scheme == \"unix\" {\n\t\tsocketPath := parsedTargetURL.Path // For unix scheme, path is the socket path\n\t\tclient.Transport = &http.Transport{\n\t\t\tDialContext: func(_ context.Context, _, _ string) (net.Conn, error) {\n\t\t\t\treturn net.Dial(\"unix\", socketPath)\n\t\t\t},\n\t\t}\n\t}\n\n\treturn &OGTagCache{\n\t\tcache: store.JSON[map[string]string]{\n\t\t\tUnderlying: backend,\n\t\t\tPrefix: \"ogtags:\",\n\t\t},\n\t\ttargetURL: parsedTargetURL,\n\t\togPassthrough: conf.Enabled,\n\t\togTimeToLive: conf.TimeToLive,\n\t\togCacheConsiderHost: conf.ConsiderHost,\n\t\togOverride: conf.Override,\n\t\tapprovedTags: defaultApprovedTags,\n\t\tapprovedPrefixes: defaultApprovedPrefixes,\n\t\tclient: client,\n\t\tunixPrefix: \"http://unix\",\n\t}\n}\n\n// getTarget constructs the target URL string for fetching OG tags.\n// Optimized to minimize allocations by building strings directly.\nfunc (c *OGTagCache) getTarget(u *url.URL) string {\n\tvar escapedPath = u.EscapedPath() // will cause an allocation if path contains special characters\n\tif c.targetURL.Scheme == \"unix\" {\n\t\t// Build URL string directly without creating intermediate URL object\n\t\tvar sb strings.Builder\n\t\tsb.Grow(len(c.unixPrefix) + len(escapedPath) + len(u.RawQuery) + querySeparatorLength) // Pre-allocate\n\t\tsb.WriteString(c.unixPrefix)\n\t\tsb.WriteString(escapedPath)\n\t\tif u.RawQuery != \"\" {\n\t\t\tsb.WriteByte('?')\n\t\t\tsb.WriteString(u.RawQuery)\n\t\t}\n\t\treturn sb.String()\n\t}\n\n\t// For regular http/https targets, build URL string directly\n\tvar sb strings.Builder\n\t// Pre-calculate size: scheme + \"://\" + host + path + \"?\" + query\n\testimatedSize := len(c.targetURL.Scheme) + schemeSeparatorLength + len(c.targetURL.Host) + len(escapedPath) + len(u.RawQuery) + querySeparatorLength\n\tsb.Grow(estimatedSize)\n\n\tsb.WriteString(c.targetURL.Scheme)\n\tsb.WriteString(\"://\")\n\tsb.WriteString(c.targetURL.Host)\n\tsb.WriteString(escapedPath)\n\tif u.RawQuery != \"\" {\n\t\tsb.WriteByte('?')\n\t\tsb.WriteString(u.RawQuery)\n\t}\n\n\treturn sb.String()\n}\n"], ["/anubis/internal/headers.go", "package internal\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/netip\"\n\t\"strings\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/sebest/xff\"\n)\n\n// TODO: move into config\ntype XFFComputePreferences struct {\n\tStripPrivate bool\n\tStripLoopback bool\n\tStripCGNAT bool\n\tStripLLU bool\n\tFlatten bool\n}\n\nvar CGNat = netip.MustParsePrefix(\"100.64.0.0/10\")\n\n// UnchangingCache sets the Cache-Control header to cache a response for 1 year if\n// and only if the application is compiled in \"release\" mode by Docker.\nfunc UnchangingCache(next http.Handler) http.Handler {\n\t//goland:noinspection GoBoolExpressions\n\tif anubis.Version == \"devel\" {\n\t\treturn next\n\t}\n\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Cache-Control\", \"public, max-age=31536000\")\n\t\tnext.ServeHTTP(w, r)\n\t})\n}\n\n// RemoteXRealIP sets the X-Real-Ip header to the request's real IP if\n// the setting is enabled by the user.\nfunc RemoteXRealIP(useRemoteAddress bool, bindNetwork string, next http.Handler) http.Handler {\n\tif !useRemoteAddress {\n\t\tslog.Debug(\"skipping middleware, useRemoteAddress is empty\")\n\t\treturn next\n\t}\n\n\tif bindNetwork == \"unix\" {\n\t\t// For local sockets there is no real remote address but the localhost\n\t\t// address should be sensible.\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tr.Header.Set(\"X-Real-Ip\", \"127.0.0.1\")\n\t\t\tnext.ServeHTTP(w, r)\n\t\t})\n\t}\n\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\thost, _, err := net.SplitHostPort(r.RemoteAddr)\n\t\tif err != nil {\n\t\t\tpanic(err) // this should never happen\n\t\t}\n\t\tr.Header.Set(\"X-Real-Ip\", host)\n\t\tnext.ServeHTTP(w, r)\n\t})\n}\n\n// XForwardedForToXRealIP sets the X-Real-Ip header based on the contents\n// of the X-Forwarded-For header.\nfunc XForwardedForToXRealIP(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif xffHeader := r.Header.Get(\"X-Forwarded-For\"); r.Header.Get(\"X-Real-Ip\") == \"\" && xffHeader != \"\" {\n\t\t\tip := xff.Parse(xffHeader)\n\t\t\tslog.Debug(\"setting x-real-ip\", \"val\", ip)\n\t\t\tr.Header.Set(\"X-Real-Ip\", ip)\n\t\t}\n\n\t\tnext.ServeHTTP(w, r)\n\t})\n}\n\n// XForwardedForUpdate sets or updates the X-Forwarded-For header, adding\n// the known remote address to an existing chain if present\nfunc XForwardedForUpdate(stripPrivate bool, next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tdefer next.ServeHTTP(w, r)\n\n\t\tpref := XFFComputePreferences{\n\t\t\tStripPrivate: stripPrivate,\n\t\t\tStripLoopback: true,\n\t\t\tStripCGNAT: true,\n\t\t\tFlatten: true,\n\t\t\tStripLLU: true,\n\t\t}\n\n\t\tremoteAddr := r.RemoteAddr\n\t\torigXFFHeader := r.Header.Get(\"X-Forwarded-For\")\n\n\t\tif remoteAddr == \"@\" {\n\t\t\t// remote is a unix socket\n\t\t\t// do not touch chain\n\t\t\treturn\n\t\t}\n\n\t\txffHeaderString, err := computeXFFHeader(remoteAddr, origXFFHeader, pref)\n\t\tif err != nil {\n\t\t\tslog.Debug(\"computing X-Forwarded-For header failed\", \"err\", err)\n\t\t\treturn\n\t\t}\n\n\t\tif len(xffHeaderString) == 0 {\n\t\t\tr.Header.Del(\"X-Forwarded-For\")\n\t\t} else {\n\t\t\tr.Header.Set(\"X-Forwarded-For\", xffHeaderString)\n\t\t}\n\t})\n}\n\nvar (\n\tErrCantSplitHostParse = errors.New(\"internal: unable to net.SplitHostParse\")\n\tErrCantParseRemoteIP = errors.New(\"internal: unable to parse remote IP\")\n)\n\nfunc computeXFFHeader(remoteAddr string, origXFFHeader string, pref XFFComputePreferences) (string, error) {\n\tremoteIP, _, err := net.SplitHostPort(remoteAddr)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"%w: %w\", ErrCantSplitHostParse, err)\n\t}\n\tparsedRemoteIP, err := netip.ParseAddr(remoteIP)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"%w: %w\", ErrCantParseRemoteIP, err)\n\t}\n\n\torigForwardedList := make([]string, 0, 4)\n\tif origXFFHeader != \"\" {\n\t\torigForwardedList = strings.Split(origXFFHeader, \",\")\n\t\tfor i := range origForwardedList {\n\t\t\torigForwardedList[i] = strings.TrimSpace(origForwardedList[i])\n\t\t}\n\t}\n\torigForwardedList = append(origForwardedList, parsedRemoteIP.String())\n\tforwardedList := make([]string, 0, len(origForwardedList))\n\t// this behavior is equivalent to\n\t// ingress-nginx \"compute-full-forwarded-for\"\n\t// https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/configmap/#compute-full-forwarded-for\n\t//\n\t// this would be the correct place to strip and/or flatten this list\n\t//\n\t// strip - iterate backwards and eliminate configured trusted IPs\n\t// flatten - only return the last element to avoid spoofing confusion\n\t//\n\t// many applications handle this in different ways, but\n\t// generally they'd be expected to do these two things on\n\t// their own end to find the first non-spoofed IP\n\tfor i := len(origForwardedList) - 1; i >= 0; i-- {\n\t\tsegmentIP, err := netip.ParseAddr(origForwardedList[i])\n\t\tif err != nil {\n\t\t\t// can't assess this element, so the remainder of the chain\n\t\t\t// can't be trusted. not a fatal error, since anyone can\n\t\t\t// spoof an XFF header\n\t\t\tslog.Debug(\"failed to parse XFF segment\", \"err\", err)\n\t\t\tbreak\n\t\t}\n\t\tif pref.StripPrivate && segmentIP.IsPrivate() {\n\t\t\tcontinue\n\t\t}\n\t\tif pref.StripLoopback && segmentIP.IsLoopback() {\n\t\t\tcontinue\n\t\t}\n\t\tif pref.StripLLU && segmentIP.IsLinkLocalUnicast() {\n\t\t\tcontinue\n\t\t}\n\t\tif pref.StripCGNAT && CGNat.Contains(segmentIP) {\n\t\t\tcontinue\n\t\t}\n\t\tforwardedList = append([]string{segmentIP.String()}, forwardedList...)\n\t}\n\tvar xffHeaderString string\n\tif len(forwardedList) == 0 {\n\t\txffHeaderString = \"\"\n\t\treturn xffHeaderString, nil\n\t}\n\tif pref.Flatten {\n\t\txffHeaderString = forwardedList[len(forwardedList)-1]\n\t} else {\n\t\txffHeaderString = strings.Join(forwardedList, \",\")\n\t}\n\treturn xffHeaderString, nil\n}\n\n// NoStoreCache sets the Cache-Control header to no-store for the response.\nfunc NoStoreCache(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Cache-Control\", \"no-store\")\n\t\tnext.ServeHTTP(w, r)\n\t})\n}\n\n// NoBrowsing prevents directory browsing by returning a 404 for any request that ends with a \"/\".\nfunc NoBrowsing(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif strings.HasSuffix(r.URL.Path, \"/\") {\n\t\t\thttp.NotFound(w, r)\n\t\t\treturn\n\t\t}\n\t\tnext.ServeHTTP(w, r)\n\t})\n}\n"], ["/anubis/lib/anubis.go", "package lib\n\nimport (\n\t\"context\"\n\t\"crypto/ed25519\"\n\t\"crypto/rand\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"slices\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/golang-jwt/jwt/v5\"\n\t\"github.com/google/cel-go/common/types\"\n\t\"github.com/google/uuid\"\n\n\t\"github.com/prometheus/client_golang/prometheus\"\n\t\"github.com/prometheus/client_golang/prometheus/promauto\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/TecharoHQ/anubis/decaymap\"\n\t\"github.com/TecharoHQ/anubis/internal\"\n\t\"github.com/TecharoHQ/anubis/internal/dnsbl\"\n\t\"github.com/TecharoHQ/anubis/internal/ogtags\"\n\t\"github.com/TecharoHQ/anubis/lib/challenge\"\n\t\"github.com/TecharoHQ/anubis/lib/localization\"\n\t\"github.com/TecharoHQ/anubis/lib/policy\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/checker\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n\n\t// challenge implementations\n\t_ \"github.com/TecharoHQ/anubis/lib/challenge/metarefresh\"\n\t_ \"github.com/TecharoHQ/anubis/lib/challenge/proofofwork\"\n)\n\nvar (\n\tchallengesIssued = promauto.NewCounterVec(prometheus.CounterOpts{\n\t\tName: \"anubis_challenges_issued\",\n\t\tHelp: \"The total number of challenges issued\",\n\t}, []string{\"method\"})\n\n\tchallengesValidated = promauto.NewCounterVec(prometheus.CounterOpts{\n\t\tName: \"anubis_challenges_validated\",\n\t\tHelp: \"The total number of challenges validated\",\n\t}, []string{\"method\"})\n\n\tdroneBLHits = promauto.NewCounterVec(prometheus.CounterOpts{\n\t\tName: \"anubis_dronebl_hits\",\n\t\tHelp: \"The total number of hits from DroneBL\",\n\t}, []string{\"status\"})\n\n\tfailedValidations = promauto.NewCounterVec(prometheus.CounterOpts{\n\t\tName: \"anubis_failed_validations\",\n\t\tHelp: \"The total number of failed validations\",\n\t}, []string{\"method\"})\n\n\trequestsProxied = promauto.NewCounterVec(prometheus.CounterOpts{\n\t\tName: \"anubis_proxied_requests_total\",\n\t\tHelp: \"Number of requests proxied through Anubis to upstream targets\",\n\t}, []string{\"host\"})\n)\n\ntype Server struct {\n\tnext http.Handler\n\tmux *http.ServeMux\n\tpolicy *policy.ParsedConfig\n\tOGTags *ogtags.OGTagCache\n\ted25519Priv ed25519.PrivateKey\n\ths512Secret []byte\n\topts Options\n\tstore store.Interface\n}\n\nfunc (s *Server) getTokenKeyfunc() jwt.Keyfunc {\n\t// return ED25519 key if HS512 is not set\n\tif len(s.hs512Secret) == 0 {\n\t\treturn func(token *jwt.Token) (interface{}, error) {\n\t\t\treturn s.ed25519Priv.Public().(ed25519.PublicKey), nil\n\t\t}\n\t} else {\n\t\treturn func(token *jwt.Token) (interface{}, error) {\n\t\t\treturn s.hs512Secret, nil\n\t\t}\n\t}\n}\n\nfunc (s *Server) challengeFor(r *http.Request) (*challenge.Challenge, error) {\n\tckies := r.CookiesNamed(anubis.TestCookieName)\n\n\tif len(ckies) == 0 {\n\t\treturn s.issueChallenge(r.Context(), r)\n\t}\n\n\tj := store.JSON[challenge.Challenge]{Underlying: s.store}\n\n\tckie := ckies[0]\n\tchall, err := j.Get(r.Context(), \"challenge:\"+ckie.Value)\n\tif err != nil {\n\t\tif errors.Is(err, store.ErrNotFound) {\n\t\t\treturn s.issueChallenge(r.Context(), r)\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\treturn &chall, nil\n}\n\nfunc (s *Server) issueChallenge(ctx context.Context, r *http.Request) (*challenge.Challenge, error) {\n\tid, err := uuid.NewV7()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar randomData = make([]byte, 256)\n\tif _, err := rand.Read(randomData); err != nil {\n\t\treturn nil, err\n\t}\n\n\tchall := challenge.Challenge{\n\t\tID: id.String(),\n\t\tRandomData: fmt.Sprintf(\"%x\", randomData),\n\t\tIssuedAt: time.Now(),\n\t\tMetadata: map[string]string{\n\t\t\t\"User-Agent\": r.Header.Get(\"User-Agent\"),\n\t\t\t\"X-Real-Ip\": r.Header.Get(\"X-Real-Ip\"),\n\t\t},\n\t}\n\n\tj := store.JSON[challenge.Challenge]{Underlying: s.store}\n\tif err := j.Set(ctx, \"challenge:\"+id.String(), chall, 30*time.Minute); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &chall, err\n}\n\nfunc (s *Server) maybeReverseProxyHttpStatusOnly(w http.ResponseWriter, r *http.Request) {\n\ts.maybeReverseProxy(w, r, true)\n}\n\nfunc (s *Server) maybeReverseProxyOrPage(w http.ResponseWriter, r *http.Request) {\n\ts.maybeReverseProxy(w, r, false)\n}\n\nfunc (s *Server) maybeReverseProxy(w http.ResponseWriter, r *http.Request, httpStatusOnly bool) {\n\tlg := internal.GetRequestLogger(r)\n\n\t// Adjust cookie path if base prefix is not empty\n\tcookiePath := \"/\"\n\tif anubis.BasePrefix != \"\" {\n\t\tcookiePath = strings.TrimSuffix(anubis.BasePrefix, \"/\") + \"/\"\n\t}\n\n\tcr, rule, err := s.check(r)\n\tif err != nil {\n\t\tlg.Error(\"check failed\", \"err\", err)\n\t\tlocalizer := localization.GetLocalizer(r)\n\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s \\\"maybeReverseProxy\\\"\", localizer.T(\"internal_server_error\")))\n\t\treturn\n\t}\n\n\tr.Header.Add(\"X-Anubis-Rule\", cr.Name)\n\tr.Header.Add(\"X-Anubis-Action\", string(cr.Rule))\n\tlg = lg.With(\"check_result\", cr)\n\tpolicy.Applications.WithLabelValues(cr.Name, string(cr.Rule)).Add(1)\n\n\tip := r.Header.Get(\"X-Real-Ip\")\n\n\tif s.handleDNSBL(w, r, ip, lg) {\n\t\treturn\n\t}\n\n\tif s.checkRules(w, r, cr, lg, rule) {\n\t\treturn\n\t}\n\n\tckie, err := r.Cookie(anubis.CookieName)\n\tif err != nil {\n\t\tlg.Debug(\"cookie not found\", \"path\", r.URL.Path)\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.RenderIndex(w, r, rule, httpStatusOnly)\n\t\treturn\n\t}\n\n\tif err := ckie.Valid(); err != nil {\n\t\tlg.Debug(\"cookie is invalid\", \"err\", err)\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.RenderIndex(w, r, rule, httpStatusOnly)\n\t\treturn\n\t}\n\n\tif time.Now().After(ckie.Expires) && !ckie.Expires.IsZero() {\n\t\tlg.Debug(\"cookie expired\", \"path\", r.URL.Path)\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.RenderIndex(w, r, rule, httpStatusOnly)\n\t\treturn\n\t}\n\n\ttoken, err := jwt.ParseWithClaims(ckie.Value, jwt.MapClaims{}, s.getTokenKeyfunc(), jwt.WithExpirationRequired(), jwt.WithStrictDecoding())\n\n\tif err != nil || !token.Valid {\n\t\tlg.Debug(\"invalid token\", \"path\", r.URL.Path, \"err\", err)\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.RenderIndex(w, r, rule, httpStatusOnly)\n\t\treturn\n\t}\n\n\tclaims, ok := token.Claims.(jwt.MapClaims)\n\tif !ok {\n\t\tlg.Debug(\"invalid token claims type\", \"path\", r.URL.Path)\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.RenderIndex(w, r, rule, httpStatusOnly)\n\t\treturn\n\t}\n\n\tpolicyRule, ok := claims[\"policyRule\"].(string)\n\tif !ok {\n\t\tlg.Debug(\"policyRule claim is not a string\")\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.RenderIndex(w, r, rule, httpStatusOnly)\n\t\treturn\n\t}\n\n\tif policyRule != rule.Hash() {\n\t\tlg.Debug(\"user originally passed with a different rule, issuing new challenge\", \"old\", policyRule, \"new\", rule.Name)\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.RenderIndex(w, r, rule, httpStatusOnly)\n\t\treturn\n\t}\n\n\tr.Header.Add(\"X-Anubis-Status\", \"PASS\")\n\ts.ServeHTTPNext(w, r)\n}\n\nfunc (s *Server) checkRules(w http.ResponseWriter, r *http.Request, cr policy.CheckResult, lg *slog.Logger, rule *policy.Bot) bool {\n\t// Adjust cookie path if base prefix is not empty\n\tcookiePath := \"/\"\n\tif anubis.BasePrefix != \"\" {\n\t\tcookiePath = strings.TrimSuffix(anubis.BasePrefix, \"/\") + \"/\"\n\t}\n\n\tlocalizer := localization.GetLocalizer(r)\n\n\tswitch cr.Rule {\n\tcase config.RuleAllow:\n\t\tlg.Debug(\"allowing traffic to origin (explicit)\")\n\t\ts.ServeHTTPNext(w, r)\n\t\treturn true\n\tcase config.RuleDeny:\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\tlg.Info(\"explicit deny\")\n\t\tif rule == nil {\n\t\t\tlg.Error(\"rule is nil, cannot calculate checksum\")\n\t\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s \\\"maybeReverseProxy.RuleDeny\\\"\", localizer.T(\"internal_server_error\")))\n\t\t\treturn true\n\t\t}\n\t\thash := rule.Hash()\n\n\t\tlg.Debug(\"rule hash\", \"hash\", hash)\n\t\ts.respondWithStatus(w, r, fmt.Sprintf(\"%s %s\", localizer.T(\"access_denied\"), hash), s.policy.StatusCodes.Deny)\n\t\treturn true\n\tcase config.RuleChallenge:\n\t\tlg.Debug(\"challenge requested\")\n\tcase config.RuleBenchmark:\n\t\tlg.Debug(\"serving benchmark page\")\n\t\ts.RenderBench(w, r)\n\t\treturn true\n\tdefault:\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\tslog.Error(\"CONFIG ERROR: unknown rule\", \"rule\", cr.Rule)\n\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s \\\"maybeReverseProxy.Rules\\\"\", localizer.T(\"internal_server_error\")))\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (s *Server) handleDNSBL(w http.ResponseWriter, r *http.Request, ip string, lg *slog.Logger) bool {\n\tdb := &store.JSON[dnsbl.DroneBLResponse]{Underlying: s.store, Prefix: \"dronebl:\"}\n\tif s.policy.DNSBL && ip != \"\" {\n\t\tresp, err := db.Get(r.Context(), ip)\n\t\tif err != nil {\n\t\t\tlg.Debug(\"looking up ip in dnsbl\")\n\t\t\tresp, err := dnsbl.Lookup(ip)\n\t\t\tif err != nil {\n\t\t\t\tlg.Error(\"can't look up ip in dnsbl\", \"err\", err)\n\t\t\t}\n\t\t\tdb.Set(r.Context(), ip, resp, 24*time.Hour)\n\t\t\tdroneBLHits.WithLabelValues(resp.String()).Inc()\n\t\t}\n\n\t\tif resp != dnsbl.AllGood {\n\t\t\tlg.Info(\"DNSBL hit\", \"status\", resp.String())\n\t\t\tlocalizer := localization.GetLocalizer(r)\n\t\t\ts.respondWithStatus(w, r, fmt.Sprintf(\"%s: %s, %s https://dronebl.org/lookup?ip=%s\",\n\t\t\t\tlocalizer.T(\"dronebl_entry\"),\n\t\t\t\tresp.String(),\n\t\t\t\tlocalizer.T(\"see_dronebl_lookup\"),\n\t\t\t\tip), s.policy.StatusCodes.Deny)\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (s *Server) MakeChallenge(w http.ResponseWriter, r *http.Request) {\n\tlg := internal.GetRequestLogger(r)\n\tlocalizer := localization.GetLocalizer(r)\n\n\tredir := r.FormValue(\"redir\")\n\tif redir == \"\" {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tencoder := json.NewEncoder(w)\n\t\tlg.Error(\"invalid invocation of MakeChallenge\", \"redir\", redir)\n\t\tencoder.Encode(struct {\n\t\t\tError string `json:\"error\"`\n\t\t}{\n\t\t\tError: localizer.T(\"invalid_invocation\"),\n\t\t})\n\t\treturn\n\t}\n\n\tr.URL.Path = redir\n\n\tencoder := json.NewEncoder(w)\n\tcr, rule, err := s.check(r)\n\tif err != nil {\n\t\tlg.Error(\"check failed\", \"err\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\terr := encoder.Encode(struct {\n\t\t\tError string `json:\"error\"`\n\t\t}{\n\t\t\tError: fmt.Sprintf(\"%s \\\"makeChallenge\\\"\", localizer.T(\"internal_server_error\")),\n\t\t})\n\t\tif err != nil {\n\t\t\tlg.Error(\"failed to encode error response\", \"err\", err)\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t}\n\t\treturn\n\t}\n\tlg = lg.With(\"check_result\", cr)\n\n\tchall, err := s.challengeFor(r)\n\tif err != nil {\n\t\tlg.Error(\"failed to fetch or issue challenge\", \"err\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\terr := encoder.Encode(struct {\n\t\t\tError string `json:\"error\"`\n\t\t}{\n\t\t\tError: fmt.Sprintf(\"%s \\\"makeChallenge\\\"\", localizer.T(\"internal_server_error\")),\n\t\t})\n\t\tif err != nil {\n\t\t\tlg.Error(\"failed to encode error response\", \"err\", err)\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t}\n\t\treturn\n\t}\n\n\ts.SetCookie(w, CookieOpts{Host: r.Host, Name: anubis.TestCookieName, Value: chall.ID})\n\n\terr = encoder.Encode(struct {\n\t\tRules *config.ChallengeRules `json:\"rules\"`\n\t\tChallenge string `json:\"challenge\"`\n\t}{\n\t\tChallenge: chall.RandomData,\n\t\tRules: rule.Challenge,\n\t})\n\tif err != nil {\n\t\tlg.Error(\"failed to encode challenge\", \"err\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\tlg.Debug(\"made challenge\", \"challenge\", chall, \"rules\", rule.Challenge, \"cr\", cr)\n\tchallengesIssued.WithLabelValues(\"api\").Inc()\n}\n\nfunc (s *Server) PassChallenge(w http.ResponseWriter, r *http.Request) {\n\tlg := internal.GetRequestLogger(r)\n\tlocalizer := localization.GetLocalizer(r)\n\n\tredir := r.FormValue(\"redir\")\n\tredirURL, err := url.ParseRequestURI(redir)\n\tif err != nil {\n\t\tlg.Error(\"invalid redirect\", \"err\", err)\n\t\ts.respondWithStatus(w, r, localizer.T(\"invalid_redirect\"), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tswitch redirURL.Scheme {\n\tcase \"\", \"http\", \"https\":\n\t\t// allowed\n\tdefault:\n\t\tlg.Error(\"XSS attempt blocked, invalid redirect scheme\", \"scheme\", redirURL.Scheme)\n\t\ts.respondWithStatus(w, r, localizer.T(\"invalid_redirect\"), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// Adjust cookie path if base prefix is not empty\n\tcookiePath := \"/\"\n\tif anubis.BasePrefix != \"\" {\n\t\tcookiePath = strings.TrimSuffix(anubis.BasePrefix, \"/\") + \"/\"\n\t}\n\n\tif _, err := r.Cookie(anubis.TestCookieName); errors.Is(err, http.ErrNoCookie) {\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.ClearCookie(w, CookieOpts{Name: anubis.TestCookieName, Host: r.Host})\n\t\tlg.Warn(\"user has cookies disabled, this is not an anubis bug\")\n\t\ts.respondWithError(w, r, localizer.T(\"cookies_disabled\"))\n\t\treturn\n\t}\n\n\t// used by the path checker rule\n\tr.URL = redirURL\n\n\turlParsed, err := r.URL.Parse(redir)\n\tif err != nil {\n\t\ts.respondWithError(w, r, localizer.T(\"redirect_not_parseable\"))\n\t\treturn\n\t}\n\tif (len(urlParsed.Host) > 0 && len(s.opts.RedirectDomains) != 0 && !slices.Contains(s.opts.RedirectDomains, urlParsed.Host)) || urlParsed.Host != r.URL.Host {\n\t\ts.respondWithError(w, r, localizer.T(\"redirect_domain_not_allowed\"))\n\t\treturn\n\t}\n\n\tcr, rule, err := s.check(r)\n\tif err != nil {\n\t\tlg.Error(\"check failed\", \"err\", err)\n\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s \\\"passChallenge\\\"\", localizer.T(\"internal_server_error\")))\n\t\treturn\n\t}\n\tlg = lg.With(\"check_result\", cr)\n\n\timpl, ok := challenge.Get(rule.Challenge.Algorithm)\n\tif !ok {\n\t\tlg.Error(\"check failed\", \"err\", err)\n\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s: %s\", localizer.T(\"internal_server_error\"), rule.Challenge.Algorithm))\n\t\treturn\n\t}\n\n\tchall, err := s.challengeFor(r)\n\tif err != nil {\n\t\tlg.Error(\"check failed\", \"err\", err)\n\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s: %s\", localizer.T(\"internal_server_error\"), rule.Challenge.Algorithm))\n\t\treturn\n\t}\n\n\tin := &challenge.ValidateInput{\n\t\tChallenge: chall,\n\t\tRule: rule,\n\t\tStore: s.store,\n\t}\n\n\tif err := impl.Validate(r, lg, in); err != nil {\n\t\tfailedValidations.WithLabelValues(rule.Challenge.Algorithm).Inc()\n\t\tvar cerr *challenge.Error\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\tlg.Debug(\"challenge validate call failed\", \"err\", err)\n\n\t\tswitch {\n\t\tcase errors.As(err, &cerr):\n\t\t\tswitch {\n\t\t\tcase errors.Is(err, challenge.ErrFailed):\n\t\t\t\ts.respondWithStatus(w, r, cerr.PublicReason, cerr.StatusCode)\n\t\t\tcase errors.Is(err, challenge.ErrInvalidFormat), errors.Is(err, challenge.ErrMissingField):\n\t\t\t\ts.respondWithError(w, r, cerr.PublicReason)\n\t\t\t}\n\t\t}\n\t}\n\n\t// generate JWT cookie\n\ttokenString, err := s.signJWT(jwt.MapClaims{\n\t\t\"challenge\": chall.ID,\n\t\t\"method\": rule.Challenge.Algorithm,\n\t\t\"policyRule\": rule.Hash(),\n\t\t\"action\": string(cr.Rule),\n\t})\n\tif err != nil {\n\t\tlg.Error(\"failed to sign JWT\", \"err\", err)\n\t\ts.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})\n\t\ts.respondWithError(w, r, localizer.T(\"failed_to_sign_jwt\"))\n\t\treturn\n\t}\n\n\ts.SetCookie(w, CookieOpts{Path: cookiePath, Host: r.Host, Value: tokenString})\n\n\tchallengesValidated.WithLabelValues(rule.Challenge.Algorithm).Inc()\n\tlg.Debug(\"challenge passed, redirecting to app\")\n\thttp.Redirect(w, r, redir, http.StatusFound)\n}\n\nfunc cr(name string, rule config.Rule, weight int) policy.CheckResult {\n\treturn policy.CheckResult{\n\t\tName: name,\n\t\tRule: rule,\n\t\tWeight: weight,\n\t}\n}\n\n// Check evaluates the list of rules, and returns the result\nfunc (s *Server) check(r *http.Request) (policy.CheckResult, *policy.Bot, error) {\n\thost := r.Header.Get(\"X-Real-Ip\")\n\tif host == \"\" {\n\t\treturn decaymap.Zilch[policy.CheckResult](), nil, fmt.Errorf(\"[misconfiguration] X-Real-Ip header is not set\")\n\t}\n\n\taddr := net.ParseIP(host)\n\tif addr == nil {\n\t\treturn decaymap.Zilch[policy.CheckResult](), nil, fmt.Errorf(\"[misconfiguration] %q is not an IP address\", host)\n\t}\n\n\tweight := 0\n\n\tfor _, b := range s.policy.Bots {\n\t\tmatch, err := b.Rules.Check(r)\n\t\tif err != nil {\n\t\t\treturn decaymap.Zilch[policy.CheckResult](), nil, fmt.Errorf(\"can't run check %s: %w\", b.Name, err)\n\t\t}\n\n\t\tif match {\n\t\t\tswitch b.Action {\n\t\t\tcase config.RuleDeny, config.RuleAllow, config.RuleBenchmark, config.RuleChallenge:\n\t\t\t\treturn cr(\"bot/\"+b.Name, b.Action, weight), &b, nil\n\t\t\tcase config.RuleWeigh:\n\t\t\t\tslog.Debug(\"adjusting weight\", \"name\", b.Name, \"delta\", b.Weight.Adjust)\n\t\t\t\tweight += b.Weight.Adjust\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, t := range s.policy.Thresholds {\n\t\tresult, _, err := t.Program.ContextEval(r.Context(), &policy.ThresholdRequest{Weight: weight})\n\t\tif err != nil {\n\t\t\tslog.Error(\"error when evaluating threshold expression\", \"expression\", t.Expression.String(), \"err\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tvar matches bool\n\n\t\tif val, ok := result.(types.Bool); ok {\n\t\t\tmatches = bool(val)\n\t\t}\n\n\t\tif matches {\n\t\t\treturn cr(\"threshold/\"+t.Name, t.Action, weight), &policy.Bot{\n\t\t\t\tChallenge: t.Challenge,\n\t\t\t\tRules: &checker.List{},\n\t\t\t}, nil\n\t\t}\n\t}\n\n\treturn cr(\"default/allow\", config.RuleAllow, weight), &policy.Bot{\n\t\tChallenge: &config.ChallengeRules{\n\t\t\tDifficulty: s.policy.DefaultDifficulty,\n\t\t\tReportAs: s.policy.DefaultDifficulty,\n\t\t\tAlgorithm: config.DefaultAlgorithm,\n\t\t},\n\t\tRules: &checker.List{},\n\t}, nil\n}\n"], ["/anubis/lib/config.go", "package lib\n\nimport (\n\t\"context\"\n\t\"crypto/ed25519\"\n\t\"crypto/rand\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log/slog\"\n\t\"net/http\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/TecharoHQ/anubis/data\"\n\t\"github.com/TecharoHQ/anubis/internal\"\n\t\"github.com/TecharoHQ/anubis/internal/ogtags\"\n\t\"github.com/TecharoHQ/anubis/lib/challenge\"\n\t\"github.com/TecharoHQ/anubis/lib/localization\"\n\t\"github.com/TecharoHQ/anubis/lib/policy\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/web\"\n\t\"github.com/TecharoHQ/anubis/xess\"\n\t\"github.com/a-h/templ\"\n)\n\ntype Options struct {\n\tNext http.Handler\n\tPolicy *policy.ParsedConfig\n\tTarget string\n\tCookieDynamicDomain bool\n\tCookieDomain string\n\tCookieExpiration time.Duration\n\tCookiePartitioned bool\n\tBasePrefix string\n\tWebmasterEmail string\n\tRedirectDomains []string\n\tED25519PrivateKey ed25519.PrivateKey\n\tHS512Secret []byte\n\tStripBasePrefix bool\n\tOpenGraph config.OpenGraph\n\tServeRobotsTXT bool\n\tCookieSecure bool\n}\n\nfunc LoadPoliciesOrDefault(ctx context.Context, fname string, defaultDifficulty int) (*policy.ParsedConfig, error) {\n\tvar fin io.ReadCloser\n\tvar err error\n\n\tif fname != \"\" {\n\t\tfin, err = os.Open(fname)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"can't parse policy file %s: %w\", fname, err)\n\t\t}\n\t} else {\n\t\tfname = \"(data)/botPolicies.yaml\"\n\t\tfin, err = data.BotPolicies.Open(\"botPolicies.yaml\")\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"[unexpected] can't parse builtin policy file %s: %w\", fname, err)\n\t\t}\n\t}\n\n\tdefer func(fin io.ReadCloser) {\n\t\terr := fin.Close()\n\t\tif err != nil {\n\t\t\tslog.Error(\"failed to close policy file\", \"file\", fname, \"err\", err)\n\t\t}\n\t}(fin)\n\n\tanubisPolicy, err := policy.ParseConfig(ctx, fin, fname, defaultDifficulty)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't parse policy file %s: %w\", fname, err)\n\t}\n\tvar validationErrs []error\n\n\tfor _, b := range anubisPolicy.Bots {\n\t\tif _, ok := challenge.Get(b.Challenge.Algorithm); !ok {\n\t\t\tvalidationErrs = append(validationErrs, fmt.Errorf(\"%w %s\", policy.ErrChallengeRuleHasWrongAlgorithm, b.Challenge.Algorithm))\n\t\t}\n\t}\n\n\tif len(validationErrs) != 0 {\n\t\treturn nil, fmt.Errorf(\"can't do final validation of Anubis config: %w\", errors.Join(validationErrs...))\n\t}\n\n\treturn anubisPolicy, err\n}\n\nfunc New(opts Options) (*Server, error) {\n\tif opts.ED25519PrivateKey == nil && opts.HS512Secret == nil {\n\t\tslog.Debug(\"opts.PrivateKey not set, generating a new one\")\n\t\t_, priv, err := ed25519.GenerateKey(rand.Reader)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"lib: can't generate private key: %v\", err)\n\t\t}\n\t\topts.ED25519PrivateKey = priv\n\t}\n\n\tanubis.BasePrefix = opts.BasePrefix\n\n\tresult := &Server{\n\t\tnext: opts.Next,\n\t\ted25519Priv: opts.ED25519PrivateKey,\n\t\ths512Secret: opts.HS512Secret,\n\t\tpolicy: opts.Policy,\n\t\topts: opts,\n\t\tOGTags: ogtags.NewOGTagCache(opts.Target, opts.Policy.OpenGraph, opts.Policy.Store),\n\t\tstore: opts.Policy.Store,\n\t}\n\n\tmux := http.NewServeMux()\n\txess.Mount(mux)\n\n\t// Helper to add global prefix\n\tregisterWithPrefix := func(pattern string, handler http.Handler, method string) {\n\t\tif method != \"\" {\n\t\t\tmethod = method + \" \" // methods must end with a space to register with them\n\t\t}\n\n\t\t// Ensure there's no double slash when concatenating BasePrefix and pattern\n\t\tbasePrefix := strings.TrimSuffix(anubis.BasePrefix, \"/\")\n\t\tprefix := method + basePrefix\n\n\t\t// If pattern doesn't start with a slash, add one\n\t\tif !strings.HasPrefix(pattern, \"/\") {\n\t\t\tpattern = \"/\" + pattern\n\t\t}\n\n\t\tmux.Handle(prefix+pattern, handler)\n\t}\n\n\t// Ensure there's no double slash when concatenating BasePrefix and StaticPath\n\tstripPrefix := strings.TrimSuffix(anubis.BasePrefix, \"/\") + anubis.StaticPath\n\tregisterWithPrefix(anubis.StaticPath, internal.UnchangingCache(internal.NoBrowsing(http.StripPrefix(stripPrefix, http.FileServerFS(web.Static)))), \"\")\n\n\tif opts.ServeRobotsTXT {\n\t\tregisterWithPrefix(\"/robots.txt\", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\thttp.ServeFileFS(w, r, web.Static, \"static/robots.txt\")\n\t\t}), \"GET\")\n\t\tregisterWithPrefix(\"/.well-known/robots.txt\", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\thttp.ServeFileFS(w, r, web.Static, \"static/robots.txt\")\n\t\t}), \"GET\")\n\t}\n\n\tif opts.Policy.Impressum != nil {\n\t\tregisterWithPrefix(anubis.APIPrefix+\"imprint\", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\ttempl.Handler(\n\t\t\t\tweb.Base(opts.Policy.Impressum.Page.Title, opts.Policy.Impressum.Page, opts.Policy.Impressum, localization.GetLocalizer(r)),\n\t\t\t).ServeHTTP(w, r)\n\t\t}), \"GET\")\n\t}\n\n\tregisterWithPrefix(anubis.APIPrefix+\"pass-challenge\", http.HandlerFunc(result.PassChallenge), \"GET\")\n\tregisterWithPrefix(anubis.APIPrefix+\"check\", http.HandlerFunc(result.maybeReverseProxyHttpStatusOnly), \"\")\n\tregisterWithPrefix(\"/\", http.HandlerFunc(result.maybeReverseProxyOrPage), \"\")\n\n\t//goland:noinspection GoBoolExpressions\n\tif anubis.Version == \"devel\" {\n\t\t// make-challenge is only used in tests. Only enable while version is devel\n\t\tregisterWithPrefix(anubis.APIPrefix+\"make-challenge\", http.HandlerFunc(result.MakeChallenge), \"POST\")\n\t}\n\n\tfor _, implKind := range challenge.Methods() {\n\t\timpl, _ := challenge.Get(implKind)\n\t\timpl.Setup(mux)\n\t}\n\n\tresult.mux = mux\n\n\treturn result, nil\n}\n"], ["/anubis/lib/http.go", "package lib\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"net/http\"\n\t\"regexp\"\n\t\"slices\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/TecharoHQ/anubis/internal\"\n\t\"github.com/TecharoHQ/anubis/lib/challenge\"\n\t\"github.com/TecharoHQ/anubis/lib/localization\"\n\t\"github.com/TecharoHQ/anubis/lib/policy\"\n\t\"github.com/TecharoHQ/anubis/web\"\n\t\"github.com/a-h/templ\"\n\t\"github.com/golang-jwt/jwt/v5\"\n\t\"golang.org/x/net/publicsuffix\"\n)\n\nvar domainMatchRegexp = regexp.MustCompile(`^((xn--)?[a-z0-9]+(-[a-z0-9]+)*\\.)+[a-z]{2,}$`)\n\ntype CookieOpts struct {\n\tValue string\n\tHost string\n\tPath string\n\tName string\n\tExpiry time.Duration\n}\n\nfunc (s *Server) SetCookie(w http.ResponseWriter, cookieOpts CookieOpts) {\n\tvar domain = s.opts.CookieDomain\n\tvar name = anubis.CookieName\n\tvar path = \"/\"\n\tif cookieOpts.Name != \"\" {\n\t\tname = cookieOpts.Name\n\t}\n\tif cookieOpts.Path != \"\" {\n\t\tpath = cookieOpts.Path\n\t}\n\tif s.opts.CookieDynamicDomain && domainMatchRegexp.MatchString(cookieOpts.Host) {\n\t\tif etld, err := publicsuffix.EffectiveTLDPlusOne(cookieOpts.Host); err == nil {\n\t\t\tdomain = etld\n\t\t}\n\t}\n\n\tif cookieOpts.Expiry == 0 {\n\t\tcookieOpts.Expiry = s.opts.CookieExpiration\n\t}\n\n\thttp.SetCookie(w, &http.Cookie{\n\t\tName: name,\n\t\tValue: cookieOpts.Value,\n\t\tExpires: time.Now().Add(cookieOpts.Expiry),\n\t\tSameSite: http.SameSiteNoneMode,\n\t\tDomain: domain,\n\t\tSecure: s.opts.CookieSecure,\n\t\tPartitioned: s.opts.CookiePartitioned,\n\t\tPath: path,\n\t})\n}\n\nfunc (s *Server) ClearCookie(w http.ResponseWriter, cookieOpts CookieOpts) {\n\tvar domain = s.opts.CookieDomain\n\tvar name = anubis.CookieName\n\tvar path = \"/\"\n\tif cookieOpts.Name != \"\" {\n\t\tname = cookieOpts.Name\n\t}\n\tif cookieOpts.Path != \"\" {\n\t\tpath = cookieOpts.Path\n\t}\n\tif s.opts.CookieDynamicDomain && domainMatchRegexp.MatchString(cookieOpts.Host) {\n\t\tif etld, err := publicsuffix.EffectiveTLDPlusOne(cookieOpts.Host); err == nil {\n\t\t\tdomain = etld\n\t\t}\n\t}\n\n\thttp.SetCookie(w, &http.Cookie{\n\t\tName: name,\n\t\tValue: \"\",\n\t\tMaxAge: -1,\n\t\tExpires: time.Now().Add(-1 * time.Minute),\n\t\tSameSite: http.SameSiteNoneMode,\n\t\tPartitioned: s.opts.CookiePartitioned,\n\t\tDomain: domain,\n\t\tSecure: s.opts.CookieSecure,\n\t\tPath: path,\n\t})\n}\n\n// https://github.com/oauth2-proxy/oauth2-proxy/blob/master/pkg/upstream/http.go#L124\ntype UnixRoundTripper struct {\n\tTransport *http.Transport\n}\n\n// set bare minimum stuff\nfunc (t UnixRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {\n\treq = req.Clone(req.Context())\n\tif req.Host == \"\" {\n\t\treq.Host = \"localhost\"\n\t}\n\treq.URL.Host = req.Host // proxy error: no Host in request URL\n\treq.URL.Scheme = \"http\" // make http.Transport happy and avoid an infinite recursion\n\treturn t.Transport.RoundTrip(req)\n}\n\nfunc randomChance(n int) bool {\n\treturn rand.Intn(n) == 0\n}\n\nfunc (s *Server) RenderIndex(w http.ResponseWriter, r *http.Request, rule *policy.Bot, returnHTTPStatusOnly bool) {\n\tlocalizer := localization.GetLocalizer(r)\n\n\tif returnHTTPStatusOnly {\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\tw.Write([]byte(localizer.T(\"authorization_required\")))\n\t\treturn\n\t}\n\n\tlg := internal.GetRequestLogger(r)\n\n\tif !strings.Contains(r.Header.Get(\"Accept-Encoding\"), \"gzip\") && randomChance(64) {\n\t\tlg.Error(\"client was given a challenge but does not in fact support gzip compression\")\n\t\ts.respondWithError(w, r, localizer.T(\"client_error_browser\"))\n\t}\n\n\tchallengesIssued.WithLabelValues(\"embedded\").Add(1)\n\tchall, err := s.challengeFor(r)\n\tif err != nil {\n\t\tlg.Error(\"can't get challenge\", \"err\", \"err\")\n\t\ts.ClearCookie(w, CookieOpts{Name: anubis.TestCookieName, Host: r.Host})\n\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s: %s\", localizer.T(\"internal_server_error\"), rule.Challenge.Algorithm))\n\t\treturn\n\t}\n\n\tvar ogTags map[string]string = nil\n\tif s.opts.OpenGraph.Enabled {\n\t\tvar err error\n\t\togTags, err = s.OGTags.GetOGTags(r.Context(), r.URL, r.Host)\n\t\tif err != nil {\n\t\t\tlg.Error(\"failed to get OG tags\", \"err\", err)\n\t\t}\n\t}\n\n\ts.SetCookie(w, CookieOpts{\n\t\tValue: chall.ID,\n\t\tHost: r.Host,\n\t\tPath: \"/\",\n\t\tName: anubis.TestCookieName,\n\t\tExpiry: 30 * time.Minute,\n\t})\n\n\timpl, ok := challenge.Get(rule.Challenge.Algorithm)\n\tif !ok {\n\t\tlg.Error(\"check failed\", \"err\", \"can't get algorithm\", \"algorithm\", rule.Challenge.Algorithm)\n\t\ts.ClearCookie(w, CookieOpts{Name: anubis.TestCookieName, Host: r.Host})\n\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s: %s\", localizer.T(\"internal_server_error\"), rule.Challenge.Algorithm))\n\t\treturn\n\t}\n\n\tin := &challenge.IssueInput{\n\t\tImpressum: s.policy.Impressum,\n\t\tRule: rule,\n\t\tChallenge: chall,\n\t\tOGTags: ogTags,\n\t\tStore: s.store,\n\t}\n\n\tcomponent, err := impl.Issue(r, lg, in)\n\tif err != nil {\n\t\tlg.Error(\"[unexpected] render failed, please open an issue\", \"err\", err) // This is likely a bug in the template. Should never be triggered as CI tests for this.\n\t\ts.respondWithError(w, r, fmt.Sprintf(\"%s \\\"RenderIndex\\\"\", localizer.T(\"internal_server_error\")))\n\t\treturn\n\t}\n\n\thandler := internal.GzipMiddleware(1, internal.NoStoreCache(templ.Handler(\n\t\tcomponent,\n\t\ttempl.WithStatus(s.opts.Policy.StatusCodes.Challenge),\n\t)))\n\thandler.ServeHTTP(w, r)\n}\n\nfunc (s *Server) RenderBench(w http.ResponseWriter, r *http.Request) {\n\tlocalizer := localization.GetLocalizer(r)\n\n\ttempl.Handler(\n\t\tweb.Base(localizer.T(\"benchmarking_anubis\"), web.Bench(localizer), s.policy.Impressum, localizer),\n\t).ServeHTTP(w, r)\n}\n\nfunc (s *Server) respondWithError(w http.ResponseWriter, r *http.Request, message string) {\n\ts.respondWithStatus(w, r, message, http.StatusInternalServerError)\n}\n\nfunc (s *Server) respondWithStatus(w http.ResponseWriter, r *http.Request, msg string, status int) {\n\tlocalizer := localization.GetLocalizer(r)\n\n\ttempl.Handler(web.Base(localizer.T(\"oh_noes\"), web.ErrorPage(msg, s.opts.WebmasterEmail, localizer), s.policy.Impressum, localizer), templ.WithStatus(status)).ServeHTTP(w, r)\n}\n\nfunc (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\ts.mux.ServeHTTP(w, r)\n}\n\nfunc (s *Server) stripBasePrefixFromRequest(r *http.Request) *http.Request {\n\tif !s.opts.StripBasePrefix || s.opts.BasePrefix == \"\" {\n\t\treturn r\n\t}\n\n\tbasePrefix := strings.TrimSuffix(s.opts.BasePrefix, \"/\")\n\tpath := r.URL.Path\n\n\tif !strings.HasPrefix(path, basePrefix) {\n\t\treturn r\n\t}\n\n\ttrimmedPath := strings.TrimPrefix(path, basePrefix)\n\tif trimmedPath == \"\" {\n\t\ttrimmedPath = \"/\"\n\t}\n\n\t// Clone the request and URL\n\treqCopy := r.Clone(r.Context())\n\turlCopy := *r.URL\n\turlCopy.Path = trimmedPath\n\treqCopy.URL = &urlCopy\n\n\treturn reqCopy\n}\n\nfunc (s *Server) ServeHTTPNext(w http.ResponseWriter, r *http.Request) {\n\tif s.next == nil {\n\t\tlocalizer := localization.GetLocalizer(r)\n\n\t\tredir := r.FormValue(\"redir\")\n\t\turlParsed, err := r.URL.Parse(redir)\n\t\tif err != nil {\n\t\t\ts.respondWithStatus(w, r, localizer.T(\"redirect_not_parseable\"), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tif (len(urlParsed.Host) > 0 && len(s.opts.RedirectDomains) != 0 && !slices.Contains(s.opts.RedirectDomains, urlParsed.Host)) || urlParsed.Host != r.URL.Host {\n\t\t\ts.respondWithStatus(w, r, localizer.T(\"redirect_domain_not_allowed\"), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tif redir != \"\" {\n\t\t\thttp.Redirect(w, r, redir, http.StatusFound)\n\t\t\treturn\n\t\t}\n\n\t\ttempl.Handler(\n\t\t\tweb.Base(localizer.T(\"you_are_not_a_bot\"), web.StaticHappy(localizer), s.policy.Impressum, localizer),\n\t\t).ServeHTTP(w, r)\n\t} else {\n\t\trequestsProxied.WithLabelValues(r.Host).Inc()\n\t\tr = s.stripBasePrefixFromRequest(r)\n\t\ts.next.ServeHTTP(w, r)\n\t}\n}\n\nfunc (s *Server) signJWT(claims jwt.MapClaims) (string, error) {\n\tclaims[\"iat\"] = time.Now().Unix()\n\tclaims[\"nbf\"] = time.Now().Add(-1 * time.Minute).Unix()\n\tclaims[\"exp\"] = time.Now().Add(s.opts.CookieExpiration).Unix()\n\n\tif len(s.hs512Secret) == 0 {\n\t\treturn jwt.NewWithClaims(jwt.SigningMethodEdDSA, claims).SignedString(s.ed25519Priv)\n\t} else {\n\t\treturn jwt.NewWithClaims(jwt.SigningMethodHS512, claims).SignedString(s.hs512Secret)\n\t}\n}\n"], ["/anubis/lib/store/bbolt/bbolt.go", "package bbolt\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n\t\"go.etcd.io/bbolt\"\n)\n\n// Sentinel error values used for testing and in admin-visible error messages.\nvar (\n\tErrBucketDoesNotExist = errors.New(\"bbolt: bucket does not exist\")\n\tErrNotExists = errors.New(\"bbolt: value does not exist in store\")\n)\n\n// Store implements store.Interface backed by bbolt[1].\n//\n// In essence, bbolt is a hierarchical key/value store with a twist: every value\n// needs to belong to a bucket. Buckets can contain an infinite number of\n// buckets. As such, Anubis nests values in buckets. Each value in the store\n// is given its own bucket with two keys:\n//\n// 1. data - The raw data, usually in JSON\n// 2. expiry - The expiry time formatted as a time.RFC3339Nano timestamp string\n//\n// When Anubis stores a new bit of data, it creates a new bucket for that value.\n// This allows the cleanup phase to iterate over every bucket in the database and\n// only scan the expiry times without having to decode the entire record.\n//\n// bbolt is not suitable for environments where multiple instance of Anubis need\n// to read from and write to the same backend store. For that, use the valkey\n// storage backend.\n//\n// [1]: https://github.com/etcd-io/bbolt\ntype Store struct {\n\tbdb *bbolt.DB\n}\n\n// Delete a key from the datastore. If the key does not exist, return an error.\nfunc (s *Store) Delete(ctx context.Context, key string) error {\n\treturn s.bdb.Update(func(tx *bbolt.Tx) error {\n\t\tif tx.Bucket([]byte(key)) == nil {\n\t\t\treturn fmt.Errorf(\"%w: %q\", ErrNotExists, key)\n\t\t}\n\n\t\treturn tx.DeleteBucket([]byte(key))\n\t})\n}\n\n// Get a value from the datastore.\n//\n// Because each value is stored in its own bucket with data and expiry keys,\n// two get operations are required:\n//\n// 1. Get the expiry key, parse as time.RFC3339Nano. If the key has expired, run deletion in the background and return a \"key not found\" error.\n// 2. Get the data key, copy into the result byteslice, return it.\nfunc (s *Store) Get(ctx context.Context, key string) ([]byte, error) {\n\tvar result []byte\n\n\tif err := s.bdb.View(func(tx *bbolt.Tx) error {\n\t\titemBucket := tx.Bucket([]byte(key))\n\t\tif itemBucket == nil {\n\t\t\treturn fmt.Errorf(\"%w: %q\", store.ErrNotFound, key)\n\t\t}\n\n\t\texpiryStr := itemBucket.Get([]byte(\"expiry\"))\n\t\tif expiryStr == nil {\n\t\t\treturn fmt.Errorf(\"[unexpected] %w: %q (expiry is nil)\", store.ErrNotFound, key)\n\t\t}\n\n\t\texpiry, err := time.Parse(time.RFC3339Nano, string(expiryStr))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"[unexpected] %w: %w\", store.ErrCantDecode, err)\n\t\t}\n\n\t\tif time.Now().After(expiry) {\n\t\t\tgo s.Delete(context.Background(), key)\n\t\t\treturn fmt.Errorf(\"%w: %q\", store.ErrNotFound, key)\n\t\t}\n\n\t\tdataStr := itemBucket.Get([]byte(\"data\"))\n\t\tif dataStr == nil {\n\t\t\treturn fmt.Errorf(\"[unexpected] %w: %q (data is nil)\", store.ErrNotFound, key)\n\t\t}\n\n\t\tresult = make([]byte, len(dataStr))\n\t\tif n := copy(result, dataStr); n != len(dataStr) {\n\t\t\treturn fmt.Errorf(\"[unexpected] %w: %d bytes copied of %d\", store.ErrCantDecode, n, len(dataStr))\n\t\t}\n\n\t\treturn nil\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn result, nil\n}\n\n// Set a value into the store with a given expiry.\nfunc (s *Store) Set(ctx context.Context, key string, value []byte, expiry time.Duration) error {\n\texpires := time.Now().Add(expiry)\n\n\treturn s.bdb.Update(func(tx *bbolt.Tx) error {\n\t\tvalueBkt, err := tx.CreateBucketIfNotExists([]byte(key))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"%w: %w: %q (create bucket)\", store.ErrCantEncode, err, key)\n\t\t}\n\n\t\tif err := valueBkt.Put([]byte(\"expiry\"), []byte(expires.Format(time.RFC3339Nano))); err != nil {\n\t\t\treturn fmt.Errorf(\"%w: %q (expiry)\", store.ErrCantEncode, key)\n\t\t}\n\n\t\tif err := valueBkt.Put([]byte(\"data\"), value); err != nil {\n\t\t\treturn fmt.Errorf(\"%w: %q (data)\", store.ErrCantEncode, key)\n\t\t}\n\n\t\treturn nil\n\t})\n}\n\nfunc (s *Store) cleanup(ctx context.Context) error {\n\tnow := time.Now()\n\n\treturn s.bdb.Update(func(tx *bbolt.Tx) error {\n\t\treturn tx.ForEach(func(key []byte, valueBkt *bbolt.Bucket) error {\n\t\t\tvar expiry time.Time\n\t\t\tvar err error\n\n\t\t\texpiryStr := valueBkt.Get([]byte(\"expiry\"))\n\t\t\tif expiryStr == nil {\n\t\t\t\tslog.Warn(\"while running cleanup, expiry is not set somehow, file a bug?\", \"key\", string(key))\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\texpiry, err = time.Parse(time.RFC3339Nano, string(expiryStr))\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"[unexpected] %w in bucket %q: %w\", store.ErrCantDecode, string(key), err)\n\t\t\t}\n\n\t\t\tif now.After(expiry) {\n\t\t\t\treturn tx.DeleteBucket(key)\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\t})\n}\n\nfunc (s *Store) cleanupThread(ctx context.Context) {\n\tt := time.NewTicker(time.Hour)\n\tdefer t.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase <-t.C:\n\t\t\tif err := s.cleanup(ctx); err != nil {\n\t\t\t\tslog.Error(\"error during bbolt cleanup\", \"err\", err)\n\t\t\t}\n\t\t}\n\t}\n}\n"], ["/anubis/lib/policy/checker.go", "package policy\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/netip\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com/TecharoHQ/anubis/internal\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/checker\"\n\t\"github.com/gaissmai/bart\"\n)\n\nvar (\n\tErrMisconfiguration = errors.New(\"[unexpected] policy: administrator misconfiguration\")\n)\n\ntype RemoteAddrChecker struct {\n\tprefixTable *bart.Lite\n\thash string\n}\n\nfunc NewRemoteAddrChecker(cidrs []string) (checker.Impl, error) {\n\ttable := new(bart.Lite)\n\n\tfor _, cidr := range cidrs {\n\t\tprefix, err := netip.ParsePrefix(cidr)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"%w: range %s not parsing: %w\", ErrMisconfiguration, cidr, err)\n\t\t}\n\n\t\ttable.Insert(prefix)\n\t}\n\n\treturn &RemoteAddrChecker{\n\t\tprefixTable: table,\n\t\thash: internal.FastHash(strings.Join(cidrs, \",\")),\n\t}, nil\n}\n\nfunc (rac *RemoteAddrChecker) Check(r *http.Request) (bool, error) {\n\thost := r.Header.Get(\"X-Real-Ip\")\n\tif host == \"\" {\n\t\treturn false, fmt.Errorf(\"%w: header X-Real-Ip is not set\", ErrMisconfiguration)\n\t}\n\n\taddr, err := netip.ParseAddr(host)\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"%w: %s is not an IP address: %w\", ErrMisconfiguration, host, err)\n\t}\n\n\treturn rac.prefixTable.Contains(addr), nil\n}\n\nfunc (rac *RemoteAddrChecker) Hash() string {\n\treturn rac.hash\n}\n\ntype HeaderMatchesChecker struct {\n\theader string\n\tregexp *regexp.Regexp\n\thash string\n}\n\nfunc NewUserAgentChecker(rexStr string) (checker.Impl, error) {\n\treturn NewHeaderMatchesChecker(\"User-Agent\", rexStr)\n}\n\nfunc NewHeaderMatchesChecker(header, rexStr string) (checker.Impl, error) {\n\trex, err := regexp.Compile(strings.TrimSpace(rexStr))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: regex %s failed parse: %w\", ErrMisconfiguration, rexStr, err)\n\t}\n\treturn &HeaderMatchesChecker{strings.TrimSpace(header), rex, internal.FastHash(header + \": \" + rexStr)}, nil\n}\n\nfunc (hmc *HeaderMatchesChecker) Check(r *http.Request) (bool, error) {\n\tif hmc.regexp.MatchString(r.Header.Get(hmc.header)) {\n\t\treturn true, nil\n\t}\n\n\treturn false, nil\n}\n\nfunc (hmc *HeaderMatchesChecker) Hash() string {\n\treturn hmc.hash\n}\n\ntype PathChecker struct {\n\tregexp *regexp.Regexp\n\thash string\n}\n\nfunc NewPathChecker(rexStr string) (checker.Impl, error) {\n\trex, err := regexp.Compile(strings.TrimSpace(rexStr))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: regex %s failed parse: %w\", ErrMisconfiguration, rexStr, err)\n\t}\n\treturn &PathChecker{rex, internal.FastHash(rexStr)}, nil\n}\n\nfunc (pc *PathChecker) Check(r *http.Request) (bool, error) {\n\tif pc.regexp.MatchString(r.URL.Path) {\n\t\treturn true, nil\n\t}\n\n\treturn false, nil\n}\n\nfunc (pc *PathChecker) Hash() string {\n\treturn pc.hash\n}\n\nfunc NewHeaderExistsChecker(key string) checker.Impl {\n\treturn headerExistsChecker{strings.TrimSpace(key)}\n}\n\ntype headerExistsChecker struct {\n\theader string\n}\n\nfunc (hec headerExistsChecker) Check(r *http.Request) (bool, error) {\n\tif r.Header.Get(hec.header) != \"\" {\n\t\treturn true, nil\n\t}\n\n\treturn false, nil\n}\n\nfunc (hec headerExistsChecker) Hash() string {\n\treturn internal.FastHash(hec.header)\n}\n\nfunc NewHeadersChecker(headermap map[string]string) (checker.Impl, error) {\n\tvar result checker.List\n\tvar errs []error\n\n\tfor key, rexStr := range headermap {\n\t\tif rexStr == \".*\" {\n\t\t\tresult = append(result, headerExistsChecker{strings.TrimSpace(key)})\n\t\t\tcontinue\n\t\t}\n\n\t\trex, err := regexp.Compile(strings.TrimSpace(rexStr))\n\t\tif err != nil {\n\t\t\terrs = append(errs, fmt.Errorf(\"while compiling header %s regex %s: %w\", key, rexStr, err))\n\t\t\tcontinue\n\t\t}\n\n\t\tresult = append(result, &HeaderMatchesChecker{key, rex, internal.FastHash(key + \": \" + rexStr)})\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn nil, errors.Join(errs...)\n\t}\n\n\treturn result, nil\n}\n"], ["/anubis/lib/policy/config/config.go", "package config\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/fs\"\n\t\"net\"\n\t\"net/http\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis/data\"\n\t\"k8s.io/apimachinery/pkg/util/yaml\"\n)\n\nvar (\n\tErrNoBotRulesDefined = errors.New(\"config: must define at least one (1) bot rule\")\n\tErrBotMustHaveName = errors.New(\"config.Bot: must set name\")\n\tErrBotMustHaveUserAgentOrPath = errors.New(\"config.Bot: must set either user_agent_regex, path_regex, headers_regex, or remote_addresses\")\n\tErrBotMustHaveUserAgentOrPathNotBoth = errors.New(\"config.Bot: must set either user_agent_regex, path_regex, and not both\")\n\tErrUnknownAction = errors.New(\"config.Bot: unknown action\")\n\tErrInvalidUserAgentRegex = errors.New(\"config.Bot: invalid user agent regex\")\n\tErrInvalidPathRegex = errors.New(\"config.Bot: invalid path regex\")\n\tErrInvalidHeadersRegex = errors.New(\"config.Bot: invalid headers regex\")\n\tErrInvalidCIDR = errors.New(\"config.Bot: invalid CIDR\")\n\tErrRegexEndsWithNewline = errors.New(\"config.Bot: regular expression ends with newline (try >- instead of > in yaml)\")\n\tErrInvalidImportStatement = errors.New(\"config.ImportStatement: invalid source file\")\n\tErrCantSetBotAndImportValuesAtOnce = errors.New(\"config.BotOrImport: can't set bot rules and import values at the same time\")\n\tErrMustSetBotOrImportRules = errors.New(\"config.BotOrImport: rule definition is invalid, you must set either bot rules or an import statement, not both\")\n\tErrStatusCodeNotValid = errors.New(\"config.StatusCode: status code not valid, must be between 100 and 599\")\n)\n\ntype Rule string\n\nconst (\n\tRuleUnknown Rule = \"\"\n\tRuleAllow Rule = \"ALLOW\"\n\tRuleDeny Rule = \"DENY\"\n\tRuleChallenge Rule = \"CHALLENGE\"\n\tRuleWeigh Rule = \"WEIGH\"\n\tRuleBenchmark Rule = \"DEBUG_BENCHMARK\"\n)\n\nfunc (r Rule) Valid() error {\n\tswitch r {\n\tcase RuleAllow, RuleDeny, RuleChallenge, RuleWeigh, RuleBenchmark:\n\t\treturn nil\n\tdefault:\n\t\treturn ErrUnknownAction\n\t}\n}\n\nconst DefaultAlgorithm = \"fast\"\n\ntype BotConfig struct {\n\tUserAgentRegex *string `json:\"user_agent_regex,omitempty\" yaml:\"user_agent_regex,omitempty\"`\n\tPathRegex *string `json:\"path_regex,omitempty\" yaml:\"path_regex,omitempty\"`\n\tHeadersRegex map[string]string `json:\"headers_regex,omitempty\" yaml:\"headers_regex,omitempty\"`\n\tExpression *ExpressionOrList `json:\"expression,omitempty\" yaml:\"expression,omitempty\"`\n\tChallenge *ChallengeRules `json:\"challenge,omitempty\" yaml:\"challenge,omitempty\"`\n\tWeight *Weight `json:\"weight,omitempty\" yaml:\"weight,omitempty\"`\n\tName string `json:\"name\" yaml:\"name\"`\n\tAction Rule `json:\"action\" yaml:\"action\"`\n\tRemoteAddr []string `json:\"remote_addresses,omitempty\" yaml:\"remote_addresses,omitempty\"`\n\n\t// Thoth features\n\tGeoIP *GeoIP `json:\"geoip,omitempty\"`\n\tASNs *ASNs `json:\"asns,omitempty\"`\n}\n\nfunc (b BotConfig) Zero() bool {\n\tfor _, cond := range []bool{\n\t\tb.Name != \"\",\n\t\tb.UserAgentRegex != nil,\n\t\tb.PathRegex != nil,\n\t\tlen(b.HeadersRegex) != 0,\n\t\tb.Action != \"\",\n\t\tlen(b.RemoteAddr) != 0,\n\t\tb.Challenge != nil,\n\t\tb.GeoIP != nil,\n\t\tb.ASNs != nil,\n\t} {\n\t\tif cond {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc (b *BotConfig) Valid() error {\n\tvar errs []error\n\n\tif b.Name == \"\" {\n\t\terrs = append(errs, ErrBotMustHaveName)\n\t}\n\n\tallFieldsEmpty := b.UserAgentRegex == nil &&\n\t\tb.PathRegex == nil &&\n\t\tlen(b.RemoteAddr) == 0 &&\n\t\tlen(b.HeadersRegex) == 0 &&\n\t\tb.ASNs == nil &&\n\t\tb.GeoIP == nil\n\n\tif allFieldsEmpty && b.Expression == nil {\n\t\terrs = append(errs, ErrBotMustHaveUserAgentOrPath)\n\t}\n\n\tif b.UserAgentRegex != nil && b.PathRegex != nil {\n\t\terrs = append(errs, ErrBotMustHaveUserAgentOrPathNotBoth)\n\t}\n\n\tif b.UserAgentRegex != nil {\n\t\tif strings.HasSuffix(*b.UserAgentRegex, \"\\n\") {\n\t\t\terrs = append(errs, fmt.Errorf(\"%w: user agent regex: %q\", ErrRegexEndsWithNewline, *b.UserAgentRegex))\n\t\t}\n\n\t\tif _, err := regexp.Compile(*b.UserAgentRegex); err != nil {\n\t\t\terrs = append(errs, ErrInvalidUserAgentRegex, err)\n\t\t}\n\t}\n\n\tif b.PathRegex != nil {\n\t\tif strings.HasSuffix(*b.PathRegex, \"\\n\") {\n\t\t\terrs = append(errs, fmt.Errorf(\"%w: path regex: %q\", ErrRegexEndsWithNewline, *b.PathRegex))\n\t\t}\n\n\t\tif _, err := regexp.Compile(*b.PathRegex); err != nil {\n\t\t\terrs = append(errs, ErrInvalidPathRegex, err)\n\t\t}\n\t}\n\n\tif len(b.HeadersRegex) > 0 {\n\t\tfor name, expr := range b.HeadersRegex {\n\t\t\tif name == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif strings.HasSuffix(expr, \"\\n\") {\n\t\t\t\terrs = append(errs, fmt.Errorf(\"%w: header %s regex: %q\", ErrRegexEndsWithNewline, name, expr))\n\t\t\t}\n\n\t\t\tif _, err := regexp.Compile(expr); err != nil {\n\t\t\t\terrs = append(errs, ErrInvalidHeadersRegex, err)\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(b.RemoteAddr) > 0 {\n\t\tfor _, cidr := range b.RemoteAddr {\n\t\t\tif _, _, err := net.ParseCIDR(cidr); err != nil {\n\t\t\t\terrs = append(errs, ErrInvalidCIDR, err)\n\t\t\t}\n\t\t}\n\t}\n\n\tif b.Expression != nil {\n\t\tif err := b.Expression.Valid(); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\tswitch b.Action {\n\tcase RuleAllow, RuleBenchmark, RuleChallenge, RuleDeny, RuleWeigh:\n\t\t// okay\n\tdefault:\n\t\terrs = append(errs, fmt.Errorf(\"%w: %q\", ErrUnknownAction, b.Action))\n\t}\n\n\tif b.Action == RuleChallenge && b.Challenge != nil {\n\t\tif err := b.Challenge.Valid(); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\tif b.Action == RuleWeigh && b.Weight == nil {\n\t\tb.Weight = &Weight{Adjust: 5}\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"config: bot entry for %q is not valid:\\n%w\", b.Name, errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n\ntype ChallengeRules struct {\n\tAlgorithm string `json:\"algorithm,omitempty\" yaml:\"algorithm,omitempty\"`\n\tDifficulty int `json:\"difficulty,omitempty\" yaml:\"difficulty,omitempty\"`\n\tReportAs int `json:\"report_as,omitempty\" yaml:\"report_as,omitempty\"`\n}\n\nvar (\n\tErrChallengeDifficultyTooLow = errors.New(\"config.ChallengeRules: difficulty is too low (must be >= 1)\")\n\tErrChallengeDifficultyTooHigh = errors.New(\"config.ChallengeRules: difficulty is too high (must be <= 64)\")\n\tErrChallengeMustHaveAlgorithm = errors.New(\"config.ChallengeRules: must have algorithm name set\")\n)\n\nfunc (cr ChallengeRules) Valid() error {\n\tvar errs []error\n\n\tif cr.Algorithm == \"\" {\n\t\terrs = append(errs, ErrChallengeMustHaveAlgorithm)\n\t}\n\n\tif cr.Difficulty < 1 {\n\t\terrs = append(errs, fmt.Errorf(\"%w, got: %d\", ErrChallengeDifficultyTooLow, cr.Difficulty))\n\t}\n\n\tif cr.Difficulty > 64 {\n\t\terrs = append(errs, fmt.Errorf(\"%w, got: %d\", ErrChallengeDifficultyTooHigh, cr.Difficulty))\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"config: challenge rules entry is not valid:\\n%w\", errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n\ntype ImportStatement struct {\n\tImport string `json:\"import\"`\n\tBots []BotConfig\n}\n\nfunc (is *ImportStatement) open() (fs.File, error) {\n\tif strings.HasPrefix(is.Import, \"(data)/\") {\n\t\tfname := strings.TrimPrefix(is.Import, \"(data)/\")\n\t\tfin, err := data.BotPolicies.Open(fname)\n\t\treturn fin, err\n\t}\n\n\treturn os.Open(is.Import)\n}\n\nfunc (is *ImportStatement) load() error {\n\tfin, err := is.open()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%w: %s: %w\", ErrInvalidImportStatement, is.Import, err)\n\t}\n\tdefer fin.Close()\n\n\tvar imported []BotOrImport\n\tvar result []BotConfig\n\n\tif err := yaml.NewYAMLToJSONDecoder(fin).Decode(&imported); err != nil {\n\t\treturn fmt.Errorf(\"can't parse %s: %w\", is.Import, err)\n\t}\n\n\tvar errs []error\n\n\tfor _, b := range imported {\n\t\tif err := b.Valid(); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\n\t\tif b.ImportStatement != nil {\n\t\t\tresult = append(result, b.ImportStatement.Bots...)\n\t\t}\n\n\t\tif b.BotConfig != nil {\n\t\t\tresult = append(result, *b.BotConfig)\n\t\t}\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"config %s is not valid:\\n%w\", is.Import, errors.Join(errs...))\n\t}\n\n\tis.Bots = result\n\n\treturn nil\n}\n\nfunc (is *ImportStatement) Valid() error {\n\treturn is.load()\n}\n\ntype BotOrImport struct {\n\t*BotConfig `json:\",inline\"`\n\t*ImportStatement `json:\",inline\"`\n}\n\nfunc (boi *BotOrImport) Valid() error {\n\tif boi.BotConfig != nil && boi.ImportStatement != nil {\n\t\treturn ErrCantSetBotAndImportValuesAtOnce\n\t}\n\n\tif boi.BotConfig != nil {\n\t\treturn boi.BotConfig.Valid()\n\t}\n\n\tif boi.ImportStatement != nil {\n\t\treturn boi.ImportStatement.Valid()\n\t}\n\n\treturn ErrMustSetBotOrImportRules\n}\n\ntype StatusCodes struct {\n\tChallenge int `json:\"CHALLENGE\"`\n\tDeny int `json:\"DENY\"`\n}\n\nfunc (sc StatusCodes) Valid() error {\n\tvar errs []error\n\n\tif sc.Challenge == 0 || (sc.Challenge < 100 && sc.Challenge >= 599) {\n\t\terrs = append(errs, fmt.Errorf(\"%w: challenge is %d\", ErrStatusCodeNotValid, sc.Challenge))\n\t}\n\n\tif sc.Deny == 0 || (sc.Deny < 100 && sc.Deny >= 599) {\n\t\terrs = append(errs, fmt.Errorf(\"%w: deny is %d\", ErrStatusCodeNotValid, sc.Deny))\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"status codes not valid:\\n%w\", errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n\ntype fileConfig struct {\n\tBots []BotOrImport `json:\"bots\"`\n\tDNSBL bool `json:\"dnsbl\"`\n\tOpenGraph openGraphFileConfig `json:\"openGraph,omitempty\"`\n\tImpressum *Impressum `json:\"impressum,omitempty\"`\n\tStatusCodes StatusCodes `json:\"status_codes\"`\n\tStore *Store `json:\"store\"`\n\tThresholds []Threshold `json:\"thresholds\"`\n}\n\nfunc (c *fileConfig) Valid() error {\n\tvar errs []error\n\n\tif len(c.Bots) == 0 {\n\t\terrs = append(errs, ErrNoBotRulesDefined)\n\t}\n\n\tfor i, b := range c.Bots {\n\t\tif err := b.Valid(); err != nil {\n\t\t\terrs = append(errs, fmt.Errorf(\"bot %d: %w\", i, err))\n\t\t}\n\t}\n\n\tif c.OpenGraph.Enabled {\n\t\tif err := c.OpenGraph.Valid(); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\tif err := c.StatusCodes.Valid(); err != nil {\n\t\terrs = append(errs, err)\n\t}\n\n\tfor i, t := range c.Thresholds {\n\t\tif err := t.Valid(); err != nil {\n\t\t\terrs = append(errs, fmt.Errorf(\"threshold %d: %w\", i, err))\n\t\t}\n\t}\n\n\tif c.Store != nil {\n\t\tif err := c.Store.Valid(); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"config is not valid:\\n%w\", errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n\nfunc Load(fin io.Reader, fname string) (*Config, error) {\n\tc := &fileConfig{\n\t\tStatusCodes: StatusCodes{\n\t\t\tChallenge: http.StatusOK,\n\t\t\tDeny: http.StatusOK,\n\t\t},\n\t\tStore: &Store{\n\t\t\tBackend: \"memory\",\n\t\t},\n\t}\n\n\tif err := yaml.NewYAMLToJSONDecoder(fin).Decode(&c); err != nil {\n\t\treturn nil, fmt.Errorf(\"can't parse policy config YAML %s: %w\", fname, err)\n\t}\n\n\tif err := c.Valid(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult := &Config{\n\t\tDNSBL: c.DNSBL,\n\t\tOpenGraph: OpenGraph{\n\t\t\tEnabled: c.OpenGraph.Enabled,\n\t\t\tConsiderHost: c.OpenGraph.ConsiderHost,\n\t\t\tOverride: c.OpenGraph.Override,\n\t\t},\n\t\tStatusCodes: c.StatusCodes,\n\t\tStore: c.Store,\n\t}\n\n\tif c.OpenGraph.TimeToLive != \"\" {\n\t\t// XXX(Xe): already validated in Valid()\n\t\togTTL, _ := time.ParseDuration(c.OpenGraph.TimeToLive)\n\t\tresult.OpenGraph.TimeToLive = ogTTL\n\t}\n\n\tvar validationErrs []error\n\n\tfor _, boi := range c.Bots {\n\t\tif boi.ImportStatement != nil {\n\t\t\tif err := boi.load(); err != nil {\n\t\t\t\tvalidationErrs = append(validationErrs, err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tresult.Bots = append(result.Bots, boi.ImportStatement.Bots...)\n\t\t}\n\n\t\tif boi.BotConfig != nil {\n\t\t\tif err := boi.BotConfig.Valid(); err != nil {\n\t\t\t\tvalidationErrs = append(validationErrs, err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tresult.Bots = append(result.Bots, *boi.BotConfig)\n\t\t}\n\t}\n\n\tif c.Impressum != nil {\n\t\tif err := c.Impressum.Valid(); err != nil {\n\t\t\tvalidationErrs = append(validationErrs, err)\n\t\t}\n\n\t\tresult.Impressum = c.Impressum\n\t}\n\n\tif len(c.Thresholds) == 0 {\n\t\tc.Thresholds = DefaultThresholds\n\t}\n\n\tfor _, t := range c.Thresholds {\n\t\tif err := t.Valid(); err != nil {\n\t\t\tvalidationErrs = append(validationErrs, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tresult.Thresholds = append(result.Thresholds, t)\n\t}\n\n\tif len(validationErrs) > 0 {\n\t\treturn nil, fmt.Errorf(\"errors validating policy config %s: %w\", fname, errors.Join(validationErrs...))\n\t}\n\n\treturn result, nil\n}\n\ntype Config struct {\n\tBots []BotConfig\n\tThresholds []Threshold\n\tDNSBL bool\n\tImpressum *Impressum\n\tOpenGraph OpenGraph\n\tStatusCodes StatusCodes\n\tStore *Store\n}\n\nfunc (c Config) Valid() error {\n\tvar errs []error\n\n\tif len(c.Bots) == 0 {\n\t\terrs = append(errs, ErrNoBotRulesDefined)\n\t}\n\n\tfor _, b := range c.Bots {\n\t\tif err := b.Valid(); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"config is not valid:\\n%w\", errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n"], ["/anubis/lib/challenge/proofofwork/proofofwork.go", "package proofofwork\n\nimport (\n\t\"crypto/subtle\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net/http\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com/TecharoHQ/anubis/internal\"\n\tchall \"github.com/TecharoHQ/anubis/lib/challenge\"\n\t\"github.com/TecharoHQ/anubis/lib/localization\"\n\t\"github.com/TecharoHQ/anubis/web\"\n\t\"github.com/a-h/templ\"\n)\n\nfunc init() {\n\tchall.Register(\"fast\", &Impl{Algorithm: \"fast\"})\n\tchall.Register(\"slow\", &Impl{Algorithm: \"slow\"})\n}\n\ntype Impl struct {\n\tAlgorithm string\n}\n\nfunc (i *Impl) Setup(mux *http.ServeMux) {\n\t/* no implementation required */\n}\n\nfunc (i *Impl) Issue(r *http.Request, lg *slog.Logger, in *chall.IssueInput) (templ.Component, error) {\n\tloc := localization.GetLocalizer(r)\n\tcomponent, err := web.BaseWithChallengeAndOGTags(loc.T(\"making_sure_not_bot\"), web.Index(loc), in.Impressum, in.Challenge.RandomData, in.Rule.Challenge, in.OGTags, loc)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't render page: %w\", err)\n\t}\n\n\treturn component, nil\n}\n\nfunc (i *Impl) Validate(r *http.Request, lg *slog.Logger, in *chall.ValidateInput) error {\n\trule := in.Rule\n\tchallenge := in.Challenge.RandomData\n\n\tnonceStr := r.FormValue(\"nonce\")\n\tif nonceStr == \"\" {\n\t\treturn chall.NewError(\"validate\", \"invalid response\", fmt.Errorf(\"%w nonce\", chall.ErrMissingField))\n\t}\n\n\tnonce, err := strconv.Atoi(nonceStr)\n\tif err != nil {\n\t\treturn chall.NewError(\"validate\", \"invalid response\", fmt.Errorf(\"%w: nonce: %w\", chall.ErrInvalidFormat, err))\n\n\t}\n\n\telapsedTimeStr := r.FormValue(\"elapsedTime\")\n\tif elapsedTimeStr == \"\" {\n\t\treturn chall.NewError(\"validate\", \"invalid response\", fmt.Errorf(\"%w elapsedTime\", chall.ErrMissingField))\n\t}\n\n\telapsedTime, err := strconv.ParseFloat(elapsedTimeStr, 64)\n\tif err != nil {\n\t\treturn chall.NewError(\"validate\", \"invalid response\", fmt.Errorf(\"%w: elapsedTime: %w\", chall.ErrInvalidFormat, err))\n\t}\n\n\tresponse := r.FormValue(\"response\")\n\tif response == \"\" {\n\t\treturn chall.NewError(\"validate\", \"invalid response\", fmt.Errorf(\"%w response\", chall.ErrMissingField))\n\t}\n\n\tcalcString := fmt.Sprintf(\"%s%d\", challenge, nonce)\n\tcalculated := internal.SHA256sum(calcString)\n\n\tif subtle.ConstantTimeCompare([]byte(response), []byte(calculated)) != 1 {\n\t\treturn chall.NewError(\"validate\", \"invalid response\", fmt.Errorf(\"%w: wanted response %s but got %s\", chall.ErrFailed, calculated, response))\n\t}\n\n\t// compare the leading zeroes\n\tif !strings.HasPrefix(response, strings.Repeat(\"0\", rule.Challenge.Difficulty)) {\n\t\treturn chall.NewError(\"validate\", \"invalid response\", fmt.Errorf(\"%w: wanted %d leading zeros but got %s\", chall.ErrFailed, rule.Challenge.Difficulty, response))\n\t}\n\n\tlg.Debug(\"challenge took\", \"elapsedTime\", elapsedTime)\n\tchall.TimeTaken.WithLabelValues(i.Algorithm).Observe(elapsedTime)\n\n\treturn nil\n}\n"], ["/anubis/lib/policy/policy.go", "package policy\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log/slog\"\n\t\"sync/atomic\"\n\n\t\"github.com/TecharoHQ/anubis/lib/policy/checker\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n\t\"github.com/TecharoHQ/anubis/lib/thoth\"\n\t\"github.com/prometheus/client_golang/prometheus\"\n\t\"github.com/prometheus/client_golang/prometheus/promauto\"\n\n\t_ \"github.com/TecharoHQ/anubis/lib/store/all\"\n)\n\nvar (\n\tApplications = promauto.NewCounterVec(prometheus.CounterOpts{\n\t\tName: \"anubis_policy_results\",\n\t\tHelp: \"The results of each policy rule\",\n\t}, []string{\"rule\", \"action\"})\n\n\tErrChallengeRuleHasWrongAlgorithm = errors.New(\"config.Bot.ChallengeRules: algorithm is invalid\")\n\twarnedAboutThresholds = &atomic.Bool{}\n)\n\ntype ParsedConfig struct {\n\torig *config.Config\n\n\tBots []Bot\n\tThresholds []*Threshold\n\tDNSBL bool\n\tImpressum *config.Impressum\n\tOpenGraph config.OpenGraph\n\tDefaultDifficulty int\n\tStatusCodes config.StatusCodes\n\tStore store.Interface\n}\n\nfunc newParsedConfig(orig *config.Config) *ParsedConfig {\n\treturn &ParsedConfig{\n\t\torig: orig,\n\t\tOpenGraph: orig.OpenGraph,\n\t\tStatusCodes: orig.StatusCodes,\n\t}\n}\n\nfunc ParseConfig(ctx context.Context, fin io.Reader, fname string, defaultDifficulty int) (*ParsedConfig, error) {\n\tc, err := config.Load(fin, fname)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar validationErrs []error\n\n\ttc, hasThothClient := thoth.FromContext(ctx)\n\n\tresult := newParsedConfig(c)\n\tresult.DefaultDifficulty = defaultDifficulty\n\n\tfor _, b := range c.Bots {\n\t\tif berr := b.Valid(); berr != nil {\n\t\t\tvalidationErrs = append(validationErrs, berr)\n\t\t\tcontinue\n\t\t}\n\n\t\tparsedBot := Bot{\n\t\t\tName: b.Name,\n\t\t\tAction: b.Action,\n\t\t}\n\n\t\tcl := checker.List{}\n\n\t\tif len(b.RemoteAddr) > 0 {\n\t\t\tc, err := NewRemoteAddrChecker(b.RemoteAddr)\n\t\t\tif err != nil {\n\t\t\t\tvalidationErrs = append(validationErrs, fmt.Errorf(\"while processing rule %s remote addr set: %w\", b.Name, err))\n\t\t\t} else {\n\t\t\t\tcl = append(cl, c)\n\t\t\t}\n\t\t}\n\n\t\tif b.UserAgentRegex != nil {\n\t\t\tc, err := NewUserAgentChecker(*b.UserAgentRegex)\n\t\t\tif err != nil {\n\t\t\t\tvalidationErrs = append(validationErrs, fmt.Errorf(\"while processing rule %s user agent regex: %w\", b.Name, err))\n\t\t\t} else {\n\t\t\t\tcl = append(cl, c)\n\t\t\t}\n\t\t}\n\n\t\tif b.PathRegex != nil {\n\t\t\tc, err := NewPathChecker(*b.PathRegex)\n\t\t\tif err != nil {\n\t\t\t\tvalidationErrs = append(validationErrs, fmt.Errorf(\"while processing rule %s path regex: %w\", b.Name, err))\n\t\t\t} else {\n\t\t\t\tcl = append(cl, c)\n\t\t\t}\n\t\t}\n\n\t\tif len(b.HeadersRegex) > 0 {\n\t\t\tc, err := NewHeadersChecker(b.HeadersRegex)\n\t\t\tif err != nil {\n\t\t\t\tvalidationErrs = append(validationErrs, fmt.Errorf(\"while processing rule %s headers regex map: %w\", b.Name, err))\n\t\t\t} else {\n\t\t\t\tcl = append(cl, c)\n\t\t\t}\n\t\t}\n\n\t\tif b.Expression != nil {\n\t\t\tc, err := NewCELChecker(b.Expression)\n\t\t\tif err != nil {\n\t\t\t\tvalidationErrs = append(validationErrs, fmt.Errorf(\"while processing rule %s expressions: %w\", b.Name, err))\n\t\t\t} else {\n\t\t\t\tcl = append(cl, c)\n\t\t\t}\n\t\t}\n\n\t\tif b.ASNs != nil {\n\t\t\tif !hasThothClient {\n\t\t\t\tslog.Warn(\"You have specified a Thoth specific check but you have no Thoth client configured. Please read https://anubis.techaro.lol/docs/admin/thoth for more information\", \"check\", \"asn\", \"settings\", b.ASNs)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tcl = append(cl, tc.ASNCheckerFor(b.ASNs.Match))\n\t\t}\n\n\t\tif b.GeoIP != nil {\n\t\t\tif !hasThothClient {\n\t\t\t\tslog.Warn(\"You have specified a Thoth specific check but you have no Thoth client configured. Please read https://anubis.techaro.lol/docs/admin/thoth for more information\", \"check\", \"geoip\", \"settings\", b.GeoIP)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tcl = append(cl, tc.GeoIPCheckerFor(b.GeoIP.Countries))\n\t\t}\n\n\t\tif b.Challenge == nil {\n\t\t\tparsedBot.Challenge = &config.ChallengeRules{\n\t\t\t\tDifficulty: defaultDifficulty,\n\t\t\t\tReportAs: defaultDifficulty,\n\t\t\t\tAlgorithm: \"fast\",\n\t\t\t}\n\t\t} else {\n\t\t\tparsedBot.Challenge = b.Challenge\n\t\t\tif parsedBot.Challenge.Algorithm == \"\" {\n\t\t\t\tparsedBot.Challenge.Algorithm = config.DefaultAlgorithm\n\t\t\t}\n\t\t}\n\n\t\tif b.Weight != nil {\n\t\t\tparsedBot.Weight = b.Weight\n\t\t}\n\n\t\tresult.Impressum = c.Impressum\n\n\t\tparsedBot.Rules = cl\n\n\t\tresult.Bots = append(result.Bots, parsedBot)\n\t}\n\n\tfor _, t := range c.Thresholds {\n\t\tif t.Name == \"legacy-anubis-behaviour\" && t.Expression.String() == \"true\" {\n\t\t\tif !warnedAboutThresholds.Load() {\n\t\t\t\tslog.Warn(\"configuration file does not contain thresholds, see docs for details on how to upgrade\", \"fname\", fname, \"docs_url\", \"https://anubis.techaro.lol/docs/admin/configuration/thresholds/\")\n\t\t\t\twarnedAboutThresholds.Store(true)\n\t\t\t}\n\n\t\t\tt.Challenge.Difficulty = defaultDifficulty\n\t\t\tt.Challenge.ReportAs = defaultDifficulty\n\t\t}\n\n\t\tthreshold, err := ParsedThresholdFromConfig(t)\n\t\tif err != nil {\n\t\t\tvalidationErrs = append(validationErrs, fmt.Errorf(\"can't compile threshold config for %s: %w\", t.Name, err))\n\t\t\tcontinue\n\t\t}\n\n\t\tresult.Thresholds = append(result.Thresholds, threshold)\n\t}\n\n\tstFac, ok := store.Get(c.Store.Backend)\n\tswitch ok {\n\tcase true:\n\t\tstore, err := stFac.Build(ctx, c.Store.Parameters)\n\t\tif err != nil {\n\t\t\tvalidationErrs = append(validationErrs, err)\n\t\t} else {\n\t\t\tresult.Store = store\n\t\t}\n\tcase false:\n\t\tvalidationErrs = append(validationErrs, config.ErrUnknownStoreBackend)\n\t}\n\n\tif len(validationErrs) > 0 {\n\t\treturn nil, fmt.Errorf(\"errors validating policy config JSON %s: %w\", fname, errors.Join(validationErrs...))\n\t}\n\n\tresult.DNSBL = c.DNSBL\n\n\treturn result, nil\n}\n"], ["/anubis/cmd/robots2policy/main.go", "package main\n\nimport (\n\t\"bufio\"\n\t\"encoding/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\n\t\"sigs.k8s.io/yaml\"\n)\n\nvar (\n\tinputFile = flag.String(\"input\", \"\", \"path to robots.txt file (use - for stdin)\")\n\toutputFile = flag.String(\"output\", \"\", \"output file path (use - for stdout, defaults to stdout)\")\n\toutputFormat = flag.String(\"format\", \"yaml\", \"output format: yaml or json\")\n\tbaseAction = flag.String(\"action\", \"CHALLENGE\", \"default action for disallowed paths: ALLOW, DENY, CHALLENGE, WEIGH\")\n\tcrawlDelay = flag.Int(\"crawl-delay-weight\", 0, \"if > 0, add weight adjustment for crawl-delay (difficulty adjustment)\")\n\tpolicyName = flag.String(\"name\", \"robots-txt-policy\", \"name for the generated policy\")\n\tuserAgentDeny = flag.String(\"deny-user-agents\", \"DENY\", \"action for specifically blocked user agents: DENY, CHALLENGE\")\n\thelpFlag = flag.Bool(\"help\", false, \"show help\")\n)\n\ntype RobotsRule struct {\n\tUserAgent string\n\tDisallows []string\n\tAllows []string\n\tCrawlDelay int\n\tIsBlacklist bool // true if this is a specifically denied user agent\n}\n\ntype AnubisRule struct {\n\tExpression *config.ExpressionOrList `yaml:\"expression,omitempty\" json:\"expression,omitempty\"`\n\tChallenge *config.ChallengeRules `yaml:\"challenge,omitempty\" json:\"challenge,omitempty\"`\n\tWeight *config.Weight `yaml:\"weight,omitempty\" json:\"weight,omitempty\"`\n\tName string `yaml:\"name\" json:\"name\"`\n\tAction string `yaml:\"action\" json:\"action\"`\n}\n\nfunc init() {\n\tflag.Usage = func() {\n\t\tfmt.Fprintf(os.Stderr, \"Usage of %s:\\n\", os.Args[0])\n\t\tfmt.Fprintf(os.Stderr, \"%s [options] -input \\n\\n\", os.Args[0])\n\t\tflag.PrintDefaults()\n\t\tfmt.Fprintln(os.Stderr, \"\\nExamples:\")\n\t\tfmt.Fprintln(os.Stderr, \" # Convert local robots.txt file\")\n\t\tfmt.Fprintln(os.Stderr, \" robots2policy -input robots.txt -output policy.yaml\")\n\t\tfmt.Fprintln(os.Stderr, \"\")\n\t\tfmt.Fprintln(os.Stderr, \" # Convert from URL\")\n\t\tfmt.Fprintln(os.Stderr, \" robots2policy -input https://example.com/robots.txt -format json\")\n\t\tfmt.Fprintln(os.Stderr, \"\")\n\t\tfmt.Fprintln(os.Stderr, \" # Read from stdin, write to stdout\")\n\t\tfmt.Fprintln(os.Stderr, \" curl https://example.com/robots.txt | robots2policy -input -\")\n\t\tos.Exit(2)\n\t}\n}\n\nfunc main() {\n\tflag.Parse()\n\n\tif len(flag.Args()) > 0 || *helpFlag || *inputFile == \"\" {\n\t\tflag.Usage()\n\t}\n\n\t// Read robots.txt\n\tvar input io.Reader\n\tif *inputFile == \"-\" {\n\t\tinput = os.Stdin\n\t} else if strings.HasPrefix(*inputFile, \"http://\") || strings.HasPrefix(*inputFile, \"https://\") {\n\t\tresp, err := http.Get(*inputFile)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to fetch robots.txt from URL: %v\", err)\n\t\t}\n\t\tdefer resp.Body.Close()\n\t\tinput = resp.Body\n\t} else {\n\t\tfile, err := os.Open(*inputFile)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to open input file: %v\", err)\n\t\t}\n\t\tdefer file.Close()\n\t\tinput = file\n\t}\n\n\t// Parse robots.txt\n\trules, err := parseRobotsTxt(input)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to parse robots.txt: %v\", err)\n\t}\n\n\t// Convert to Anubis rules\n\tanubisRules := convertToAnubisRules(rules)\n\n\t// Check if any rules were generated\n\tif len(anubisRules) == 0 {\n\t\tlog.Fatal(\"no valid rules generated from robots.txt - file may be empty or contain no disallow directives\")\n\t}\n\n\t// Generate output\n\tvar output []byte\n\tswitch strings.ToLower(*outputFormat) {\n\tcase \"yaml\":\n\t\toutput, err = yaml.Marshal(anubisRules)\n\tcase \"json\":\n\t\toutput, err = json.MarshalIndent(anubisRules, \"\", \" \")\n\tdefault:\n\t\tlog.Fatalf(\"unsupported output format: %s (use yaml or json)\", *outputFormat)\n\t}\n\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to marshal output: %v\", err)\n\t}\n\n\t// Write output\n\tif *outputFile == \"\" || *outputFile == \"-\" {\n\t\tfmt.Print(string(output))\n\t} else {\n\t\terr = os.WriteFile(*outputFile, output, 0644)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to write output file: %v\", err)\n\t\t}\n\t\tfmt.Printf(\"Generated Anubis policy written to %s\\n\", *outputFile)\n\t}\n}\n\nfunc parseRobotsTxt(input io.Reader) ([]RobotsRule, error) {\n\tscanner := bufio.NewScanner(input)\n\tvar rules []RobotsRule\n\tvar currentRule *RobotsRule\n\n\tfor scanner.Scan() {\n\t\tline := strings.TrimSpace(scanner.Text())\n\n\t\t// Skip empty lines and comments\n\t\tif line == \"\" || strings.HasPrefix(line, \"#\") {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Split on first colon\n\t\tparts := strings.SplitN(line, \":\", 2)\n\t\tif len(parts) != 2 {\n\t\t\tcontinue\n\t\t}\n\n\t\tdirective := strings.TrimSpace(strings.ToLower(parts[0]))\n\t\tvalue := strings.TrimSpace(parts[1])\n\n\t\tswitch directive {\n\t\tcase \"user-agent\":\n\t\t\t// Start a new rule section\n\t\t\tif currentRule != nil {\n\t\t\t\trules = append(rules, *currentRule)\n\t\t\t}\n\t\t\tcurrentRule = &RobotsRule{\n\t\t\t\tUserAgent: value,\n\t\t\t\tDisallows: make([]string, 0),\n\t\t\t\tAllows: make([]string, 0),\n\t\t\t}\n\n\t\tcase \"disallow\":\n\t\t\tif currentRule != nil && value != \"\" {\n\t\t\t\tcurrentRule.Disallows = append(currentRule.Disallows, value)\n\t\t\t}\n\n\t\tcase \"allow\":\n\t\t\tif currentRule != nil && value != \"\" {\n\t\t\t\tcurrentRule.Allows = append(currentRule.Allows, value)\n\t\t\t}\n\n\t\tcase \"crawl-delay\":\n\t\t\tif currentRule != nil {\n\t\t\t\tif delay, err := parseIntSafe(value); err == nil {\n\t\t\t\t\tcurrentRule.CrawlDelay = delay\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Don't forget the last rule\n\tif currentRule != nil {\n\t\trules = append(rules, *currentRule)\n\t}\n\n\t// Mark blacklisted user agents (those with \"Disallow: /\")\n\tfor i := range rules {\n\t\tfor _, disallow := range rules[i].Disallows {\n\t\t\tif disallow == \"/\" {\n\t\t\t\trules[i].IsBlacklist = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn rules, scanner.Err()\n}\n\nfunc parseIntSafe(s string) (int, error) {\n\tvar result int\n\t_, err := fmt.Sscanf(s, \"%d\", &result)\n\treturn result, err\n}\n\nfunc convertToAnubisRules(robotsRules []RobotsRule) []AnubisRule {\n\tvar anubisRules []AnubisRule\n\truleCounter := 0\n\n\tfor _, robotsRule := range robotsRules {\n\t\tuserAgent := robotsRule.UserAgent\n\n\t\t// Handle crawl delay as weight adjustment (do this first before any continues)\n\t\tif robotsRule.CrawlDelay > 0 && *crawlDelay > 0 {\n\t\t\truleCounter++\n\t\t\trule := AnubisRule{\n\t\t\t\tName: fmt.Sprintf(\"%s-crawl-delay-%d\", *policyName, ruleCounter),\n\t\t\t\tAction: \"WEIGH\",\n\t\t\t\tWeight: &config.Weight{Adjust: *crawlDelay},\n\t\t\t}\n\n\t\t\tif userAgent == \"*\" {\n\t\t\t\trule.Expression = &config.ExpressionOrList{\n\t\t\t\t\tAll: []string{\"true\"}, // Always applies\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\trule.Expression = &config.ExpressionOrList{\n\t\t\t\t\tAll: []string{fmt.Sprintf(\"userAgent.contains(%q)\", userAgent)},\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tanubisRules = append(anubisRules, rule)\n\t\t}\n\n\t\t// Handle blacklisted user agents (complete deny/challenge)\n\t\tif robotsRule.IsBlacklist {\n\t\t\truleCounter++\n\t\t\trule := AnubisRule{\n\t\t\t\tName: fmt.Sprintf(\"%s-blacklist-%d\", *policyName, ruleCounter),\n\t\t\t\tAction: *userAgentDeny,\n\t\t\t}\n\n\t\t\tif userAgent == \"*\" {\n\t\t\t\t// This would block everything - convert to a weight adjustment instead\n\t\t\t\trule.Name = fmt.Sprintf(\"%s-global-restriction-%d\", *policyName, ruleCounter)\n\t\t\t\trule.Action = \"WEIGH\"\n\t\t\t\trule.Weight = &config.Weight{Adjust: 20} // Increase difficulty significantly\n\t\t\t\trule.Expression = &config.ExpressionOrList{\n\t\t\t\t\tAll: []string{\"true\"}, // Always applies\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\trule.Expression = &config.ExpressionOrList{\n\t\t\t\t\tAll: []string{fmt.Sprintf(\"userAgent.contains(%q)\", userAgent)},\n\t\t\t\t}\n\t\t\t}\n\t\t\tanubisRules = append(anubisRules, rule)\n\t\t\tcontinue\n\t\t}\n\n\t\t// Handle specific disallow rules\n\t\tfor _, disallow := range robotsRule.Disallows {\n\t\t\tif disallow == \"/\" {\n\t\t\t\tcontinue // Already handled as blacklist above\n\t\t\t}\n\n\t\t\truleCounter++\n\t\t\trule := AnubisRule{\n\t\t\t\tName: fmt.Sprintf(\"%s-disallow-%d\", *policyName, ruleCounter),\n\t\t\t\tAction: *baseAction,\n\t\t\t}\n\n\t\t\t// Build CEL expression\n\t\t\tvar conditions []string\n\n\t\t\t// Add user agent condition if not wildcard\n\t\t\tif userAgent != \"*\" {\n\t\t\t\tconditions = append(conditions, fmt.Sprintf(\"userAgent.contains(%q)\", userAgent))\n\t\t\t}\n\n\t\t\t// Add path condition\n\t\t\tpathCondition := buildPathCondition(disallow)\n\t\t\tconditions = append(conditions, pathCondition)\n\n\t\t\trule.Expression = &config.ExpressionOrList{\n\t\t\t\tAll: conditions,\n\t\t\t}\n\n\t\t\tanubisRules = append(anubisRules, rule)\n\t\t}\n\n\t}\n\n\treturn anubisRules\n}\n\nfunc buildPathCondition(robotsPath string) string {\n\t// Handle wildcards in robots.txt paths\n\tif strings.Contains(robotsPath, \"*\") || strings.Contains(robotsPath, \"?\") {\n\t\t// Convert robots.txt wildcards to regex\n\t\tregex := regexp.QuoteMeta(robotsPath)\n\t\tregex = strings.ReplaceAll(regex, `\\*`, `.*`) // * becomes .*\n\t\tregex = strings.ReplaceAll(regex, `\\?`, `.`) // ? becomes .\n\t\tregex = \"^\" + regex\n\t\treturn fmt.Sprintf(\"path.matches(%q)\", regex)\n\t}\n\n\t// Simple prefix match for most cases\n\treturn fmt.Sprintf(\"path.startsWith(%q)\", robotsPath)\n}\n"], ["/anubis/lib/thoth/cachediptoasn.go", "package thoth\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net/netip\"\n\n\tiptoasnv1 \"github.com/TecharoHQ/thoth-proto/gen/techaro/thoth/iptoasn/v1\"\n\t\"github.com/gaissmai/bart\"\n\t\"google.golang.org/grpc\"\n)\n\ntype IPToASNWithCache struct {\n\tnext iptoasnv1.IpToASNServiceClient\n\ttable *bart.Table[*iptoasnv1.LookupResponse]\n}\n\nfunc NewIpToASNWithCache(next iptoasnv1.IpToASNServiceClient) *IPToASNWithCache {\n\tresult := &IPToASNWithCache{\n\t\tnext: next,\n\t\ttable: &bart.Table[*iptoasnv1.LookupResponse]{},\n\t}\n\n\tfor _, pfx := range []netip.Prefix{\n\t\tnetip.MustParsePrefix(\"10.0.0.0/8\"), // RFC 1918\n\t\tnetip.MustParsePrefix(\"172.16.0.0/12\"), // RFC 1918\n\t\tnetip.MustParsePrefix(\"192.168.0.0/16\"), // RFC 1918\n\t\tnetip.MustParsePrefix(\"127.0.0.0/8\"), // Loopback\n\t\tnetip.MustParsePrefix(\"169.254.0.0/16\"), // Link-local\n\t\tnetip.MustParsePrefix(\"100.64.0.0/10\"), // CGNAT\n\t\tnetip.MustParsePrefix(\"192.0.0.0/24\"), // Protocol assignments\n\t\tnetip.MustParsePrefix(\"192.0.2.0/24\"), // TEST-NET-1\n\t\tnetip.MustParsePrefix(\"198.18.0.0/15\"), // Benchmarking\n\t\tnetip.MustParsePrefix(\"198.51.100.0/24\"), // TEST-NET-2\n\t\tnetip.MustParsePrefix(\"203.0.113.0/24\"), // TEST-NET-3\n\t\tnetip.MustParsePrefix(\"240.0.0.0/4\"), // Reserved\n\t\tnetip.MustParsePrefix(\"255.255.255.255/32\"), // Broadcast\n\t\tnetip.MustParsePrefix(\"fc00::/7\"), // Unique local address\n\t\tnetip.MustParsePrefix(\"fe80::/10\"), // Link-local\n\t\tnetip.MustParsePrefix(\"::1/128\"), // Loopback\n\t\tnetip.MustParsePrefix(\"::/128\"), // Unspecified\n\t\tnetip.MustParsePrefix(\"100::/64\"), // Discard-only\n\t\tnetip.MustParsePrefix(\"2001:db8::/32\"), // Documentation\n\t} {\n\t\tresult.table.Insert(pfx, &iptoasnv1.LookupResponse{Announced: false})\n\t}\n\n\treturn result\n}\n\nfunc (ip2asn *IPToASNWithCache) Lookup(ctx context.Context, lr *iptoasnv1.LookupRequest, opts ...grpc.CallOption) (*iptoasnv1.LookupResponse, error) {\n\taddr, err := netip.ParseAddr(lr.GetIpAddress())\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"input is not an IP address: %w\", err)\n\t}\n\n\tcachedResponse, ok := ip2asn.table.Lookup(addr)\n\tif ok {\n\t\treturn cachedResponse, nil\n\t}\n\n\tresp, err := ip2asn.next.Lookup(ctx, lr, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar errs []error\n\tfor _, cidr := range resp.GetCidr() {\n\t\tpfx, err := netip.ParsePrefix(cidr)\n\t\tif err != nil {\n\t\t\terrs = append(errs, err)\n\t\t\tcontinue\n\t\t}\n\t\tip2asn.table.Insert(pfx, resp)\n\t}\n\n\tif len(errs) != 0 {\n\t\tslog.Error(\"errors parsing IP prefixes\", \"err\", errors.Join(errs...))\n\t}\n\n\treturn resp, nil\n}\n"], ["/anubis/lib/store/bbolt/factory.go", "package bbolt\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n\t\"go.etcd.io/bbolt\"\n)\n\nvar (\n\tErrMissingPath = errors.New(\"bbolt: path is missing from config\")\n\tErrCantWriteToPath = errors.New(\"bbolt: can't write to path\")\n)\n\nfunc init() {\n\tstore.Register(\"bbolt\", Factory{})\n}\n\n// Factory builds new instances of the bbolt storage backend according to\n// configuration passed via a json.RawMessage.\ntype Factory struct{}\n\n// Build parses and validates the bbolt storage backend Config and creates\n// a new instance of it.\nfunc (Factory) Build(ctx context.Context, data json.RawMessage) (store.Interface, error) {\n\tvar config Config\n\tif err := json.Unmarshal([]byte(data), &config); err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\tif err := config.Valid(); err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\tbdb, err := bbolt.Open(config.Path, 0600, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't open bbolt database %s: %w\", config.Path, err)\n\t}\n\n\tresult := &Store{\n\t\tbdb: bdb,\n\t}\n\n\tgo result.cleanupThread(ctx)\n\n\treturn result, nil\n}\n\n// Valid parses and validates the bbolt store Config or returns\n// an error.\nfunc (Factory) Valid(data json.RawMessage) error {\n\tvar config Config\n\tif err := json.Unmarshal([]byte(data), &config); err != nil {\n\t\treturn fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\tif err := config.Valid(); err != nil {\n\t\treturn fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\treturn nil\n}\n\n// Config is the bbolt storage backend configuration.\ntype Config struct {\n\t// Path is the filesystem path of the database. The folder must be writable to Anubis.\n\tPath string `json:\"path\"`\n}\n\n// Valid validates the configuration including checking if its containing folder is writable.\nfunc (c Config) Valid() error {\n\tvar errs []error\n\n\tif c.Path == \"\" {\n\t\terrs = append(errs, ErrMissingPath)\n\t} else {\n\t\tdir := filepath.Dir(c.Path)\n\t\tif err := os.WriteFile(filepath.Join(dir, \".test-file\"), []byte(\"\"), 0600); err != nil {\n\t\t\terrs = append(errs, ErrCantWriteToPath)\n\t\t}\n\t\tos.Remove(filepath.Join(dir, \".test-file\"))\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn errors.Join(errs...)\n\t}\n\n\treturn nil\n}\n"], ["/anubis/lib/thoth/geoipchecker.go", "package thoth\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net/http\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis/lib/policy/checker\"\n\tiptoasnv1 \"github.com/TecharoHQ/thoth-proto/gen/techaro/thoth/iptoasn/v1\"\n)\n\nfunc (c *Client) GeoIPCheckerFor(countries []string) checker.Impl {\n\tcountryMap := map[string]struct{}{}\n\tvar sb strings.Builder\n\tfmt.Fprintln(&sb, \"GeoIPChecker\")\n\tfor _, cc := range countries {\n\t\tcountryMap[cc] = struct{}{}\n\t\tfmt.Fprintln(&sb, cc)\n\t}\n\n\treturn &GeoIPChecker{\n\t\tIPToASN: c.IPToASN,\n\t\tCountries: countryMap,\n\t\thash: sb.String(),\n\t}\n}\n\ntype GeoIPChecker struct {\n\tIPToASN iptoasnv1.IpToASNServiceClient\n\tCountries map[string]struct{}\n\thash string\n}\n\nfunc (gipc *GeoIPChecker) Check(r *http.Request) (bool, error) {\n\tctx, cancel := context.WithTimeout(r.Context(), 500*time.Millisecond)\n\tdefer cancel()\n\n\tipInfo, err := gipc.IPToASN.Lookup(ctx, &iptoasnv1.LookupRequest{\n\t\tIpAddress: r.Header.Get(\"X-Real-Ip\"),\n\t})\n\tif err != nil {\n\t\tswitch {\n\t\tcase errors.Is(err, context.DeadlineExceeded):\n\t\t\tslog.Debug(\"error contacting thoth\", \"err\", err, \"actionable\", false)\n\t\t\treturn false, nil\n\t\tdefault:\n\t\t\tslog.Error(\"error contacting thoth, please contact support\", \"err\", err, \"actionable\", true)\n\t\t\treturn false, nil\n\t\t}\n\t}\n\n\t// If IP is not publicly announced, return false\n\tif !ipInfo.GetAnnounced() {\n\t\treturn false, nil\n\t}\n\n\t_, ok := gipc.Countries[strings.ToLower(ipInfo.GetCountryCode())]\n\n\treturn ok, nil\n}\n\nfunc (gipc *GeoIPChecker) Hash() string {\n\treturn gipc.hash\n}\n"], ["/anubis/lib/store/valkey/factory.go", "package valkey\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n\tvalkey \"github.com/redis/go-redis/v9\"\n)\n\nvar (\n\tErrNoURL = errors.New(\"valkey.Config: no URL defined\")\n\tErrBadURL = errors.New(\"valkey.Config: URL is invalid\")\n)\n\nfunc init() {\n\tstore.Register(\"valkey\", Factory{})\n}\n\ntype Factory struct{}\n\nfunc (Factory) Build(ctx context.Context, data json.RawMessage) (store.Interface, error) {\n\tvar config Config\n\n\tif err := json.Unmarshal([]byte(data), &config); err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\tif err := config.Valid(); err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\topts, err := valkey.ParseURL(config.URL)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\trdb := valkey.NewClient(opts)\n\n\tif _, err := rdb.Ping(ctx).Result(); err != nil {\n\t\treturn nil, fmt.Errorf(\"can't ping valkey instance: %w\", err)\n\t}\n\n\treturn &Store{\n\t\trdb: rdb,\n\t}, nil\n}\n\nfunc (Factory) Valid(data json.RawMessage) error {\n\tvar config Config\n\tif err := json.Unmarshal([]byte(data), &config); err != nil {\n\t\treturn fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\tif err := config.Valid(); err != nil {\n\t\treturn fmt.Errorf(\"%w: %w\", store.ErrBadConfig, err)\n\t}\n\n\treturn nil\n}\n\ntype Config struct {\n\tURL string `json:\"url\"`\n}\n\nfunc (c Config) Valid() error {\n\tvar errs []error\n\n\tif c.URL == \"\" {\n\t\terrs = append(errs, ErrNoURL)\n\t}\n\n\tif _, err := valkey.ParseURL(c.URL); err != nil {\n\t\terrs = append(errs, ErrBadURL)\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"valkey.Config: invalid config: %w\", errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n"], ["/anubis/lib/policy/config/opengraph.go", "package config\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"time\"\n)\n\nvar (\n\tErrInvalidOpenGraphConfig = errors.New(\"config.OpenGraph: invalid OpenGraph configuration\")\n\tErrOpenGraphTTLDoesNotParse = errors.New(\"config.OpenGraph: ttl does not parse as a Duration, see https://pkg.go.dev/time#ParseDuration (formatted like 5m -> 5 minutes, 2h -> 2 hours, etc)\")\n\tErrOpenGraphMissingProperty = errors.New(\"config.OpenGraph: default opengraph tags missing a property\")\n)\n\ntype openGraphFileConfig struct {\n\tEnabled bool `json:\"enabled\" yaml:\"enabled\"`\n\tConsiderHost bool `json:\"considerHost\" yaml:\"enabled\"`\n\tTimeToLive string `json:\"ttl\" yaml:\"ttl\"`\n\tOverride map[string]string `json:\"override,omitempty\" yaml:\"override,omitempty\"`\n}\n\ntype OpenGraph struct {\n\tEnabled bool `json:\"enabled\" yaml:\"enabled\"`\n\tConsiderHost bool `json:\"considerHost\" yaml:\"enabled\"`\n\tOverride map[string]string `json:\"override,omitempty\" yaml:\"override,omitempty\"`\n\tTimeToLive time.Duration `json:\"ttl\" yaml:\"ttl\"`\n}\n\nfunc (og *openGraphFileConfig) Valid() error {\n\tvar errs []error\n\n\tif _, err := time.ParseDuration(og.TimeToLive); err != nil {\n\t\terrs = append(errs, fmt.Errorf(\"%w: ParseDuration(%q) returned: %w\", ErrOpenGraphTTLDoesNotParse, og.TimeToLive, err))\n\t}\n\n\tif len(og.Override) != 0 {\n\t\tfor _, tag := range []string{\n\t\t\t\"og:title\",\n\t\t} {\n\t\t\tif _, ok := og.Override[tag]; !ok {\n\t\t\t\terrs = append(errs, fmt.Errorf(\"%w: %s\", ErrOpenGraphMissingProperty, tag))\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn errors.Join(ErrInvalidOpenGraphConfig, errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n"], ["/anubis/internal/log.go", "package internal\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"log/slog\"\n\t\"net/http\"\n\t\"os\"\n\t\"strings\"\n)\n\nfunc InitSlog(level string) {\n\tvar programLevel slog.Level\n\tif err := (&programLevel).UnmarshalText([]byte(level)); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"invalid log level %s: %v, using info\\n\", level, err)\n\t\tprogramLevel = slog.LevelInfo\n\t}\n\n\tleveler := &slog.LevelVar{}\n\tleveler.Set(programLevel)\n\n\th := slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{\n\t\tAddSource: true,\n\t\tLevel: leveler,\n\t})\n\tslog.SetDefault(slog.New(h))\n}\n\nfunc GetRequestLogger(r *http.Request) *slog.Logger {\n\treturn slog.With(\n\t\t\"user_agent\", r.UserAgent(),\n\t\t\"accept_language\", r.Header.Get(\"Accept-Language\"),\n\t\t\"priority\", r.Header.Get(\"Priority\"),\n\t\t\"x-forwarded-for\",\n\t\tr.Header.Get(\"X-Forwarded-For\"),\n\t\t\"x-real-ip\", r.Header.Get(\"X-Real-Ip\"),\n\t)\n}\n\n// ErrorLogFilter is used to suppress \"context canceled\" logs from the http server when a request is canceled (e.g., when a client disconnects).\ntype ErrorLogFilter struct {\n\tUnwrap *log.Logger\n}\n\nfunc (elf *ErrorLogFilter) Write(p []byte) (n int, err error) {\n\tlogMessage := string(p)\n\tif strings.Contains(logMessage, \"context canceled\") {\n\t\treturn len(p), nil // Suppress the log by doing nothing\n\t}\n\tif elf.Unwrap != nil {\n\t\treturn elf.Unwrap.Writer().Write(p)\n\t}\n\treturn len(p), nil\n}\n\nfunc GetFilteredHTTPLogger() *log.Logger {\n\tstdErrLogger := log.New(os.Stderr, \"\", log.LstdFlags) // essentially what the default logger is.\n\treturn log.New(&ErrorLogFilter{Unwrap: stdErrLogger}, \"\", 0)\n}\n"], ["/anubis/lib/store/interface.go", "package store\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"time\"\n)\n\nvar (\n\t// ErrNotFound is returned when the store implementation cannot find the value\n\t// for a given key.\n\tErrNotFound = errors.New(\"store: key not found\")\n\n\t// ErrCantDecode is returned when a store adaptor cannot decode the store format\n\t// to a value used by the code.\n\tErrCantDecode = errors.New(\"store: can't decode value\")\n\n\t// ErrCantEncode is returned when a store adaptor cannot encode the value into\n\t// the format that the store uses.\n\tErrCantEncode = errors.New(\"store: can't encode value\")\n\n\t// ErrBadConfig is returned when a store adaptor's configuration is invalid.\n\tErrBadConfig = errors.New(\"store: configuration is invalid\")\n)\n\n// Interface defines the calls that Anubis uses for storage in a local or remote\n// datastore. This can be implemented with an in-memory, on-disk, or in-database\n// storage backend.\ntype Interface interface {\n\t// Delete removes a value from the store by key.\n\tDelete(ctx context.Context, key string) error\n\n\t// Get returns the value of a key assuming that value exists and has not expired.\n\tGet(ctx context.Context, key string) ([]byte, error)\n\n\t// Set puts a value into the store that expires according to its expiry.\n\tSet(ctx context.Context, key string, value []byte, expiry time.Duration) error\n}\n\nfunc z[T any]() T { return *new(T) }\n\ntype JSON[T any] struct {\n\tUnderlying Interface\n\tPrefix string\n}\n\nfunc (j *JSON[T]) Delete(ctx context.Context, key string) error {\n\tif j.Prefix != \"\" {\n\t\tkey = j.Prefix + key\n\t}\n\n\treturn j.Underlying.Delete(ctx, key)\n}\n\nfunc (j *JSON[T]) Get(ctx context.Context, key string) (T, error) {\n\tif j.Prefix != \"\" {\n\t\tkey = j.Prefix + key\n\t}\n\n\tdata, err := j.Underlying.Get(ctx, key)\n\tif err != nil {\n\t\treturn z[T](), err\n\t}\n\n\tvar result T\n\tif err := json.Unmarshal(data, &result); err != nil {\n\t\treturn z[T](), fmt.Errorf(\"%w: %w\", ErrCantDecode, err)\n\t}\n\n\treturn result, nil\n}\n\nfunc (j *JSON[T]) Set(ctx context.Context, key string, value T, expiry time.Duration) error {\n\tif j.Prefix != \"\" {\n\t\tkey = j.Prefix + key\n\t}\n\n\tdata, err := json.Marshal(value)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%w: %w\", ErrCantEncode, err)\n\t}\n\n\tif err := j.Underlying.Set(ctx, key, data, expiry); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n"], ["/anubis/lib/thoth/asnchecker.go", "package thoth\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net/http\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis/internal\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/checker\"\n\tiptoasnv1 \"github.com/TecharoHQ/thoth-proto/gen/techaro/thoth/iptoasn/v1\"\n)\n\nfunc (c *Client) ASNCheckerFor(asns []uint32) checker.Impl {\n\tasnMap := map[uint32]struct{}{}\n\tvar sb strings.Builder\n\tfmt.Fprintln(&sb, \"ASNChecker\")\n\tfor _, asn := range asns {\n\t\tasnMap[asn] = struct{}{}\n\t\tfmt.Fprintln(&sb, \"AS\", asn)\n\t}\n\n\treturn &ASNChecker{\n\t\tiptoasn: c.IPToASN,\n\t\tasns: asnMap,\n\t\thash: internal.FastHash(sb.String()),\n\t}\n}\n\ntype ASNChecker struct {\n\tiptoasn iptoasnv1.IpToASNServiceClient\n\tasns map[uint32]struct{}\n\thash string\n}\n\nfunc (asnc *ASNChecker) Check(r *http.Request) (bool, error) {\n\tctx, cancel := context.WithTimeout(r.Context(), 500*time.Millisecond)\n\tdefer cancel()\n\n\tipInfo, err := asnc.iptoasn.Lookup(ctx, &iptoasnv1.LookupRequest{\n\t\tIpAddress: r.Header.Get(\"X-Real-Ip\"),\n\t})\n\tif err != nil {\n\t\tswitch {\n\t\tcase errors.Is(err, context.DeadlineExceeded):\n\t\t\tslog.Debug(\"error contacting thoth\", \"err\", err, \"actionable\", false)\n\t\t\treturn false, nil\n\t\tdefault:\n\t\t\tslog.Error(\"error contacting thoth, please contact support\", \"err\", err, \"actionable\", true)\n\t\t\treturn false, nil\n\t\t}\n\t}\n\n\t// If IP is not publicly announced, return false\n\tif !ipInfo.GetAnnounced() {\n\t\treturn false, nil\n\t}\n\n\t_, ok := asnc.asns[uint32(ipInfo.GetAsNumber())]\n\n\treturn ok, nil\n}\n\nfunc (asnc *ASNChecker) Hash() string {\n\treturn asnc.hash\n}\n"], ["/anubis/internal/ogtags/parse.go", "package ogtags\n\nimport (\n\t\"strings\"\n\n\t\"golang.org/x/net/html\"\n)\n\n// extractOGTags traverses the HTML document and extracts approved Open Graph tags\nfunc (c *OGTagCache) extractOGTags(doc *html.Node) map[string]string {\n\togTags := make(map[string]string)\n\n\tvar traverseNodes func(*html.Node)\n\ttraverseNodes = func(n *html.Node) {\n\t\tif isOGMetaTag(n) {\n\t\t\tproperty, content := c.extractMetaTagInfo(n)\n\t\t\tif property != \"\" {\n\t\t\t\togTags[property] = content\n\t\t\t}\n\t\t}\n\t\tfor child := n.FirstChild; child != nil; child = child.NextSibling {\n\t\t\ttraverseNodes(child)\n\t\t}\n\t}\n\n\ttraverseNodes(doc)\n\treturn ogTags\n}\n\n// isOGMetaTag checks if a node is *any* meta tag\nfunc isOGMetaTag(n *html.Node) bool {\n\tif n == nil {\n\t\treturn false\n\t}\n\treturn n.Type == html.ElementNode && n.Data == \"meta\"\n}\n\n// extractMetaTagInfo extracts property and content from a meta tag\nfunc (c *OGTagCache) extractMetaTagInfo(n *html.Node) (property, content string) {\n\tvar propertyKey string\n\n\t// Single pass through attributes, using range to avoid bounds checking\n\tfor _, attr := range n.Attr {\n\t\tswitch attr.Key {\n\t\tcase \"property\", \"name\":\n\t\t\tpropertyKey = attr.Val\n\t\tcase \"content\":\n\t\t\tcontent = attr.Val\n\t\t}\n\t\t// Early exit if we have both\n\t\tif propertyKey != \"\" && content != \"\" {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif propertyKey == \"\" {\n\t\treturn \"\", content\n\t}\n\n\t// Check prefixes first (more common case)\n\tfor _, prefix := range c.approvedPrefixes {\n\t\tif strings.HasPrefix(propertyKey, prefix) {\n\t\t\treturn propertyKey, content\n\t\t}\n\t}\n\n\t// Check exact matches\n\tfor _, tag := range c.approvedTags {\n\t\tif propertyKey == tag {\n\t\t\treturn propertyKey, content\n\t\t}\n\t}\n\n\treturn \"\", content\n}\n"], ["/anubis/lib/policy/expressions/environment.go", "package expressions\n\nimport (\n\t\"math/rand/v2\"\n\t\"strings\"\n\n\t\"github.com/google/cel-go/cel\"\n\t\"github.com/google/cel-go/common/types\"\n\t\"github.com/google/cel-go/common/types/ref\"\n\t\"github.com/google/cel-go/common/types/traits\"\n\t\"github.com/google/cel-go/ext\"\n)\n\n// BotEnvironment creates a new CEL environment, this is the set of\n// variables and functions that are passed into the CEL scope so that\n// Anubis can fail loudly and early when something is invalid instead\n// of blowing up at runtime.\nfunc BotEnvironment() (*cel.Env, error) {\n\treturn New(\n\t\t// Variables exposed to CEL programs:\n\t\tcel.Variable(\"remoteAddress\", cel.StringType),\n\t\tcel.Variable(\"host\", cel.StringType),\n\t\tcel.Variable(\"method\", cel.StringType),\n\t\tcel.Variable(\"userAgent\", cel.StringType),\n\t\tcel.Variable(\"path\", cel.StringType),\n\t\tcel.Variable(\"query\", cel.MapType(cel.StringType, cel.StringType)),\n\t\tcel.Variable(\"headers\", cel.MapType(cel.StringType, cel.StringType)),\n\t\tcel.Variable(\"load_1m\", cel.DoubleType),\n\t\tcel.Variable(\"load_5m\", cel.DoubleType),\n\t\tcel.Variable(\"load_15m\", cel.DoubleType),\n\n\t\t// Bot-specific functions:\n\t\tcel.Function(\"missingHeader\",\n\t\t\tcel.Overload(\"missingHeader_map_string_string_string\",\n\t\t\t\t[]*cel.Type{cel.MapType(cel.StringType, cel.StringType), cel.StringType},\n\t\t\t\tcel.BoolType,\n\t\t\t\tcel.BinaryBinding(func(headers, key ref.Val) ref.Val {\n\t\t\t\t\t// Convert headers to a trait that supports Find\n\t\t\t\t\theadersMap, ok := headers.(traits.Indexer)\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn types.ValOrErr(headers, \"headers is not a map, but is %T\", headers)\n\t\t\t\t\t}\n\n\t\t\t\t\tkeyStr, ok := key.(types.String)\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn types.ValOrErr(key, \"key is not a string, but is %T\", key)\n\t\t\t\t\t}\n\n\t\t\t\t\tval := headersMap.Get(keyStr)\n\t\t\t\t\t// Check if the key is missing by testing for an error\n\t\t\t\t\tif types.IsError(val) {\n\t\t\t\t\t\treturn types.Bool(true) // header is missing\n\t\t\t\t\t}\n\t\t\t\t\treturn types.Bool(false) // header is present\n\t\t\t\t}),\n\t\t\t),\n\t\t),\n\n\t\tcel.Function(\"segments\",\n\t\t\tcel.Overload(\"segments_string_list_string\",\n\t\t\t\t[]*cel.Type{cel.StringType},\n\t\t\t\tcel.ListType(cel.StringType),\n\t\t\t\tcel.UnaryBinding(func(path ref.Val) ref.Val {\n\t\t\t\t\tpathStrType, ok := path.(types.String)\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn types.ValOrErr(path, \"path is not a string, but is %T\", path)\n\t\t\t\t\t}\n\n\t\t\t\t\tpathStr := string(pathStrType)\n\t\t\t\t\tif !strings.HasPrefix(pathStr, \"/\") {\n\t\t\t\t\t\treturn types.ValOrErr(path, \"path does not start with /\")\n\t\t\t\t\t}\n\n\t\t\t\t\tpathList := strings.Split(string(pathStr), \"/\")[1:]\n\n\t\t\t\t\treturn types.NewStringList(types.DefaultTypeAdapter, pathList)\n\t\t\t\t}),\n\t\t\t),\n\t\t),\n\t)\n}\n\n// NewThreshold creates a new CEL environment for threshold checking.\nfunc ThresholdEnvironment() (*cel.Env, error) {\n\treturn New(\n\t\tcel.Variable(\"weight\", cel.IntType),\n\t)\n}\n\nfunc New(opts ...cel.EnvOption) (*cel.Env, error) {\n\targs := []cel.EnvOption{\n\t\text.Strings(\n\t\t\text.StringsLocale(\"en_US\"),\n\t\t\text.StringsValidateFormatCalls(true),\n\t\t),\n\n\t\t// default all timestamps to UTC\n\t\tcel.DefaultUTCTimeZone(true),\n\n\t\t// Functions exposed to all CEL programs:\n\t\tcel.Function(\"randInt\",\n\t\t\tcel.Overload(\"randInt_int\",\n\t\t\t\t[]*cel.Type{cel.IntType},\n\t\t\t\tcel.IntType,\n\t\t\t\tcel.UnaryBinding(func(val ref.Val) ref.Val {\n\t\t\t\t\tn, ok := val.(types.Int)\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn types.ValOrErr(val, \"value is not an integer, but is %T\", val)\n\t\t\t\t\t}\n\n\t\t\t\t\treturn types.Int(rand.IntN(int(n)))\n\t\t\t\t}),\n\t\t\t),\n\t\t),\n\t}\n\n\targs = append(args, opts...)\n\treturn cel.NewEnv(args...)\n}\n\n// Compile takes CEL environment and syntax tree then emits an optimized\n// Program for execution.\nfunc Compile(env *cel.Env, src string) (cel.Program, error) {\n\tintermediate, iss := env.Compile(src)\n\tif iss != nil {\n\t\treturn nil, iss.Err()\n\t}\n\n\tast, iss := env.Check(intermediate)\n\tif iss != nil {\n\t\treturn nil, iss.Err()\n\t}\n\n\treturn env.Program(\n\t\tast,\n\t\tcel.EvalOptions(\n\t\t\t// optimize regular expressions right now instead of on the fly\n\t\t\tcel.OptOptimize,\n\t\t),\n\t)\n}\n"], ["/anubis/lib/challenge/metarefresh/metarefresh.go", "package metarefresh\n\nimport (\n\t\"crypto/subtle\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net/http\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/TecharoHQ/anubis/lib/challenge\"\n\t\"github.com/TecharoHQ/anubis/lib/localization\"\n\t\"github.com/TecharoHQ/anubis/web\"\n\t\"github.com/a-h/templ\"\n)\n\n//go:generate go tool github.com/a-h/templ/cmd/templ generate\n\nfunc init() {\n\tchallenge.Register(\"metarefresh\", &Impl{})\n}\n\ntype Impl struct{}\n\nfunc (i *Impl) Setup(mux *http.ServeMux) {}\n\nfunc (i *Impl) Issue(r *http.Request, lg *slog.Logger, in *challenge.IssueInput) (templ.Component, error) {\n\tu, err := r.URL.Parse(anubis.BasePrefix + \"/.within.website/x/cmd/anubis/api/pass-challenge\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't render page: %w\", err)\n\t}\n\n\tq := u.Query()\n\tq.Set(\"redir\", r.URL.String())\n\tq.Set(\"challenge\", in.Challenge.RandomData)\n\tu.RawQuery = q.Encode()\n\n\tloc := localization.GetLocalizer(r)\n\tcomponent, err := web.BaseWithChallengeAndOGTags(loc.T(\"making_sure_not_bot\"), page(u.String(), in.Rule.Challenge.Difficulty, loc), in.Impressum, in.Challenge.RandomData, in.Rule.Challenge, in.OGTags, loc)\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't render page: %w\", err)\n\t}\n\n\treturn component, nil\n}\n\nfunc (i *Impl) Validate(r *http.Request, lg *slog.Logger, in *challenge.ValidateInput) error {\n\tgotChallenge := r.FormValue(\"challenge\")\n\n\tif subtle.ConstantTimeCompare([]byte(in.Challenge.RandomData), []byte(gotChallenge)) != 1 {\n\t\treturn challenge.NewError(\"validate\", \"invalid response\", fmt.Errorf(\"%w: wanted response %s but got %s\", challenge.ErrFailed, in.Challenge.RandomData, gotChallenge))\n\t}\n\n\treturn nil\n}\n"], ["/anubis/lib/store/valkey/valkey.go", "package valkey\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n\tvalkey \"github.com/redis/go-redis/v9\"\n)\n\ntype Store struct {\n\trdb *valkey.Client\n}\n\nfunc (s *Store) Delete(ctx context.Context, key string) error {\n\tn, err := s.rdb.Del(ctx, key).Result()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"can't delete from valkey: %w\", err)\n\t}\n\n\tswitch n {\n\tcase 0:\n\t\treturn fmt.Errorf(\"%w: %d key(s) deleted\", store.ErrNotFound, n)\n\tdefault:\n\t\treturn nil\n\t}\n}\n\nfunc (s *Store) Get(ctx context.Context, key string) ([]byte, error) {\n\tresult, err := s.rdb.Get(ctx, key).Result()\n\tif err != nil {\n\t\tif valkey.HasErrorPrefix(err, \"redis: nil\") {\n\t\t\treturn nil, fmt.Errorf(\"%w: %w\", store.ErrNotFound, err)\n\t\t}\n\n\t\treturn nil, fmt.Errorf(\"can't fetch from valkey: %w\", err)\n\t}\n\n\treturn []byte(result), nil\n}\n\nfunc (s *Store) Set(ctx context.Context, key string, value []byte, expiry time.Duration) error {\n\tif _, err := s.rdb.Set(ctx, key, string(value), expiry).Result(); err != nil {\n\t\treturn fmt.Errorf(\"can't set %q in valkey: %w\", key, err)\n\t}\n\n\treturn nil\n}\n"], ["/anubis/lib/thoth/thoth.go", "package thoth\n\nimport (\n\t\"context\"\n\t\"crypto/tls\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\tiptoasnv1 \"github.com/TecharoHQ/thoth-proto/gen/techaro/thoth/iptoasn/v1\"\n\tgrpcprom \"github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus\"\n\t\"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/timeout\"\n\t\"github.com/prometheus/client_golang/prometheus\"\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/credentials\"\n\t\"google.golang.org/grpc/credentials/insecure\"\n\thealthv1 \"google.golang.org/grpc/health/grpc_health_v1\"\n)\n\ntype Client struct {\n\tconn *grpc.ClientConn\n\thealth healthv1.HealthClient\n\tIPToASN iptoasnv1.IpToASNServiceClient\n}\n\nfunc New(ctx context.Context, thothURL, apiToken string, plaintext bool) (*Client, error) {\n\tclMetrics := grpcprom.NewClientMetrics(\n\t\tgrpcprom.WithClientHandlingTimeHistogram(\n\t\t\tgrpcprom.WithHistogramBuckets([]float64{0.001, 0.01, 0.1, 0.3, 0.6, 1, 3, 6, 9, 20, 30, 60, 90, 120}),\n\t\t),\n\t)\n\tprometheus.DefaultRegisterer.Register(clMetrics)\n\n\tdo := []grpc.DialOption{\n\t\tgrpc.WithChainUnaryInterceptor(\n\t\t\ttimeout.UnaryClientInterceptor(500*time.Millisecond),\n\t\t\tclMetrics.UnaryClientInterceptor(),\n\t\t\tauthUnaryClientInterceptor(apiToken),\n\t\t),\n\t\tgrpc.WithChainStreamInterceptor(\n\t\t\tclMetrics.StreamClientInterceptor(),\n\t\t\tauthStreamClientInterceptor(apiToken),\n\t\t),\n\t\tgrpc.WithUserAgent(fmt.Sprint(\"Techaro/anubis:\", anubis.Version)),\n\t}\n\n\tif plaintext {\n\t\tdo = append(do, grpc.WithTransportCredentials(insecure.NewCredentials()))\n\t} else {\n\t\tdo = append(do, grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{})))\n\t}\n\n\tconn, err := grpc.NewClient(\n\t\tthothURL,\n\t\tdo...,\n\t)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't dial thoth at %s: %w\", thothURL, err)\n\t}\n\n\thc := healthv1.NewHealthClient(conn)\n\n\treturn &Client{\n\t\tconn: conn,\n\t\thealth: hc,\n\t\tIPToASN: NewIpToASNWithCache(iptoasnv1.NewIpToASNServiceClient(conn)),\n\t}, nil\n}\n\nfunc (c *Client) Close() error {\n\tif c.conn != nil {\n\t\treturn c.conn.Close()\n\t}\n\treturn nil\n}\n\nfunc (c *Client) WithIPToASNService(impl iptoasnv1.IpToASNServiceClient) {\n\tc.IPToASN = impl\n}\n"], ["/anubis/internal/dnsbl/dnsbl.go", "package dnsbl\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net\"\n\t\"strings\"\n)\n\n//go:generate go tool golang.org/x/tools/cmd/stringer -type=DroneBLResponse\n\ntype DroneBLResponse byte\n\nconst (\n\tAllGood DroneBLResponse = 0\n\tIRCDrone DroneBLResponse = 3\n\tBottler DroneBLResponse = 5\n\tUnknownSpambotOrDrone DroneBLResponse = 6\n\tDDOSDrone DroneBLResponse = 7\n\tSOCKSProxy DroneBLResponse = 8\n\tHTTPProxy DroneBLResponse = 9\n\tProxyChain DroneBLResponse = 10\n\tOpenProxy DroneBLResponse = 11\n\tOpenDNSResolver DroneBLResponse = 12\n\tBruteForceAttackers DroneBLResponse = 13\n\tOpenWingateProxy DroneBLResponse = 14\n\tCompromisedRouter DroneBLResponse = 15\n\tAutoRootingWorms DroneBLResponse = 16\n\tAutoDetectedBotIP DroneBLResponse = 17\n\tUnknown DroneBLResponse = 255\n)\n\nfunc Reverse(ip net.IP) string {\n\tif ip.To4() != nil {\n\t\treturn reverse4(ip)\n\t}\n\n\treturn reverse6(ip)\n}\n\nfunc reverse4(ip net.IP) string {\n\tsplitAddress := strings.Split(ip.String(), \".\")\n\n\t// swap first and last octet\n\tsplitAddress[0], splitAddress[3] = splitAddress[3], splitAddress[0]\n\t// swap middle octets\n\tsplitAddress[1], splitAddress[2] = splitAddress[2], splitAddress[1]\n\n\treturn strings.Join(splitAddress, \".\")\n}\n\nfunc reverse6(ip net.IP) string {\n\tipBytes := []byte(ip)\n\tvar sb strings.Builder\n\n\tfor i := len(ipBytes) - 1; i >= 0; i-- {\n\t\t// Split the byte into two nibbles\n\t\thighNibble := ipBytes[i] >> 4\n\t\tlowNibble := ipBytes[i] & 0x0F\n\n\t\t// Append the nibbles in reversed order\n\t\tsb.WriteString(fmt.Sprintf(\"%x.%x.\", lowNibble, highNibble))\n\t}\n\n\treturn sb.String()[:len(sb.String())-1]\n}\n\nfunc Lookup(ipStr string) (DroneBLResponse, error) {\n\tip := net.ParseIP(ipStr)\n\tif ip == nil {\n\t\treturn Unknown, errors.New(\"dnsbl: input is not an IP address\")\n\t}\n\n\trevIP := Reverse(ip) + \".dnsbl.dronebl.org\"\n\n\tips, err := net.LookupIP(revIP)\n\tif err != nil {\n\t\tvar dnserr *net.DNSError\n\t\tif errors.As(err, &dnserr) {\n\t\t\tif dnserr.IsNotFound {\n\t\t\t\treturn AllGood, nil\n\t\t\t}\n\t\t}\n\n\t\treturn Unknown, err\n\t}\n\n\tif len(ips) != 0 {\n\t\tfor _, ip := range ips {\n\t\t\treturn DroneBLResponse(ip.To4()[3]), nil\n\t\t}\n\t}\n\n\treturn UnknownSpambotOrDrone, nil\n}\n"], ["/anubis/lib/policy/config/threshold.go", "package config\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com/TecharoHQ/anubis\"\n)\n\nvar (\n\tErrNoThresholdRulesDefined = errors.New(\"config: no thresholds defined\")\n\tErrThresholdMustHaveName = errors.New(\"config.Threshold: must set name\")\n\tErrThresholdMustHaveExpression = errors.New(\"config.Threshold: must set expression\")\n\tErrThresholdChallengeMustHaveChallenge = errors.New(\"config.Threshold: a threshold with the CHALLENGE action must have challenge set\")\n\tErrThresholdCannotHaveWeighAction = errors.New(\"config.Threshold: a threshold cannot have the WEIGH action\")\n\n\tDefaultThresholds = []Threshold{\n\t\t{\n\t\t\tName: \"legacy-anubis-behaviour\",\n\t\t\tExpression: &ExpressionOrList{\n\t\t\t\tExpression: \"weight > 0\",\n\t\t\t},\n\t\t\tAction: RuleChallenge,\n\t\t\tChallenge: &ChallengeRules{\n\t\t\t\tAlgorithm: \"fast\",\n\t\t\t\tDifficulty: anubis.DefaultDifficulty,\n\t\t\t\tReportAs: anubis.DefaultDifficulty,\n\t\t\t},\n\t\t},\n\t}\n)\n\ntype Threshold struct {\n\tName string `json:\"name\" yaml:\"name\"`\n\tExpression *ExpressionOrList `json:\"expression\" yaml:\"expression\"`\n\tAction Rule `json:\"action\" yaml:\"action\"`\n\tChallenge *ChallengeRules `json:\"challenge\" yaml:\"challenge\"`\n}\n\nfunc (t Threshold) Valid() error {\n\tvar errs []error\n\n\tif len(t.Name) == 0 {\n\t\terrs = append(errs, ErrThresholdMustHaveName)\n\t}\n\n\tif t.Expression == nil {\n\t\terrs = append(errs, ErrThresholdMustHaveExpression)\n\t}\n\n\tif t.Expression != nil {\n\t\tif err := t.Expression.Valid(); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\tif err := t.Action.Valid(); err != nil {\n\t\terrs = append(errs, err)\n\t}\n\n\tif t.Action == RuleWeigh {\n\t\terrs = append(errs, ErrThresholdCannotHaveWeighAction)\n\t}\n\n\tif t.Action == RuleChallenge && t.Challenge == nil {\n\t\terrs = append(errs, ErrThresholdChallengeMustHaveChallenge)\n\t}\n\n\tif t.Challenge != nil {\n\t\tif err := t.Challenge.Valid(); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"config: threshold entry for %q is not valid:\\n%w\", t.Name, errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n"], ["/anubis/lib/policy/config/impressum.go", "package config\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n)\n\nvar ErrMissingValue = errors.New(\"config: missing value\")\n\ntype Impressum struct {\n\tFooter string `json:\"footer\" yaml:\"footer\"`\n\tPage ImpressumPage `json:\"page\" yaml:\"page\"`\n}\n\nfunc (i Impressum) Render(_ context.Context, w io.Writer) error {\n\tif _, err := fmt.Fprint(w, i.Footer); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (i Impressum) Valid() error {\n\tvar errs []error\n\n\tif len(i.Footer) == 0 {\n\t\terrs = append(errs, fmt.Errorf(\"%w: impressum footer must be defined\", ErrMissingValue))\n\t}\n\n\tif err := i.Page.Valid(); err != nil {\n\t\terrs = append(errs, err)\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn errors.Join(errs...)\n\t}\n\n\treturn nil\n}\n\ntype ImpressumPage struct {\n\tTitle string `json:\"title\" yaml:\"title\"`\n\tBody string `json:\"body\" yaml:\"body\"`\n}\n\nfunc (ip ImpressumPage) Render(_ context.Context, w io.Writer) error {\n\tif _, err := fmt.Fprint(w, ip.Body); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (ip ImpressumPage) Valid() error {\n\tvar errs []error\n\n\tif len(ip.Title) == 0 {\n\t\terrs = append(errs, fmt.Errorf(\"%w: impressum page title must be defined\", ErrMissingValue))\n\t}\n\n\tif len(ip.Body) == 0 {\n\t\terrs = append(errs, fmt.Errorf(\"%w: impressum body title must be defined\", ErrMissingValue))\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn errors.Join(errs...)\n\t}\n\n\treturn nil\n}\n"], ["/anubis/lib/localization/localization.go", "package localization\n\nimport (\n\t\"embed\"\n\t\"encoding/json\"\n\t\"net/http\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/nicksnyder/go-i18n/v2/i18n\"\n\t\"golang.org/x/text/language\"\n)\n\n//go:embed locales/*.json\nvar localeFS embed.FS\n\ntype LocalizationService struct {\n\tbundle *i18n.Bundle\n}\n\nvar (\n\tglobalService *LocalizationService\n\tonce sync.Once\n)\n\nfunc NewLocalizationService() *LocalizationService {\n\tonce.Do(func() {\n\t\tbundle := i18n.NewBundle(language.English)\n\t\tbundle.RegisterUnmarshalFunc(\"json\", json.Unmarshal)\n\n\t\t// Read all JSON files from the locales directory\n\t\tentries, err := localeFS.ReadDir(\"locales\")\n\t\tif err != nil {\n\t\t\t// Try fallback - create a minimal service with default messages\n\t\t\tglobalService = &LocalizationService{bundle: bundle}\n\t\t\treturn\n\t\t}\n\n\t\tloadedAny := false\n\t\tfor _, entry := range entries {\n\t\t\tif !entry.IsDir() && strings.HasSuffix(entry.Name(), \".json\") {\n\t\t\t\tfilePath := \"locales/\" + entry.Name()\n\t\t\t\t_, err := bundle.LoadMessageFileFS(localeFS, filePath)\n\t\t\t\tif err != nil {\n\t\t\t\t\t// Log error but continue with other files\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tloadedAny = true\n\t\t\t}\n\t\t}\n\n\t\tif !loadedAny {\n\t\t\t// If no files were loaded successfully, create minimal service\n\t\t\tglobalService = &LocalizationService{bundle: bundle}\n\t\t\treturn\n\t\t}\n\n\t\tglobalService = &LocalizationService{bundle: bundle}\n\t})\n\n\t// Safety check - if globalService is still nil, create a minimal one\n\tif globalService == nil {\n\t\tbundle := i18n.NewBundle(language.English)\n\t\tbundle.RegisterUnmarshalFunc(\"json\", json.Unmarshal)\n\t\tglobalService = &LocalizationService{bundle: bundle}\n\t}\n\n\treturn globalService\n}\n\nfunc (ls *LocalizationService) GetLocalizer(lang string) *i18n.Localizer {\n\treturn i18n.NewLocalizer(ls.bundle, lang)\n}\n\nfunc (ls *LocalizationService) GetLocalizerFromRequest(r *http.Request) *i18n.Localizer {\n\tif ls == nil || ls.bundle == nil {\n\t\t// Fallback to a basic bundle if service is not properly initialized\n\t\tbundle := i18n.NewBundle(language.English)\n\t\tbundle.RegisterUnmarshalFunc(\"json\", json.Unmarshal)\n\t\treturn i18n.NewLocalizer(bundle, \"en\")\n\t}\n\tacceptLanguage := r.Header.Get(\"Accept-Language\")\n\treturn i18n.NewLocalizer(ls.bundle, acceptLanguage, \"en\")\n}\n\n// SimpleLocalizer wraps i18n.Localizer with a more convenient API\ntype SimpleLocalizer struct {\n\tLocalizer *i18n.Localizer\n}\n\n// T provides a concise way to localize messages\nfunc (sl *SimpleLocalizer) T(messageID string) string {\n\treturn sl.Localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: messageID})\n}\n\n// Get the language that is used by the localizer by retrieving a well-known string that is required to be present\nfunc (sl *SimpleLocalizer) GetLang() string {\n\t_, tag, err := sl.Localizer.LocalizeWithTag(&i18n.LocalizeConfig{MessageID: \"loading\"})\n\tif err != nil {\n\t\treturn \"en\"\n\t}\n\treturn tag.String()\n}\n\n// GetLocalizer creates a localizer based on the request's Accept-Language header or forcedLanguage option\nfunc GetLocalizer(r *http.Request) *SimpleLocalizer {\n\tvar localizer *i18n.Localizer\n\tif anubis.ForcedLanguage == \"\" {\n\t\tlocalizer = NewLocalizationService().GetLocalizerFromRequest(r)\n\t} else {\n\t\tlocalizer = NewLocalizationService().GetLocalizer(anubis.ForcedLanguage)\n\t}\n\treturn &SimpleLocalizer{Localizer: localizer}\n}\n"], ["/anubis/utils/cmd/backoff-retry/main.go", "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"os\"\n\t\"os/exec\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar (\n\tstartWait = flag.Duration(\"start-wait\", 250*time.Millisecond, \"amount of time to start with exponential backoff\")\n\ttryCount = flag.Int(\"try-count\", 5, \"number of retries\")\n)\n\nfunc main() {\n\tflag.Parse()\n\n\tcmdStr := strings.Join(flag.Args(), \" \")\n\twait := *startWait\n\n\tfor i := range make([]struct{}, *tryCount) {\n\t\tslog.Info(\"executing\", \"try\", i+1, \"wait\", wait, \"cmd\", cmdStr)\n\n\t\tcmd := exec.Command(\"sh\", \"-c\", cmdStr)\n\t\tcmd.Stdin = nil\n\t\tcmd.Stdout = os.Stdout\n\t\tcmd.Stderr = os.Stderr\n\n\t\tif err := cmd.Run(); err != nil {\n\t\t\ttime.Sleep(wait)\n\t\t\twait = wait * 2\n\t\t} else {\n\t\t\tos.Exit(0)\n\t\t}\n\t}\n\n\tfmt.Printf(\"giving up after %d tries\\n\", *tryCount)\n\tos.Exit(1)\n}\n"], ["/anubis/lib/policy/expressions/url_values.go", "package expressions\n\nimport (\n\t\"errors\"\n\t\"net/url\"\n\t\"reflect\"\n\t\"strings\"\n\n\t\"github.com/google/cel-go/common/types\"\n\t\"github.com/google/cel-go/common/types/ref\"\n\t\"github.com/google/cel-go/common/types/traits\"\n)\n\nvar ErrNotImplemented = errors.New(\"expressions: not implemented\")\n\n// URLValues is a type wrapper to expose url.Values into CEL programs.\ntype URLValues struct {\n\turl.Values\n}\n\nfunc (u URLValues) ConvertToNative(typeDesc reflect.Type) (any, error) {\n\treturn nil, ErrNotImplemented\n}\n\nfunc (u URLValues) ConvertToType(typeVal ref.Type) ref.Val {\n\tswitch typeVal {\n\tcase types.MapType:\n\t\treturn u\n\tcase types.TypeType:\n\t\treturn types.MapType\n\t}\n\n\treturn types.NewErr(\"can't convert from %q to %q\", types.MapType, typeVal)\n}\n\nfunc (u URLValues) Equal(other ref.Val) ref.Val {\n\treturn types.Bool(false) // We don't want to compare header maps\n}\n\nfunc (u URLValues) Type() ref.Type {\n\treturn types.MapType\n}\n\nfunc (u URLValues) Value() any { return u }\n\nfunc (u URLValues) Find(key ref.Val) (ref.Val, bool) {\n\tk, ok := key.(types.String)\n\tif !ok {\n\t\treturn nil, false\n\t}\n\n\tif _, ok := u.Values[string(k)]; !ok {\n\t\treturn nil, false\n\t}\n\n\treturn types.String(strings.Join(u.Values[string(k)], \",\")), true\n}\n\nfunc (u URLValues) Contains(key ref.Val) ref.Val {\n\t_, ok := u.Find(key)\n\treturn types.Bool(ok)\n}\n\nfunc (u URLValues) Get(key ref.Val) ref.Val {\n\tresult, ok := u.Find(key)\n\tif !ok {\n\t\treturn types.ValOrErr(result, \"no such key: %v\", key)\n\t}\n\treturn result\n}\n\nfunc (u URLValues) Iterator() traits.Iterator { panic(\"TODO(Xe): implement me\") }\n\nfunc (u URLValues) IsZeroValue() bool {\n\treturn len(u.Values) == 0\n}\n\nfunc (u URLValues) Size() ref.Val { return types.Int(len(u.Values)) }\n"], ["/anubis/lib/policy/config/store.go", "package config\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n\t_ \"github.com/TecharoHQ/anubis/lib/store/all\"\n)\n\nvar (\n\tErrNoStoreBackend = errors.New(\"config.Store: no backend defined\")\n\tErrUnknownStoreBackend = errors.New(\"config.Store: unknown backend\")\n)\n\ntype Store struct {\n\tBackend string `json:\"backend\"`\n\tParameters json.RawMessage `json:\"parameters\"`\n}\n\nfunc (s *Store) Valid() error {\n\tvar errs []error\n\n\tif len(s.Backend) == 0 {\n\t\terrs = append(errs, ErrNoStoreBackend)\n\t}\n\n\tfac, ok := store.Get(s.Backend)\n\tswitch ok {\n\tcase true:\n\t\tif err := fac.Valid(s.Parameters); err != nil {\n\t\t\terrs = append(errs, err)\n\t\t}\n\tcase false:\n\t\terrs = append(errs, fmt.Errorf(\"%w: %q\", ErrUnknownStoreBackend, s.Backend))\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn errors.Join(errs...)\n\t}\n\n\treturn nil\n}\n"], ["/anubis/lib/policy/config/geoip.go", "package config\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"regexp\"\n\t\"strings\"\n)\n\nvar (\n\tcountryCodeRegexp = regexp.MustCompile(`^[a-zA-Z]{2}$`)\n\n\tErrNotCountryCode = errors.New(\"config.Bot: invalid country code\")\n)\n\ntype GeoIP struct {\n\tCountries []string `json:\"countries\"`\n}\n\nfunc (g *GeoIP) Valid() error {\n\tvar errs []error\n\n\tfor i, cc := range g.Countries {\n\t\tif !countryCodeRegexp.MatchString(cc) {\n\t\t\terrs = append(errs, fmt.Errorf(\"%w: %s\", ErrNotCountryCode, cc))\n\t\t}\n\n\t\tg.Countries[i] = strings.ToLower(cc)\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"bot.GeoIP: invalid GeoIP settings: %w\", errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n"], ["/anubis/internal/gzip.go", "package internal\n\nimport (\n\t\"compress/gzip\"\n\t\"net/http\"\n\t\"strings\"\n)\n\nfunc GzipMiddleware(level int, next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif !strings.Contains(r.Header.Get(\"Accept-Encoding\"), \"gzip\") {\n\t\t\tnext.ServeHTTP(w, r)\n\t\t\treturn\n\t\t}\n\n\t\tw.Header().Set(\"Content-Encoding\", \"gzip\")\n\t\tgz, err := gzip.NewWriterLevel(w, level)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tdefer gz.Close()\n\n\t\tgrw := gzipResponseWriter{ResponseWriter: w, sink: gz}\n\t\tnext.ServeHTTP(grw, r)\n\t})\n}\n\ntype gzipResponseWriter struct {\n\thttp.ResponseWriter\n\tsink *gzip.Writer\n}\n\nfunc (w gzipResponseWriter) Write(b []byte) (int, error) {\n\treturn w.sink.Write(b)\n}\n"], ["/anubis/cmd/robots2policy/batch/batch_process.go", "/*\nBatch process robots.txt files from archives like https://github.com/nrjones8/robots-dot-txt-archive-bot/tree/master/data/cleaned\ninto Anubis CEL policies. Usage: go run batch_process.go \n*/\npackage main\n\nimport (\n\t\"fmt\"\n\t\"io/fs\"\n\t\"log\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\nfunc main() {\n\tif len(os.Args) < 2 {\n\t\tfmt.Println(\"Usage: go run batch_process.go \")\n\t\tfmt.Println(\"Example: go run batch_process.go ./cleaned\")\n\t\tos.Exit(1)\n\t}\n\n\tcleanedDir := os.Args[1]\n\toutputDir := \"generated_policies\"\n\n\t// Create output directory\n\tif err := os.MkdirAll(outputDir, 0755); err != nil {\n\t\tlog.Fatalf(\"Failed to create output directory: %v\", err)\n\t}\n\n\tcount := 0\n\terr := filepath.WalkDir(cleanedDir, func(path string, d fs.DirEntry, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Skip directories\n\t\tif d.IsDir() {\n\t\t\treturn nil\n\t\t}\n\n\t\t// Generate policy name from file path\n\t\trelPath, _ := filepath.Rel(cleanedDir, path)\n\t\tpolicyName := strings.ReplaceAll(relPath, \"/\", \"-\")\n\t\tpolicyName = strings.TrimSuffix(policyName, \"-robots.txt\")\n\t\tpolicyName = strings.ReplaceAll(policyName, \".\", \"-\")\n\n\t\toutputFile := filepath.Join(outputDir, policyName+\".yaml\")\n\n\t\tcmd := exec.Command(\"go\", \"run\", \"main.go\",\n\t\t\t\"-input\", path,\n\t\t\t\"-output\", outputFile,\n\t\t\t\"-name\", policyName,\n\t\t\t\"-format\", \"yaml\")\n\n\t\tif err := cmd.Run(); err != nil {\n\t\t\tfmt.Printf(\"Warning: Failed to process %s: %v\\n\", path, err)\n\t\t\treturn nil // Continue processing other files\n\t\t}\n\n\t\tcount++\n\t\tif count%100 == 0 {\n\t\t\tfmt.Printf(\"Processed %d files...\\n\", count)\n\t\t} else if count%10 == 0 {\n\t\t\tfmt.Print(\".\")\n\t\t}\n\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\tlog.Fatalf(\"Error walking directory: %v\", err)\n\t}\n\n\tfmt.Printf(\"Successfully processed %d robots.txt files\\n\", count)\n\tfmt.Printf(\"Generated policies saved to: %s/\\n\", outputDir)\n}\n"], ["/anubis/lib/policy/config/asn.go", "package config\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\nvar (\n\tErrPrivateASN = errors.New(\"bot.ASNs: you have specified a private use ASN\")\n)\n\ntype ASNs struct {\n\tMatch []uint32 `json:\"match\"`\n}\n\nfunc (a *ASNs) Valid() error {\n\tvar errs []error\n\n\tfor _, asn := range a.Match {\n\t\tif isPrivateASN(asn) {\n\t\t\terrs = append(errs, fmt.Errorf(\"%w: %d is private (see RFC 6996)\", ErrPrivateASN, asn))\n\t\t}\n\t}\n\n\tif len(errs) != 0 {\n\t\treturn fmt.Errorf(\"bot.ASNs: invalid ASN settings: %w\", errors.Join(errs...))\n\t}\n\n\treturn nil\n}\n\n// isPrivateASN checks if an ASN is in the private use area.\n//\n// Based on RFC 6996 and IANA allocations.\nfunc isPrivateASN(asn uint32) bool {\n\tswitch {\n\tcase asn >= 64512 && asn <= 65534:\n\t\treturn true\n\tcase asn >= 4200000000 && asn <= 4294967294:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n"], ["/anubis/lib/policy/config/expressionorlist.go", "package config\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"slices\"\n\t\"strings\"\n)\n\nvar (\n\tErrExpressionOrListMustBeStringOrObject = errors.New(\"config: this must be a string or an object\")\n\tErrExpressionEmpty = errors.New(\"config: this expression is empty\")\n\tErrExpressionCantHaveBoth = errors.New(\"config: expression block can't contain multiple expression types\")\n)\n\ntype ExpressionOrList struct {\n\tExpression string `json:\"-\" yaml:\"-\"`\n\tAll []string `json:\"all,omitempty\" yaml:\"all,omitempty\"`\n\tAny []string `json:\"any,omitempty\" yaml:\"any,omitempty\"`\n}\n\nfunc (eol ExpressionOrList) String() string {\n\tswitch {\n\tcase len(eol.Expression) != 0:\n\t\treturn eol.Expression\n\tcase len(eol.All) != 0:\n\t\tvar sb strings.Builder\n\t\tfor i, pred := range eol.All {\n\t\t\tif i != 0 {\n\t\t\t\tfmt.Fprintf(&sb, \" && \")\n\t\t\t}\n\t\t\tfmt.Fprintf(&sb, \"( %s )\", pred)\n\t\t}\n\t\treturn sb.String()\n\tcase len(eol.Any) != 0:\n\t\tvar sb strings.Builder\n\t\tfor i, pred := range eol.Any {\n\t\t\tif i != 0 {\n\t\t\t\tfmt.Fprintf(&sb, \" || \")\n\t\t\t}\n\t\t\tfmt.Fprintf(&sb, \"( %s )\", pred)\n\t\t}\n\t\treturn sb.String()\n\t}\n\tpanic(\"this should not happen\")\n}\n\nfunc (eol ExpressionOrList) Equal(rhs *ExpressionOrList) bool {\n\tif eol.Expression != rhs.Expression {\n\t\treturn false\n\t}\n\n\tif !slices.Equal(eol.All, rhs.All) {\n\t\treturn false\n\t}\n\n\tif !slices.Equal(eol.Any, rhs.Any) {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\nfunc (eol *ExpressionOrList) MarshalYAML() (any, error) {\n\tswitch {\n\tcase len(eol.All) == 1 && len(eol.Any) == 0:\n\t\teol.Expression = eol.All[0]\n\t\teol.All = nil\n\tcase len(eol.Any) == 1 && len(eol.All) == 0:\n\t\teol.Expression = eol.Any[0]\n\t\teol.Any = nil\n\t}\n\n\tif eol.Expression != \"\" {\n\t\treturn eol.Expression, nil\n\t}\n\n\ttype RawExpressionOrList ExpressionOrList\n\treturn RawExpressionOrList(*eol), nil\n}\n\nfunc (eol *ExpressionOrList) MarshalJSON() ([]byte, error) {\n\tswitch {\n\tcase len(eol.All) == 1 && len(eol.Any) == 0:\n\t\teol.Expression = eol.All[0]\n\t\teol.All = nil\n\tcase len(eol.Any) == 1 && len(eol.All) == 0:\n\t\teol.Expression = eol.Any[0]\n\t\teol.Any = nil\n\t}\n\n\tif eol.Expression != \"\" {\n\t\treturn json.Marshal(string(eol.Expression))\n\t}\n\n\ttype RawExpressionOrList ExpressionOrList\n\tval := RawExpressionOrList(*eol)\n\treturn json.Marshal(val)\n}\n\nfunc (eol *ExpressionOrList) UnmarshalJSON(data []byte) error {\n\tswitch string(data[0]) {\n\tcase `\"`: // string\n\t\treturn json.Unmarshal(data, &eol.Expression)\n\tcase \"{\": // object\n\t\ttype RawExpressionOrList ExpressionOrList\n\t\tvar val RawExpressionOrList\n\t\tif err := json.Unmarshal(data, &val); err != nil {\n\t\t\treturn err\n\t\t}\n\t\teol.All = val.All\n\t\teol.Any = val.Any\n\n\t\treturn nil\n\t}\n\n\treturn ErrExpressionOrListMustBeStringOrObject\n}\n\nfunc (eol *ExpressionOrList) Valid() error {\n\tif eol.Expression == \"\" && len(eol.All) == 0 && len(eol.Any) == 0 {\n\t\treturn ErrExpressionEmpty\n\t}\n\tif len(eol.All) != 0 && len(eol.Any) != 0 {\n\t\treturn ErrExpressionCantHaveBoth\n\t}\n\n\treturn nil\n}\n"], ["/anubis/lib/store/memory/memory.go", "package memory\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/TecharoHQ/anubis/decaymap\"\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n)\n\ntype factory struct{}\n\nfunc (factory) Build(ctx context.Context, _ json.RawMessage) (store.Interface, error) {\n\treturn New(ctx), nil\n}\n\nfunc (factory) Valid(json.RawMessage) error { return nil }\n\nfunc init() {\n\tstore.Register(\"memory\", factory{})\n}\n\ntype impl struct {\n\tstore *decaymap.Impl[string, []byte]\n}\n\nfunc (i *impl) Delete(_ context.Context, key string) error {\n\tif !i.store.Delete(key) {\n\t\treturn fmt.Errorf(\"%w: %q\", store.ErrNotFound, key)\n\t}\n\n\treturn nil\n}\n\nfunc (i *impl) Get(_ context.Context, key string) ([]byte, error) {\n\tresult, ok := i.store.Get(key)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"%w: %q\", store.ErrNotFound, key)\n\t}\n\n\treturn result, nil\n}\n\nfunc (i *impl) Set(_ context.Context, key string, value []byte, expiry time.Duration) error {\n\ti.store.Set(key, value, expiry)\n\treturn nil\n}\n\nfunc (i *impl) cleanupThread(ctx context.Context) {\n\tt := time.NewTicker(5 * time.Minute)\n\tdefer t.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase <-t.C:\n\t\t\ti.store.Cleanup()\n\t\t}\n\t}\n}\n\n// New creates a simple in-memory store. This will not scale to multiple Anubis instances.\nfunc New(ctx context.Context) store.Interface {\n\tresult := &impl{\n\t\tstore: decaymap.New[string, []byte](),\n\t}\n\n\tgo result.cleanupThread(ctx)\n\n\treturn result\n}\n"], ["/anubis/lib/policy/celchecker.go", "package policy\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"github.com/TecharoHQ/anubis/internal\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/expressions\"\n\t\"github.com/google/cel-go/cel\"\n\t\"github.com/google/cel-go/common/types\"\n)\n\ntype CELChecker struct {\n\tprogram cel.Program\n\tsrc string\n}\n\nfunc NewCELChecker(cfg *config.ExpressionOrList) (*CELChecker, error) {\n\tenv, err := expressions.BotEnvironment()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tprogram, err := expressions.Compile(env, cfg.String())\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't compile CEL program: %w\", err)\n\t}\n\n\treturn &CELChecker{\n\t\tsrc: cfg.String(),\n\t\tprogram: program,\n\t}, nil\n}\n\nfunc (cc *CELChecker) Hash() string {\n\treturn internal.FastHash(cc.src)\n}\n\nfunc (cc *CELChecker) Check(r *http.Request) (bool, error) {\n\tresult, _, err := cc.program.ContextEval(r.Context(), &CELRequest{r})\n\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tif val, ok := result.(types.Bool); ok {\n\t\treturn bool(val), nil\n\t}\n\n\treturn false, nil\n}\n\ntype CELRequest struct {\n\t*http.Request\n}\n\nfunc (cr *CELRequest) Parent() cel.Activation { return nil }\n\nfunc (cr *CELRequest) ResolveName(name string) (any, bool) {\n\tswitch name {\n\tcase \"remoteAddress\":\n\t\treturn cr.Header.Get(\"X-Real-Ip\"), true\n\tcase \"host\":\n\t\treturn cr.Host, true\n\tcase \"method\":\n\t\treturn cr.Method, true\n\tcase \"userAgent\":\n\t\treturn cr.UserAgent(), true\n\tcase \"path\":\n\t\treturn cr.URL.Path, true\n\tcase \"query\":\n\t\treturn expressions.URLValues{Values: cr.URL.Query()}, true\n\tcase \"headers\":\n\t\treturn expressions.HTTPHeaders{Header: cr.Header}, true\n\tcase \"load_1m\":\n\t\treturn expressions.Load1(), true\n\tcase \"load_5m\":\n\t\treturn expressions.Load5(), true\n\tcase \"load_15m\":\n\t\treturn expressions.Load15(), true\n\tdefault:\n\t\treturn nil, false\n\t}\n}\n"], ["/anubis/lib/policy/expressions/http_headers.go", "package expressions\n\nimport (\n\t\"net/http\"\n\t\"reflect\"\n\t\"strings\"\n\n\t\"github.com/google/cel-go/common/types\"\n\t\"github.com/google/cel-go/common/types/ref\"\n\t\"github.com/google/cel-go/common/types/traits\"\n)\n\n// HTTPHeaders is a type wrapper to expose HTTP headers into CEL programs.\ntype HTTPHeaders struct {\n\thttp.Header\n}\n\nfunc (h HTTPHeaders) ConvertToNative(typeDesc reflect.Type) (any, error) {\n\treturn nil, ErrNotImplemented\n}\n\nfunc (h HTTPHeaders) ConvertToType(typeVal ref.Type) ref.Val {\n\tswitch typeVal {\n\tcase types.MapType:\n\t\treturn h\n\tcase types.TypeType:\n\t\treturn types.MapType\n\t}\n\n\treturn types.NewErr(\"can't convert from %q to %q\", types.MapType, typeVal)\n}\n\nfunc (h HTTPHeaders) Equal(other ref.Val) ref.Val {\n\treturn types.Bool(false) // We don't want to compare header maps\n}\n\nfunc (h HTTPHeaders) Type() ref.Type {\n\treturn types.MapType\n}\n\nfunc (h HTTPHeaders) Value() any { return h }\n\nfunc (h HTTPHeaders) Find(key ref.Val) (ref.Val, bool) {\n\tk, ok := key.(types.String)\n\tif !ok {\n\t\treturn nil, false\n\t}\n\n\tif _, ok := h.Header[string(k)]; !ok {\n\t\treturn nil, false\n\t}\n\n\treturn types.String(strings.Join(h.Header.Values(string(k)), \",\")), true\n}\n\nfunc (h HTTPHeaders) Contains(key ref.Val) ref.Val {\n\t_, ok := h.Find(key)\n\treturn types.Bool(ok)\n}\n\nfunc (h HTTPHeaders) Get(key ref.Val) ref.Val {\n\tresult, ok := h.Find(key)\n\tif !ok {\n\t\treturn types.ValOrErr(result, \"no such key: %v\", key)\n\t}\n\treturn result\n}\n\nfunc (h HTTPHeaders) Iterator() traits.Iterator { panic(\"TODO(Xe): implement me\") }\n\nfunc (h HTTPHeaders) IsZeroValue() bool {\n\treturn len(h.Header) == 0\n}\n\nfunc (h HTTPHeaders) Size() ref.Val { return types.Int(len(h.Header)) }\n"], ["/anubis/lib/thoth/thothmock/iptoasn.go", "package thothmock\n\nimport (\n\t\"context\"\n\t\"net/netip\"\n\n\tiptoasnv1 \"github.com/TecharoHQ/thoth-proto/gen/techaro/thoth/iptoasn/v1\"\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/status\"\n)\n\nfunc MockIpToASNService() *IpToASNService {\n\tresponses := map[string]*iptoasnv1.LookupResponse{\n\t\t\"127.0.0.1\": {Announced: false},\n\t\t\"::1\": {Announced: false},\n\t\t\"10.10.10.10\": {\n\t\t\tAnnounced: true,\n\t\t\tAsNumber: 13335,\n\t\t\tCidr: []string{\"1.1.1.0/24\"},\n\t\t\tCountryCode: \"US\",\n\t\t\tDescription: \"Cloudflare\",\n\t\t},\n\t\t\"2.2.2.2\": {\n\t\t\tAnnounced: true,\n\t\t\tAsNumber: 420,\n\t\t\tCidr: []string{\"2.2.2.0/24\"},\n\t\t\tCountryCode: \"CA\",\n\t\t\tDescription: \"test canada\",\n\t\t},\n\t\t\"1.1.1.1\": {\n\t\t\tAnnounced: true,\n\t\t\tAsNumber: 13335,\n\t\t\tCidr: []string{\"1.1.1.0/24\"},\n\t\t\tCountryCode: \"US\",\n\t\t\tDescription: \"Cloudflare\",\n\t\t},\n\t}\n\n\treturn &IpToASNService{Responses: responses}\n}\n\ntype IpToASNService struct {\n\tiptoasnv1.UnimplementedIpToASNServiceServer\n\tResponses map[string]*iptoasnv1.LookupResponse\n}\n\nfunc (ip2asn *IpToASNService) Lookup(ctx context.Context, lr *iptoasnv1.LookupRequest, opts ...grpc.CallOption) (*iptoasnv1.LookupResponse, error) {\n\tif _, err := netip.ParseAddr(lr.GetIpAddress()); err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, ok := ip2asn.Responses[lr.GetIpAddress()]\n\tif !ok {\n\t\treturn nil, status.Error(codes.NotFound, \"IP address not found in mock\")\n\t}\n\n\treturn resp, nil\n}\n"], ["/anubis/lib/challenge/metarefresh/metarefresh_templ.go", "// Code generated by templ - DO NOT EDIT.\n\n// templ: version: v0.3.906\npackage metarefresh\n\n//lint:file-ignore SA4006 This context is only used if a nested component is present.\n\nimport \"github.com/a-h/templ\"\nimport templruntime \"github.com/a-h/templ/runtime\"\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/TecharoHQ/anubis/lib/localization\"\n)\n\nfunc page(redir string, difficulty int, loc *localization.SimpleLocalizer) templ.Component {\n\treturn templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {\n\t\ttempl_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context\n\t\tif templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {\n\t\t\treturn templ_7745c5c3_CtxErr\n\t\t}\n\t\ttempl_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)\n\t\tif !templ_7745c5c3_IsBuffer {\n\t\t\tdefer func() {\n\t\t\t\ttempl_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)\n\t\t\t\tif templ_7745c5c3_Err == nil {\n\t\t\t\t\ttempl_7745c5c3_Err = templ_7745c5c3_BufErr\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\tctx = templ.InitializeContext(ctx)\n\t\ttempl_7745c5c3_Var1 := templ.GetChildren(ctx)\n\t\tif templ_7745c5c3_Var1 == nil {\n\t\t\ttempl_7745c5c3_Var1 = templ.NopComponent\n\t\t}\n\t\tctx = templ.ClearChildren(ctx)\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var4 string\n\t\ttempl_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(loc.T(\"loading\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `metarefresh.templ`, Line: 14, Col: 35}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var5 string\n\t\ttempl_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(loc.T(\"connection_security\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `metarefresh.templ`, Line: 15, Col: 35}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\treturn nil\n\t})\n}\n\nvar _ = templruntime.GeneratedTemplate\n"], ["/anubis/lib/policy/expressions/loadavg.go", "package expressions\n\nimport (\n\t\"context\"\n\t\"log/slog\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/shirou/gopsutil/v4/load\"\n)\n\ntype loadAvg struct {\n\tlock sync.RWMutex\n\tdata *load.AvgStat\n}\n\nfunc (l *loadAvg) updateThread(ctx context.Context) {\n\tticker := time.NewTicker(15 * time.Second)\n\tdefer ticker.Stop()\n\n\tl.update()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tl.update()\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (l *loadAvg) update() {\n\tl.lock.Lock()\n\tdefer l.lock.Unlock()\n\n\tvar err error\n\tl.data, err = load.Avg()\n\tif err != nil {\n\t\tslog.Debug(\"can't get load average\", \"err\", err)\n\t}\n}\n\nvar (\n\tglobalLoadAvg *loadAvg\n)\n\nfunc init() {\n\tglobalLoadAvg = &loadAvg{}\n\tgo globalLoadAvg.updateThread(context.Background())\n}\n\nfunc Load1() float64 {\n\tglobalLoadAvg.lock.RLock()\n\tdefer globalLoadAvg.lock.RUnlock()\n\treturn globalLoadAvg.data.Load1\n}\n\nfunc Load5() float64 {\n\tglobalLoadAvg.lock.RLock()\n\tdefer globalLoadAvg.lock.RUnlock()\n\treturn globalLoadAvg.data.Load5\n}\n\nfunc Load15() float64 {\n\tglobalLoadAvg.lock.RLock()\n\tdefer globalLoadAvg.lock.RUnlock()\n\treturn globalLoadAvg.data.Load15\n}\n"], ["/anubis/web/index_templ.go", "// Code generated by templ - DO NOT EDIT.\n\n// templ: version: v0.3.906\npackage web\n\n//lint:file-ignore SA4006 This context is only used if a nested component is present.\n\nimport \"github.com/a-h/templ\"\nimport templruntime \"github.com/a-h/templ/runtime\"\n\nimport (\n\t\"fmt\"\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/TecharoHQ/anubis/lib/localization\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/xess\"\n)\n\nfunc base(title string, body templ.Component, impressum *config.Impressum, challenge any, ogTags map[string]string, localizer *localization.SimpleLocalizer) templ.Component {\n\treturn templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {\n\t\ttempl_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context\n\t\tif templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {\n\t\t\treturn templ_7745c5c3_CtxErr\n\t\t}\n\t\ttempl_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)\n\t\tif !templ_7745c5c3_IsBuffer {\n\t\t\tdefer func() {\n\t\t\t\ttempl_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)\n\t\t\t\tif templ_7745c5c3_Err == nil {\n\t\t\t\t\ttempl_7745c5c3_Err = templ_7745c5c3_BufErr\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\tctx = templ.InitializeContext(ctx)\n\t\ttempl_7745c5c3_Var1 := templ.GetChildren(ctx)\n\t\tif templ_7745c5c3_Var1 == nil {\n\t\t\ttempl_7745c5c3_Var1 = templ.NopComponent\n\t\t}\n\t\tctx = templ.ClearChildren(ctx)\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, \"\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var3 string\n\t\ttempl_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(title)\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 15, Col: 17}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 3, \"\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tfor key, value := range ogTags {\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, \"\")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, \"\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templ.JSONScript(\"anubis_version\", anubis.Version).Render(ctx, templ_7745c5c3_Buffer)\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tif challenge != nil {\n\t\t\ttempl_7745c5c3_Err = templ.JSONScript(\"anubis_challenge\", challenge).Render(ctx, templ_7745c5c3_Buffer)\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t}\n\t\ttempl_7745c5c3_Err = templ.JSONScript(\"anubis_base_prefix\", anubis.BasePrefix).Render(ctx, templ_7745c5c3_Buffer)\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var7 string\n\t\ttempl_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(title)\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 68, Col: 47}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 10, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = body.Render(ctx, templ_7745c5c3_Buffer)\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var8 string\n\t\ttempl_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"protected_by\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 73, Col: 36}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, \" Anubis \")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var9 string\n\t\ttempl_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"protected_from\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 73, Col: 127}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, \" Techaro. \")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var10 string\n\t\ttempl_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"made_with\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 75, Col: 40}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 14, \".

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var11 string\n\t\ttempl_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"mascot_design\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 77, Col: 39}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, \" \")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var12 string\n\t\ttempl_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"celphase\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 77, Col: 123}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, \".

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tif impressum != nil {\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, \"

\")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\ttempl_7745c5c3_Err = templ.Raw(impressum.Footer).Render(ctx, templ_7745c5c3_Buffer)\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 18, \"-- Imprint

\")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 20, \"
\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\treturn nil\n\t})\n}\n\nfunc index(localizer *localization.SimpleLocalizer) templ.Component {\n\treturn templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {\n\t\ttempl_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context\n\t\tif templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {\n\t\t\treturn templ_7745c5c3_CtxErr\n\t\t}\n\t\ttempl_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)\n\t\tif !templ_7745c5c3_IsBuffer {\n\t\t\tdefer func() {\n\t\t\t\ttempl_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)\n\t\t\t\tif templ_7745c5c3_Err == nil {\n\t\t\t\t\ttempl_7745c5c3_Err = templ_7745c5c3_BufErr\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\tctx = templ.InitializeContext(ctx)\n\t\ttempl_7745c5c3_Var14 := templ.GetChildren(ctx)\n\t\tif templ_7745c5c3_Var14 == nil {\n\t\t\ttempl_7745c5c3_Var14 = templ.NopComponent\n\t\t}\n\t\tctx = templ.ClearChildren(ctx)\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 21, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var17 string\n\t\ttempl_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"loading\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 95, Col: 41}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var17))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 24, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var19 string\n\t\ttempl_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"why_am_i_seeing\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 101, Col: 44}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var19))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 26, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var20 string\n\t\ttempl_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"ai_companies_explanation\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 103, Col: 45}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var20))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 27, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var21 string\n\t\ttempl_7745c5c3_Var21, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"anubis_compromise\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 106, Col: 38}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var21))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var22 string\n\t\ttempl_7745c5c3_Var22, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"hack_purpose\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 109, Col: 33}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var22))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var23 string\n\t\ttempl_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"jshelter_note\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 112, Col: 34}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var23))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 30, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var24 string\n\t\ttempl_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"version_info\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 114, Col: 35}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var24))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 31, \" \")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var25 string\n\t\ttempl_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinStringErrs(anubis.Version)\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 114, Col: 60}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var25))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 32, \".

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\treturn nil\n\t})\n}\n\nfunc errorPage(message, mail string, localizer *localization.SimpleLocalizer) templ.Component {\n\treturn templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {\n\t\ttempl_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context\n\t\tif templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {\n\t\t\treturn templ_7745c5c3_CtxErr\n\t\t}\n\t\ttempl_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)\n\t\tif !templ_7745c5c3_IsBuffer {\n\t\t\tdefer func() {\n\t\t\t\ttempl_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)\n\t\t\t\tif templ_7745c5c3_Err == nil {\n\t\t\t\t\ttempl_7745c5c3_Err = templ_7745c5c3_BufErr\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\tctx = templ.InitializeContext(ctx)\n\t\ttempl_7745c5c3_Var27 := templ.GetChildren(ctx)\n\t\tif templ_7745c5c3_Var27 == nil {\n\t\t\ttempl_7745c5c3_Var27 = templ.NopComponent\n\t\t}\n\t\tctx = templ.ClearChildren(ctx)\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 34, \"
\\\"Sad

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var29 string\n\t\ttempl_7745c5c3_Var29, templ_7745c5c3_Err = templ.JoinStringErrs(message)\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 128, Col: 14}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var29))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 36, \".

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tif mail != \"\" {\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 37, \"

\")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\tvar templ_7745c5c3_Var30 string\n\t\t\ttempl_7745c5c3_Var30, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"go_home\"))\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 131, Col: 40}\n\t\t\t}\n\t\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var30))\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 38, \" \")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\tvar templ_7745c5c3_Var31 string\n\t\t\ttempl_7745c5c3_Var31, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"contact_webmaster\"))\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 131, Col: 81}\n\t\t\t}\n\t\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var31))\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 39, \" \")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\tvar templ_7745c5c3_Var33 string\n\t\t\ttempl_7745c5c3_Var33, templ_7745c5c3_Err = templ.JoinStringErrs(mail)\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 133, Col: 11}\n\t\t\t}\n\t\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var33))\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 41, \"

\")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t} else {\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 42, \"

\")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\tvar templ_7745c5c3_Var34 string\n\t\t\ttempl_7745c5c3_Var34, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"go_home\"))\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 137, Col: 42}\n\t\t\t}\n\t\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var34))\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 43, \"

\")\n\t\t\tif templ_7745c5c3_Err != nil {\n\t\t\t\treturn templ_7745c5c3_Err\n\t\t\t}\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 44, \"
\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\treturn nil\n\t})\n}\n\nfunc StaticHappy(localizer *localization.SimpleLocalizer) templ.Component {\n\treturn templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {\n\t\ttempl_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context\n\t\tif templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {\n\t\t\treturn templ_7745c5c3_CtxErr\n\t\t}\n\t\ttempl_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)\n\t\tif !templ_7745c5c3_IsBuffer {\n\t\t\tdefer func() {\n\t\t\t\ttempl_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)\n\t\t\t\tif templ_7745c5c3_Err == nil {\n\t\t\t\t\ttempl_7745c5c3_Err = templ_7745c5c3_BufErr\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\tctx = templ.InitializeContext(ctx)\n\t\ttempl_7745c5c3_Var35 := templ.GetChildren(ctx)\n\t\tif templ_7745c5c3_Var35 == nil {\n\t\t\ttempl_7745c5c3_Var35 = templ.NopComponent\n\t\t}\n\t\tctx = templ.ClearChildren(ctx)\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 45, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var37 string\n\t\ttempl_7745c5c3_Var37, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"static_check_endpoint\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 150, Col: 43}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var37))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 47, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\treturn nil\n\t})\n}\n\nfunc bench(localizer *localization.SimpleLocalizer) templ.Component {\n\treturn templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {\n\t\ttempl_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context\n\t\tif templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {\n\t\t\treturn templ_7745c5c3_CtxErr\n\t\t}\n\t\ttempl_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)\n\t\tif !templ_7745c5c3_IsBuffer {\n\t\t\tdefer func() {\n\t\t\t\ttempl_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)\n\t\t\t\tif templ_7745c5c3_Err == nil {\n\t\t\t\t\ttempl_7745c5c3_Err = templ_7745c5c3_BufErr\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\t\tctx = templ.InitializeContext(ctx)\n\t\ttempl_7745c5c3_Var38 := templ.GetChildren(ctx)\n\t\tif templ_7745c5c3_Var38 == nil {\n\t\t\ttempl_7745c5c3_Var38 = templ.NopComponent\n\t\t}\n\t\tctx = templ.ClearChildren(ctx)\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 48, \"
\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var39 string\n\t\ttempl_7745c5c3_Var39, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"time\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 161, Col: 51}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var39))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 49, \"\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var40 string\n\t\ttempl_7745c5c3_Var40, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"iters\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 162, Col: 50}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var40))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 50, \"
\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var41 string\n\t\ttempl_7745c5c3_Var41, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"time_a\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 165, Col: 53}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var41))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 51, \"\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var42 string\n\t\ttempl_7745c5c3_Var42, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"iters_a\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 166, Col: 52}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var42))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 52, \"\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var43 string\n\t\ttempl_7745c5c3_Var43, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"time_b\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 167, Col: 53}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var43))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 53, \"\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var44 string\n\t\ttempl_7745c5c3_Var44, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"iters_b\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 168, Col: 52}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var44))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 54, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\tvar templ_7745c5c3_Var46 string\n\t\ttempl_7745c5c3_Var46, templ_7745c5c3_Err = templ.JoinStringErrs(localizer.T(\"loading\"))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ.Error{Err: templ_7745c5c3_Err, FileName: `index.templ`, Line: 178, Col: 66}\n\t\t}\n\t\t_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var46))\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\ttempl_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 56, \"

\")\n\t\tif templ_7745c5c3_Err != nil {\n\t\t\treturn templ_7745c5c3_Err\n\t\t}\n\t\treturn nil\n\t})\n}\n\nvar _ = templruntime.GeneratedTemplate\n"], ["/anubis/xess/xess.go", "// Package xess vendors a copy of Xess and makes it available at /.xess/xess.css\n//\n// This is intended to be used as a vendored package in other projects.\npackage xess\n\nimport (\n\t\"embed\"\n\t\"net/http\"\n\t\"path/filepath\"\n\n\t\"github.com/TecharoHQ/anubis\"\n\t\"github.com/TecharoHQ/anubis/internal\"\n)\n\nvar (\n\t//go:embed *.css static\n\tStatic embed.FS\n\n\tURL = \"/.within.website/x/xess/xess.css\"\n)\n\nfunc init() {\n\tMount(http.DefaultServeMux)\n\n\t//goland:noinspection GoBoolExpressions\n\tif anubis.Version != \"devel\" {\n\t\tURL = filepath.Join(filepath.Dir(URL), \"xess.min.css\")\n\t}\n\n\tURL = URL + \"?cachebuster=\" + anubis.Version\n}\n\n// Mount registers the xess static file handlers on the given mux\nfunc Mount(mux *http.ServeMux) {\n\tprefix := anubis.BasePrefix + \"/.within.website/x/xess/\"\n\n\tmux.Handle(prefix, internal.UnchangingCache(http.StripPrefix(prefix, http.FileServerFS(Static))))\n}\n"], ["/anubis/lib/challenge/error.go", "package challenge\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net/http\"\n)\n\nvar (\n\tErrFailed = errors.New(\"challenge: user failed challenge\")\n\tErrMissingField = errors.New(\"challenge: missing field\")\n\tErrInvalidFormat = errors.New(\"challenge: field has invalid format\")\n)\n\nfunc NewError(verb, publicReason string, privateReason error) *Error {\n\treturn &Error{\n\t\tVerb: verb,\n\t\tPublicReason: publicReason,\n\t\tPrivateReason: privateReason,\n\t\tStatusCode: http.StatusForbidden,\n\t}\n}\n\ntype Error struct {\n\tPrivateReason error\n\tVerb string\n\tPublicReason string\n\tStatusCode int\n}\n\nfunc (e *Error) Error() string {\n\treturn fmt.Sprintf(\"challenge: error when processing challenge: %s: %v\", e.Verb, e.PrivateReason)\n}\n\nfunc (e *Error) Unwrap() error {\n\treturn e.PrivateReason\n}\n"], ["/anubis/internal/unbreakdocker.go", "package internal\n\nimport (\n\t\"os\"\n\t\"os/exec\"\n)\n\nfunc UnbreakDocker() {\n\t// XXX(Xe): This is bad code. Do not do this.\n\t//\n\t// I have to do this because I'm running from inside the context of a dev\n\t// container. This dev container runs in a different docker network than\n\t// the valkey test container runs in. In order to let my dev container\n\t// connect to the test container, they need to share a network in common.\n\t// The easiest network to use for this is the default \"bridge\" network.\n\t//\n\t// This is a horrifying monstrosity, but the part that scares me the most\n\t// is the fact that it works.\n\tif hostname, err := os.Hostname(); err == nil {\n\t\texec.Command(\"docker\", \"network\", \"connect\", \"bridge\", hostname).Run()\n\t}\n}\n"], ["/anubis/lib/policy/checker/checker.go", "// Package checker defines the Checker interface and a helper utility to avoid import cycles.\npackage checker\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"strings\"\n\n\t\"github.com/TecharoHQ/anubis/internal\"\n)\n\ntype Impl interface {\n\tCheck(*http.Request) (bool, error)\n\tHash() string\n}\n\ntype List []Impl\n\nfunc (l List) Check(r *http.Request) (bool, error) {\n\tfor _, c := range l {\n\t\tok, err := c.Check(r)\n\t\tif err != nil {\n\t\t\treturn ok, err\n\t\t}\n\t\tif ok {\n\t\t\treturn ok, nil\n\t\t}\n\t}\n\n\treturn false, nil\n}\n\nfunc (l List) Hash() string {\n\tvar sb strings.Builder\n\n\tfor _, c := range l {\n\t\tfmt.Fprintln(&sb, c.Hash())\n\t}\n\n\treturn internal.FastHash(sb.String())\n}\n"], ["/anubis/decaymap/decaymap.go", "package decaymap\n\nimport (\n\t\"sync\"\n\t\"time\"\n)\n\nfunc Zilch[T any]() T {\n\tvar zero T\n\treturn zero\n}\n\n// Impl is a lazy key->value map. It's a wrapper around a map and a mutex. If values exceed their time-to-live, they are pruned at Get time.\ntype Impl[K comparable, V any] struct {\n\tdata map[K]decayMapEntry[V]\n\tlock sync.RWMutex\n}\n\ntype decayMapEntry[V any] struct {\n\tValue V\n\texpiry time.Time\n}\n\n// New creates a new DecayMap of key type K and value type V.\n//\n// Key types must be comparable to work with maps.\nfunc New[K comparable, V any]() *Impl[K, V] {\n\treturn &Impl[K, V]{\n\t\tdata: make(map[K]decayMapEntry[V]),\n\t}\n}\n\n// expire forcibly expires a key by setting its time-to-live one second in the past.\nfunc (m *Impl[K, V]) expire(key K) bool {\n\tm.lock.RLock()\n\tval, ok := m.data[key]\n\tm.lock.RUnlock()\n\n\tif !ok {\n\t\treturn false\n\t}\n\n\tm.lock.Lock()\n\tval.expiry = time.Now().Add(-1 * time.Second)\n\tm.data[key] = val\n\tm.lock.Unlock()\n\n\treturn true\n}\n\n// Delete a value from the DecayMap by key.\n//\n// If the value does not exist, return false. Return true after\n// deletion.\nfunc (m *Impl[K, V]) Delete(key K) bool {\n\tm.lock.RLock()\n\t_, ok := m.data[key]\n\tm.lock.RUnlock()\n\n\tif !ok {\n\t\treturn false\n\t}\n\n\tm.lock.Lock()\n\tdelete(m.data, key)\n\tm.lock.Unlock()\n\n\treturn true\n}\n\n// Get gets a value from the DecayMap by key.\n//\n// If a value has expired, forcibly delete it if it was not updated.\nfunc (m *Impl[K, V]) Get(key K) (V, bool) {\n\tm.lock.RLock()\n\tvalue, ok := m.data[key]\n\tm.lock.RUnlock()\n\n\tif !ok {\n\t\treturn Zilch[V](), false\n\t}\n\n\tif time.Now().After(value.expiry) {\n\t\tm.lock.Lock()\n\t\t// Since previously reading m.data[key], the value may have been updated.\n\t\t// Delete the entry only if the expiry time is still the same.\n\t\tif m.data[key].expiry.Equal(value.expiry) {\n\t\t\tdelete(m.data, key)\n\t\t}\n\t\tm.lock.Unlock()\n\n\t\treturn Zilch[V](), false\n\t}\n\n\treturn value.Value, true\n}\n\n// Set sets a key value pair in the map.\nfunc (m *Impl[K, V]) Set(key K, value V, ttl time.Duration) {\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\n\tm.data[key] = decayMapEntry[V]{\n\t\tValue: value,\n\t\texpiry: time.Now().Add(ttl),\n\t}\n}\n\n// Cleanup removes all expired entries from the DecayMap.\nfunc (m *Impl[K, V]) Cleanup() {\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\n\tnow := time.Now()\n\tfor key, entry := range m.data {\n\t\tif now.After(entry.expiry) {\n\t\t\tdelete(m.data, key)\n\t\t}\n\t}\n}\n\n// Len returns the number of entries in the DecayMap.\nfunc (m *Impl[K, V]) Len() int {\n\tm.lock.RLock()\n\tdefer m.lock.RUnlock()\n\treturn len(m.data)\n}\n"], ["/anubis/lib/challenge/interface.go", "package challenge\n\nimport (\n\t\"log/slog\"\n\t\"net/http\"\n\t\"sort\"\n\t\"sync\"\n\n\t\"github.com/TecharoHQ/anubis/lib/policy\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/lib/store\"\n\t\"github.com/a-h/templ\"\n)\n\nvar (\n\tregistry map[string]Impl = map[string]Impl{}\n\tregLock sync.RWMutex\n)\n\nfunc Register(name string, impl Impl) {\n\tregLock.Lock()\n\tdefer regLock.Unlock()\n\n\tregistry[name] = impl\n}\n\nfunc Get(name string) (Impl, bool) {\n\tregLock.RLock()\n\tdefer regLock.RUnlock()\n\tresult, ok := registry[name]\n\treturn result, ok\n}\n\nfunc Methods() []string {\n\tregLock.RLock()\n\tdefer regLock.RUnlock()\n\tvar result []string\n\tfor method := range registry {\n\t\tresult = append(result, method)\n\t}\n\tsort.Strings(result)\n\treturn result\n}\n\ntype IssueInput struct {\n\tImpressum *config.Impressum\n\tRule *policy.Bot\n\tChallenge *Challenge\n\tOGTags map[string]string\n\tStore store.Interface\n}\n\ntype ValidateInput struct {\n\tRule *policy.Bot\n\tChallenge *Challenge\n\tStore store.Interface\n}\n\ntype Impl interface {\n\t// Setup registers any additional routes with the Impl for assets or API routes.\n\tSetup(mux *http.ServeMux)\n\n\t// Issue a new challenge to the user, called by the Anubis.\n\tIssue(r *http.Request, lg *slog.Logger, in *IssueInput) (templ.Component, error)\n\n\t// Validate a challenge, making sure that it passes muster.\n\tValidate(r *http.Request, lg *slog.Logger, in *ValidateInput) error\n}\n"], ["/anubis/lib/thoth/auth.go", "package thoth\n\nimport (\n\t\"context\"\n\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/metadata\"\n)\n\nfunc authUnaryClientInterceptor(token string) grpc.UnaryClientInterceptor {\n\treturn func(\n\t\tctx context.Context,\n\t\tmethod string,\n\t\treq interface{},\n\t\treply interface{},\n\t\tcc *grpc.ClientConn,\n\t\tinvoker grpc.UnaryInvoker,\n\t\topts ...grpc.CallOption,\n\t) error {\n\t\tmd := metadata.Pairs(\"authorization\", \"Bearer \"+token)\n\t\tctx = metadata.NewOutgoingContext(ctx, md)\n\t\treturn invoker(ctx, method, req, reply, cc, opts...)\n\t}\n}\n\nfunc authStreamClientInterceptor(token string) grpc.StreamClientInterceptor {\n\treturn func(\n\t\tctx context.Context,\n\t\tdesc *grpc.StreamDesc,\n\t\tcc *grpc.ClientConn,\n\t\tmethod string,\n\t\tstreamer grpc.Streamer,\n\t\topts ...grpc.CallOption,\n\t) (grpc.ClientStream, error) {\n\t\tmd := metadata.Pairs(\"authorization\", \"Bearer \"+token)\n\t\tctx = metadata.NewOutgoingContext(ctx, md)\n\t\treturn streamer(ctx, desc, cc, method, opts...)\n\t}\n}\n"], ["/anubis/internal/health.go", "package internal\n\nimport (\n\t\"context\"\n\n\t\"google.golang.org/grpc/health\"\n\thealthv1 \"google.golang.org/grpc/health/grpc_health_v1\"\n)\n\nvar HealthSrv = health.NewServer()\n\nfunc SetHealth(svc string, status healthv1.HealthCheckResponse_ServingStatus) {\n\tHealthSrv.SetServingStatus(svc, status)\n}\n\nfunc GetHealth(svc string) (healthv1.HealthCheckResponse_ServingStatus, bool) {\n\tst, err := HealthSrv.Check(context.Background(), &healthv1.HealthCheckRequest{\n\t\tService: svc,\n\t})\n\tif err != nil {\n\t\treturn healthv1.HealthCheckResponse_UNKNOWN, false\n\t}\n\n\treturn st.GetStatus(), true\n}\n"], ["/anubis/anubis.go", "// Package anubis contains the version number of Anubis.\npackage anubis\n\nimport \"time\"\n\n// Version is the current version of Anubis.\n//\n// This variable is set at build time using the -X linker flag. If not set,\n// it defaults to \"devel\".\nvar Version = \"devel\"\n\n// CookieName is the name of the cookie that Anubis uses in order to validate\n// access.\nvar CookieName = \"techaro.lol-anubis-auth\"\n\n// TestCookieName is the name of the cookie that Anubis uses in order to check\n// if cookies are enabled on the client's browser.\nvar TestCookieName = \"techaro.lol-anubis-cookie-verification\"\n\n// CookieDefaultExpirationTime is the amount of time before the cookie/JWT expires.\nconst CookieDefaultExpirationTime = 7 * 24 * time.Hour\n\n// BasePrefix is a global prefix for all Anubis endpoints. Can be emptied to remove the prefix entirely.\nvar BasePrefix = \"\"\n\n// StaticPath is the location where all static Anubis assets are located.\nconst StaticPath = \"/.within.website/x/cmd/anubis/\"\n\n// APIPrefix is the location where all Anubis API endpoints are located.\nconst APIPrefix = \"/.within.website/x/cmd/anubis/api/\"\n\n// DefaultDifficulty is the default \"difficulty\" (number of leading zeroes)\n// that must be met by the client in order to pass the challenge.\nconst DefaultDifficulty = 4\n\n// ForcedLanguage is the language being used instead of the one of the request's Accept-Language header\n// if being set.\nvar ForcedLanguage = \"\"\n"], ["/anubis/lib/policy/thresholds.go", "package policy\n\nimport (\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/expressions\"\n\t\"github.com/google/cel-go/cel\"\n)\n\ntype Threshold struct {\n\tconfig.Threshold\n\tProgram cel.Program\n}\n\nfunc ParsedThresholdFromConfig(t config.Threshold) (*Threshold, error) {\n\tresult := &Threshold{\n\t\tThreshold: t,\n\t}\n\n\tenv, err := expressions.ThresholdEnvironment()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tprogram, err := expressions.Compile(env, t.Expression.String())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult.Program = program\n\n\treturn result, nil\n}\n\ntype ThresholdRequest struct {\n\tWeight int\n}\n\nfunc (tr *ThresholdRequest) Parent() cel.Activation { return nil }\n\nfunc (tr *ThresholdRequest) ResolveName(name string) (any, bool) {\n\tswitch name {\n\tcase \"weight\":\n\t\treturn tr.Weight, true\n\tdefault:\n\t\treturn nil, false\n\t}\n}\n"], ["/anubis/internal/ja4h.go", "package internal\n\nimport (\n\t\"net/http\"\n\n\t\"github.com/lum8rjack/go-ja4h\"\n)\n\nfunc JA4H(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tr.Header.Add(\"X-Http-Fingerprint-JA4H\", ja4h.JA4H(r))\n\t\tnext.ServeHTTP(w, r)\n\t})\n}\n"], ["/anubis/internal/dnsbl/droneblresponse_string.go", "// Code generated by \"stringer -type=DroneBLResponse\"; DO NOT EDIT.\n\npackage dnsbl\n\nimport \"strconv\"\n\nfunc _() {\n\t// An \"invalid array index\" compiler error signifies that the constant values have changed.\n\t// Re-run the stringer command to generate them again.\n\tvar x [1]struct{}\n\t_ = x[AllGood-0]\n\t_ = x[IRCDrone-3]\n\t_ = x[Bottler-5]\n\t_ = x[UnknownSpambotOrDrone-6]\n\t_ = x[DDOSDrone-7]\n\t_ = x[SOCKSProxy-8]\n\t_ = x[HTTPProxy-9]\n\t_ = x[ProxyChain-10]\n\t_ = x[OpenProxy-11]\n\t_ = x[OpenDNSResolver-12]\n\t_ = x[BruteForceAttackers-13]\n\t_ = x[OpenWingateProxy-14]\n\t_ = x[CompromisedRouter-15]\n\t_ = x[AutoRootingWorms-16]\n\t_ = x[AutoDetectedBotIP-17]\n\t_ = x[Unknown-255]\n}\n\nconst (\n\t_DroneBLResponse_name_0 = \"AllGood\"\n\t_DroneBLResponse_name_1 = \"IRCDrone\"\n\t_DroneBLResponse_name_2 = \"BottlerUnknownSpambotOrDroneDDOSDroneSOCKSProxyHTTPProxyProxyChainOpenProxyOpenDNSResolverBruteForceAttackersOpenWingateProxyCompromisedRouterAutoRootingWormsAutoDetectedBotIP\"\n\t_DroneBLResponse_name_3 = \"Unknown\"\n)\n\nvar (\n\t_DroneBLResponse_index_2 = [...]uint8{0, 7, 28, 37, 47, 56, 66, 75, 90, 109, 125, 142, 158, 175}\n)\n\nfunc (i DroneBLResponse) String() string {\n\tswitch {\n\tcase i == 0:\n\t\treturn _DroneBLResponse_name_0\n\tcase i == 3:\n\t\treturn _DroneBLResponse_name_1\n\tcase 5 <= i && i <= 17:\n\t\ti -= 5\n\t\treturn _DroneBLResponse_name_2[_DroneBLResponse_index_2[i]:_DroneBLResponse_index_2[i+1]]\n\tcase i == 255:\n\t\treturn _DroneBLResponse_name_3\n\tdefault:\n\t\treturn \"DroneBLResponse(\" + strconv.FormatInt(int64(i), 10) + \")\"\n\t}\n}\n"], ["/anubis/lib/policy/checkresult.go", "package policy\n\nimport (\n\t\"log/slog\"\n\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n)\n\ntype CheckResult struct {\n\tName string\n\tRule config.Rule\n\tWeight int\n}\n\nfunc (cr CheckResult) LogValue() slog.Value {\n\treturn slog.GroupValue(\n\t\tslog.String(\"name\", cr.Name),\n\t\tslog.String(\"rule\", string(cr.Rule)),\n\t\tslog.Int(\"weight\", cr.Weight),\n\t)\n}\n"], ["/anubis/web/index.go", "package web\n\nimport (\n\t\"github.com/a-h/templ\"\n\n\t\"github.com/TecharoHQ/anubis/lib/localization\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n)\n\nfunc Base(title string, body templ.Component, impressum *config.Impressum, localizer *localization.SimpleLocalizer) templ.Component {\n\treturn base(title, body, impressum, nil, nil, localizer)\n}\n\nfunc BaseWithChallengeAndOGTags(title string, body templ.Component, impressum *config.Impressum, challenge string, rules *config.ChallengeRules, ogTags map[string]string, localizer *localization.SimpleLocalizer) (templ.Component, error) {\n\treturn base(title, body, impressum, struct {\n\t\tRules *config.ChallengeRules `json:\"rules\"`\n\t\tChallenge string `json:\"challenge\"`\n\t}{\n\t\tChallenge: challenge,\n\t\tRules: rules,\n\t}, ogTags, localizer), nil\n}\n\nfunc Index(localizer *localization.SimpleLocalizer) templ.Component {\n\treturn index(localizer)\n}\n\nfunc ErrorPage(msg, mail string, localizer *localization.SimpleLocalizer) templ.Component {\n\treturn errorPage(msg, mail, localizer)\n}\n\nfunc Bench(localizer *localization.SimpleLocalizer) templ.Component {\n\treturn bench(localizer)\n}\n"], ["/anubis/internal/hash.go", "package internal\n\nimport (\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"strconv\"\n\n\t\"github.com/cespare/xxhash/v2\"\n)\n\n// SHA256sum computes a cryptographic hash. Still used for proof-of-work challenges\n// where we need the security properties of a cryptographic hash function.\nfunc SHA256sum(text string) string {\n\thash := sha256.New()\n\thash.Write([]byte(text))\n\treturn hex.EncodeToString(hash.Sum(nil))\n}\n\n// FastHash is a high-performance non-cryptographic hash function suitable for\n// internal caching, policy rule identification, and other performance-critical\n// use cases where cryptographic security is not required.\nfunc FastHash(text string) string {\n\th := xxhash.Sum64String(text)\n\treturn strconv.FormatUint(h, 16)\n}\n"], ["/anubis/lib/store/registry.go", "package store\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"sort\"\n\t\"sync\"\n)\n\nvar (\n\tregistry map[string]Factory = map[string]Factory{}\n\tregLock sync.RWMutex\n)\n\ntype Factory interface {\n\tBuild(ctx context.Context, config json.RawMessage) (Interface, error)\n\tValid(config json.RawMessage) error\n}\n\nfunc Register(name string, impl Factory) {\n\tregLock.Lock()\n\tdefer regLock.Unlock()\n\n\tregistry[name] = impl\n}\n\nfunc Get(name string) (Factory, bool) {\n\tregLock.RLock()\n\tdefer regLock.RUnlock()\n\tresult, ok := registry[name]\n\treturn result, ok\n}\n\nfunc Methods() []string {\n\tregLock.RLock()\n\tdefer regLock.RUnlock()\n\tvar result []string\n\tfor method := range registry {\n\t\tresult = append(result, method)\n\t}\n\tsort.Strings(result)\n\treturn result\n}\n"], ["/anubis/lib/thoth/context.go", "package thoth\n\nimport \"context\"\n\ntype ctxKey struct{}\n\nfunc With(ctx context.Context, cli *Client) context.Context {\n\treturn context.WithValue(ctx, ctxKey{}, cli)\n}\n\nfunc FromContext(ctx context.Context) (*Client, bool) {\n\tcli, ok := ctx.Value(ctxKey{}).(*Client)\n\treturn cli, ok\n}\n"], ["/anubis/internal/mimetype.go", "package internal\n\nimport \"mime\"\n\nfunc init() {\n\tmime.AddExtensionType(\".mjs\", \"text/javascript\")\n}\n"], ["/anubis/lib/policy/bot.go", "package policy\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/TecharoHQ/anubis/internal\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/checker\"\n\t\"github.com/TecharoHQ/anubis/lib/policy/config\"\n)\n\ntype Bot struct {\n\tRules checker.Impl\n\tChallenge *config.ChallengeRules\n\tWeight *config.Weight\n\tName string\n\tAction config.Rule\n}\n\nfunc (b Bot) Hash() string {\n\treturn internal.FastHash(fmt.Sprintf(\"%s::%s\", b.Name, b.Rules.Hash()))\n}\n"], ["/anubis/lib/challenge/metrics.go", "package challenge\n\nimport (\n\t\"math\"\n\n\t\"github.com/prometheus/client_golang/prometheus\"\n\t\"github.com/prometheus/client_golang/prometheus/promauto\"\n)\n\nvar TimeTaken = promauto.NewHistogramVec(prometheus.HistogramOpts{\n\tName: \"anubis_time_taken\",\n\tHelp: \"The time taken for a browser to generate a response (milliseconds)\",\n\tBuckets: prometheus.ExponentialBucketsRange(1, math.Pow(2, 20), 20),\n}, []string{\"method\"})\n"], ["/anubis/lib/challenge/challenge.go", "package challenge\n\nimport \"time\"\n\n// Challenge is the metadata about a single challenge issuance.\ntype Challenge struct {\n\tID string `json:\"id\"` // UUID identifying the challenge\n\tRandomData string `json:\"randomData\"` // The random data the client processes\n\tIssuedAt time.Time `json:\"issuedAt\"` // When the challenge was issued\n\tMetadata map[string]string `json:\"metadata\"` // Challenge metadata such as IP address and user agent\n}\n"], ["/anubis/lib/store/all/all.go", "// Package all is a meta-package that imports all store implementations.\n//\n// This is a HACK to make tests work consistently.\npackage all\n\nimport (\n\t_ \"github.com/TecharoHQ/anubis/lib/store/bbolt\"\n\t_ \"github.com/TecharoHQ/anubis/lib/store/memory\"\n\t_ \"github.com/TecharoHQ/anubis/lib/store/valkey\"\n)\n"], ["/anubis/lib/thoth/thothmock/withthothmock.go", "package thothmock\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/TecharoHQ/anubis/lib/thoth\"\n)\n\nfunc WithMockThoth(t *testing.T) context.Context {\n\tt.Helper()\n\n\tthothCli := &thoth.Client{}\n\tthothCli.WithIPToASNService(MockIpToASNService())\n\tctx := thoth.With(t.Context(), thothCli)\n\treturn ctx\n}\n"], ["/anubis/web/embed.go", "package web\n\nimport \"embed\"\n\n//go:generate go tool github.com/a-h/templ/cmd/templ generate\n\nvar (\n\t//go:embed static\n\tStatic embed.FS\n)\n"], ["/anubis/data/embed.go", "package data\n\nimport \"embed\"\n\nvar (\n\t//go:embed botPolicies.yaml botPolicies.json all:apps all:bots all:clients all:common all:crawlers all:meta\n\tBotPolicies embed.FS\n)\n"], ["/anubis/lib/policy/config/weight.go", "package config\n\ntype Weight struct {\n\tAdjust int `json:\"adjust\" yaml:\"adjust\"`\n}\n"]], "task_instance_info": {"created_time": "2025-08-20 20:50:29", "created_task_model": "DeepSeek-R1", "function_skeleton": "func (c *OGTagCache) fetchHTMLDocumentWithCache (ctx context.Context, urlStr string, originalHost string, cacheKey string) (*html.Node, error) {}", "code_description": "This code segment functions to: Retrieve and validate web content from a specified URL while implementing error handling, content type verification, response size restrictions, and caching mechanisms for error states and processing outcomes."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```go\n[TASK_BEGIN]\nfunc (c *OGTagCache) fetchHTMLDocumentWithCache(ctx context.Context, urlStr string, originalHost string, cacheKey string) (*html.Node, error) {\n\tif cached, ok := c.cache.Get(cacheKey); ok {\n\t\tif m, ok := cached.(map[string]string); ok && len(m) == 0 {\n\t\t\treturn nil, fmt.Errorf(\"%w: empty cached result\", ErrOgHandled)\n\t\t}\n\t\t\n\t\thtmlStr, ok := cached.(string)\n\t\tif !ok {\n\t\t\treturn nil, errors.New(\"invalid cache entry type\")\n\t\t}\n\t\t\n\t\tdoc, err := html.Parse(strings.NewReader(htmlStr))\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to parse cached HTML: %w\", err)\n\t\t}\n\t\treturn doc, nil\n\t}\n\n\thtmlString, err := fetchHTML(ctx, urlStr, originalHost)\n\tif err != nil {\n\t\tif errors.Is(err, ErrOgHandled) {\n\t\t\tc.cache.Set(cacheKey, emptyMap)\n\t\t\treturn nil, err\n\t\t}\n\t\tslog.ErrorContext(ctx, \"fetchHTML error\", \"error\", err, \"url\", urlStr)\n\t\treturn nil, err\n\t}\n\n\tdoc, err := html.Parse(strings.NewReader(htmlString))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to parse HTML: %w\", err)\n\t}\n\n\tc.cache.Set(cacheKey, htmlString)\n\treturn doc, nil\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 20-52-27"}, "editdistance_info": {"edit_distance": 20.8655, "calculate_time": "2025-08-20 20:52:27", "true_code_clean": "func (c *OGTagCache) fetchHTMLDocumentWithCache(ctx context.Context, urlStr string, originalHost string, cacheKey string) (*html.Node, error) {\n\treq, err := http.NewRequestWithContext(ctx, \"GET\", urlStr, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create http request: %w\", err)\n\t}\n\tif originalHost != \"\" {\n\t\treq.Host = originalHost\n\t}\n\treq.Header.Set(\"X-Forwarded-Proto\", \"https\")\n\treq.Header.Set(\"User-Agent\", \"Anubis-OGTag-Fetcher/1.0\") \n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\tvar netErr net.Error\n\t\tif errors.As(err, &netErr) && netErr.Timeout() {\n\t\t\tslog.Debug(\"og: request timed out\", \"url\", urlStr)\n\t\t\tc.cache.Set(ctx, cacheKey, emptyMap, c.ogTimeToLive/2) \n\t\t}\n\t\treturn nil, fmt.Errorf(\"http get failed: %w\", err)\n\t}\n\tdefer func(Body io.ReadCloser) {\n\t\terr := Body.Close()\n\t\tif err != nil {\n\t\t\tslog.Debug(\"og: error closing response body\", \"url\", urlStr, \"error\", err)\n\t\t}\n\t}(resp.Body)\n\tif resp.StatusCode != http.StatusOK {\n\t\tslog.Debug(\"og: received non-OK status code\", \"url\", urlStr, \"status\", resp.StatusCode)\n\t\tc.cache.Set(ctx, cacheKey, emptyMap, c.ogTimeToLive) \n\t\treturn nil, fmt.Errorf(\"%w: page not found\", ErrOgHandled)\n\t}\n\tct := resp.Header.Get(\"Content-Type\")\n\tif ct == \"\" {\n\t\treturn nil, fmt.Errorf(\"missing Content-Type header\")\n\t} else {\n\t\tmediaType, _, err := mime.ParseMediaType(ct)\n\t\tif err != nil {\n\t\t\tslog.Debug(\"og: malformed Content-Type header\", \"url\", urlStr, \"contentType\", ct)\n\t\t\treturn nil, fmt.Errorf(\"%w malformed Content-Type header: %w\", ErrOgHandled, err)\n\t\t}\n\t\tif mediaType != \"text/html\" && mediaType != \"application/xhtml+xml\" {\n\t\t\tslog.Debug(\"og: unsupported Content-Type\", \"url\", urlStr, \"contentType\", mediaType)\n\t\t\treturn nil, fmt.Errorf(\"%w unsupported Content-Type: %s\", ErrOgHandled, mediaType)\n\t\t}\n\t}\n\tresp.Body = http.MaxBytesReader(nil, resp.Body, maxContentLength)\n\tdoc, err := html.Parse(resp.Body)\n\tif err != nil {\n\t\tvar maxBytesErr *http.MaxBytesError\n\t\tif errors.As(err, &maxBytesErr) {\n\t\t\tslog.Debug(\"og: content exceeded max length\", \"url\", urlStr, \"limit\", maxContentLength)\n\t\t\treturn nil, fmt.Errorf(\"content too large: exceeded %d bytes\", maxContentLength)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"failed to parse HTML: %w\", err)\n\t}\n\treturn doc, nil\n}", "predict_code_clean": "func (c *OGTagCache) fetchHTMLDocumentWithCache(ctx context.Context, urlStr string, originalHost string, cacheKey string) (*html.Node, error) {\n\tif cached, ok := c.cache.Get(cacheKey); ok {\n\t\tif m, ok := cached.(map[string]string); ok && len(m) == 0 {\n\t\t\treturn nil, fmt.Errorf(\"%w: empty cached result\", ErrOgHandled)\n\t\t}\n\t\thtmlStr, ok := cached.(string)\n\t\tif !ok {\n\t\t\treturn nil, errors.New(\"invalid cache entry type\")\n\t\t}\n\t\tdoc, err := html.Parse(strings.NewReader(htmlStr))\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to parse cached HTML: %w\", err)\n\t\t}\n\t\treturn doc, nil\n\t}\n\thtmlString, err := fetchHTML(ctx, urlStr, originalHost)\n\tif err != nil {\n\t\tif errors.Is(err, ErrOgHandled) {\n\t\t\tc.cache.Set(cacheKey, emptyMap)\n\t\t\treturn nil, err\n\t\t}\n\t\tslog.ErrorContext(ctx, \"fetchHTML error\", \"error\", err, \"url\", urlStr)\n\t\treturn nil, err\n\t}\n\tdoc, err := html.Parse(strings.NewReader(htmlString))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to parse HTML: %w\", err)\n\t}\n\tc.cache.Set(cacheKey, htmlString)\n\treturn doc, nil\n}"}}