Files
sol_bot Bot caf4d72880 Update to Anubis v1.28.2 (#1)
This upgrades the Masyunis fork from Anubis v1.25.0 to the latest stable release, **v1.28.2** (“Wuk Lamat Echo 2”), while keeping the fork’s custom styling and removals.

## Approach

The Gitea repo is a tree snapshot of v1.25.0, not a git-level fork of [TecharoHQ/anubis](https://github.com/TecharoHQ/anubis). The histories share no commits, so a merge or rebase onto the upstream tag is not usable.

The first commit on this branch replaces the tree with a snapshot of the **v1.28.2** tag (`git rm -r` plus `git checkout v1.28.2 -- .`; the import tree is identical to the tag). A short patch series on top restores the Masyunis customizations.

## Customizations kept

- Masyunya mascots (`web/static/img/{happy,pensive,reject}.webp`), hashes match current `master`.
- `web/static/img/ATTRIBUTIONS.txt` stays deleted.
- Challenge footer: drop the `made_with` (Canada / maple-leaf) line and the CELPHASE mascot credit; keep “Protected by Anubis from Techaro”. The generated `web/index_templ.go` matches `go generate ./web`.
- Short README (the old `anubisc` typo is fixed).
- Version stamped `v1.28.2/masyunis` via Makefile ldflags. `anubis.go` `init()` does not overwrite a link-time version; `go run` / `go test` still report `devel` on purpose.
- Upstream `.github`, `.devcontainer`, `.husky`, and `.vscode` stay deleted.
- `"uk"` is removed from `lib/localization/locales/manifest.json` **on purpose**, because of Alpine locale problems. `uk.json` and its test entry stay; the served manifest lists 27 languages.
- `package.json` `prepare` no longer runs `husky` (the hooks directory is gone). The rest of the script is unchanged. `husky` remains in devDependencies, as upstream left it.

## Deploy notes

- **Cookie rename (v1.27):** with the default `DYNAMIC_COOKIE_SUFFIX=true`, cookie names become e.g. `techaro.lol-anubis-auth-<hash>`. Existing clients get a **one-time re-challenge**. That is expected, not a loop.
- **Docker / ko / yeet builds** skip the Makefile ldflags, so the displayed version is `<git-version>/masyunis`. It is `v1.28.2/masyunis` only when built from a `v1.28.2` tag (or via `make build` / `make prebaked-build`).
- Go 1.27.3 is required (upstream bump in v1.28.2). Thoth (`THOTH_URL` / `THOTH_TOKEN`) was removed upstream; those settings now warn and do nothing. New WASM challenge methods stay disabled unless opted in.

## Verification

- `make build` succeeds. `./var/anubis --version` prints `Anubis v1.28.2/masyunis`.
- `SKIP_INTEGRATION=1 go test ./...` passes (unit tests; integration package is skipped).
- Local challenge/reject pages (en and ru) show Masyunya, version `v1.28.2/masyunis`, and no Canada / CELPHASE / mascot-credit text. Screenshots:

![Challenge page (en)](https://git.unvr.site/attachments/36112ff0-5155-495c-8bd2-59606ee3bd64)
![Reject page (en)](https://git.unvr.site/attachments/2cad0256-1b0e-4f71-8d06-d1a447fd5263)

- Upstream Playwright tests (`make test` without `SKIP_INTEGRATION`) fail on this box because the browser download fails. A clean v1.28.2 tree fails the same three Playwright tests here, so this is not a fork regression.
- `npm audit` reports **4** findings in upstream’s lockfile (2 moderate, 2 high: `brace-expansion`, `fast-uri`, `lodash.trim`, `source-map-js`). Left alone.

Please review and merge when ready. I will not merge this myself.

Reviewed-on: #1
Co-authored-by: Lead <3+lead_bot@noreply.git.unvr.site>
2026-11-28 12:10:27 +00:00

238 lines
6.4 KiB
Go

package geoip
import (
"context"
"crypto/md5"
"encoding/hex"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"os"
"path/filepath"
"time"
"github.com/TecharoHQ/anubis"
"github.com/TecharoHQ/anubis/lib/config"
"github.com/maxmind/geoipupdate/v8/client"
)
var (
ErrChecksumMismatch = errors.New("geoip: downloaded database checksum does not match")
ErrDatabaseTooLarge = errors.New("geoip: downloaded database is too large")
)
const (
// maxDatabaseSize caps how much of a download is written to disk.
// GeoIP2-City, the largest common edition, is well under this.
maxDatabaseSize = 512 << 20
// fileCheckInterval is how often database files are checked for changes
// when automatic updates are off.
fileCheckInterval = 5 * time.Minute
)
type updater struct {
cli client.Client
interval time.Duration
}
func newUpdater(cfg *config.GeoIPAutoUpdate) (*updater, error) {
opts := []client.Option{
client.WithHTTPClient(&http.Client{
Timeout: 5 * time.Minute,
Transport: userAgentTransport{next: http.DefaultTransport},
}),
}
if cfg.Endpoint != nil {
opts = append(opts, client.WithEndpoint(*cfg.Endpoint))
}
cli, err := client.New(cfg.AccountID, cfg.LicenseKey(), opts...)
if err != nil {
return nil, fmt.Errorf("geoip: can't create MaxMind update client: %w", err)
}
return &updater{
cli: cli,
interval: cfg.GetInterval(),
}, nil
}
// update checks MaxMind for a newer copy of src. When there is one, it saves
// the download as a new file named after the Unix timestamp of the update,
// verifies it, and swaps it in. It never renames over or rewrites a file that
// is mapped. It reports whether a new database was installed.
func (u *updater) update(ctx context.Context, src *source) (bool, error) {
resp, err := u.cli.Download(ctx, src.edition, src.md5)
if err != nil {
return false, fmt.Errorf("geoip: can't download %s: %w", src.edition, err)
}
defer resp.Reader.Close() //nolint:errcheck
if !resp.UpdateAvailable {
return false, nil
}
fname := src.nextVersionPath(time.Now().Unix())
gotMD5, err := writeVersion(fname, resp.Reader)
if err != nil {
return false, fmt.Errorf("geoip: can't save %s download: %w", src.edition, err)
}
if gotMD5 != resp.MD5 {
os.Remove(fname) //nolint:errcheck
return false, fmt.Errorf("%w: %s: want %s, got %s", ErrChecksumMismatch, src.edition, resp.MD5, gotMD5)
}
rdr, err := src.open(fname)
if err != nil {
os.Remove(fname) //nolint:errcheck
return false, fmt.Errorf("geoip: downloaded %s is not valid: %w", src.edition, err)
}
src.install(rdr, fname, gotMD5)
return true, nil
}
// nextVersionPath returns the file name for a download made at ts. If that
// name is taken, such as after the clock steps backwards, it moves forward to
// the next free second so the new file still sorts as the newest.
func (src *source) nextVersionPath(ts int64) string {
if latest, ok := src.latest(); ok {
if lts, ok := parseVersion(filepath.Base(latest), filepath.Base(src.path)+"."); ok && lts >= ts {
ts = lts + 1
}
}
return src.versionPath(ts)
}
// writeVersion streams r into a staging file, syncs it, and renames it to
// fname. Nothing maps fname yet, so the rename is safe on every platform. It
// returns the MD5 checksum of what was written.
func writeVersion(fname string, r io.Reader) (string, error) {
if err := os.MkdirAll(filepath.Dir(fname), 0o755); err != nil {
return "", err
}
tmpName := fname + tmpSuffix
tmp, err := os.OpenFile(tmpName, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644)
if err != nil {
return "", err
}
h := md5.New()
n, err := io.Copy(io.MultiWriter(tmp, h), io.LimitReader(r, maxDatabaseSize+1))
if err == nil && n > maxDatabaseSize {
err = fmt.Errorf("%w: larger than %d bytes", ErrDatabaseTooLarge, maxDatabaseSize)
}
if err == nil {
err = tmp.Sync()
}
if cerr := tmp.Close(); err == nil {
err = cerr
}
if err == nil {
err = os.Rename(tmpName, fname)
}
if err != nil {
os.Remove(tmpName) //nolint:errcheck
return "", err
}
return hex.EncodeToString(h.Sum(nil)), nil
}
// run keeps the databases fresh until ctx is canceled. With an updater it
// polls MaxMind. Without one it reloads files that change on disk, such as
// when an external geoipupdate job replaces them.
func (db *DB) run(ctx context.Context, lg *slog.Logger, up *updater) {
interval := fileCheckInterval
if up != nil {
interval = up.interval
}
t := time.NewTicker(interval)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
}
for _, src := range db.sources() {
if up != nil {
db.checkUpdate(ctx, lg, up, src)
} else {
db.checkFile(ctx, lg, src)
}
}
}
}
func (db *DB) checkUpdate(ctx context.Context, lg *slog.Logger, up *updater, src *source) {
lg = lg.With("edition", src.edition, "path", src.path)
updated, err := up.update(ctx, src)
if err != nil {
updateErrors.WithLabelValues(string(src.kind)).Inc()
var httpErr client.HTTPError
if errors.As(err, &httpErr) && (httpErr.StatusCode == http.StatusUnauthorized || httpErr.StatusCode == http.StatusForbidden) {
lg.ErrorContext(ctx, "MaxMind rejected the account ID or license key, please check the geoip auto_update settings", "err", err, "actionable", true)
return
}
lg.WarnContext(ctx, "can't update geoip database, keeping the current one", "err", err)
return
}
if updated {
lg.InfoContext(ctx, "updated geoip database", "file", src.current)
}
if err := src.cleanup(); err != nil {
lg.DebugContext(ctx, "can't clean up old geoip databases yet", "err", err)
}
}
func (db *DB) checkFile(ctx context.Context, lg *slog.Logger, src *source) {
lg = lg.With("path", src.path)
fi, err := os.Stat(src.path)
if err != nil {
updateErrors.WithLabelValues(string(src.kind)).Inc()
lg.WarnContext(ctx, "can't stat geoip database, keeping the current one", "err", err)
return
}
if fi.ModTime().Equal(src.modTime) {
return
}
if err := src.load(); err != nil {
updateErrors.WithLabelValues(string(src.kind)).Inc()
lg.WarnContext(ctx, "can't reload geoip database, keeping the current one", "err", err)
return
}
lg.InfoContext(ctx, "reloaded geoip database from disk")
}
type userAgentTransport struct {
next http.RoundTripper
}
func (u userAgentTransport) RoundTrip(r *http.Request) (*http.Response, error) {
r = r.Clone(r.Context())
r.Header.Set("User-Agent", fmt.Sprint("Techaro/anubis:", anubis.Version, " ", r.Header.Get("User-Agent")))
return u.next.RoundTrip(r)
}