commit cf961ab94fc293feb8616d2cedc11b1dad5508f0 Author: Patrick MARIE Date: Thu Jun 4 14:19:37 2026 +0200 feat: initial commit diff --git a/.gitea/workflows/build.yaml b/.gitea/workflows/build.yaml new file mode 100644 index 0000000..6e0f4d7 --- /dev/null +++ b/.gitea/workflows/build.yaml @@ -0,0 +1,75 @@ +name: build + +on: + push: + branches: + - main + tags: + - '*' + pull_request: + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - name: Check out repository code + uses: actions/checkout@v4 + + - name: Set up Go + uses: actions/setup-go@v5 + with: + go-version-file: go.mod + + - name: Build + run: go build ./... + + test: + runs-on: ubuntu-latest + + steps: + - name: Check out repository code + uses: actions/checkout@v4 + + - name: Set up Go + uses: actions/setup-go@v5 + with: + go-version-file: go.mod + + - name: Test + run: go test ./... + + build-image: + runs-on: ubuntu-latest + needs: + - build + - test + + steps: + - name: Check out repository code + uses: actions/checkout@v4 + + - name: Docker metadata + id: meta + uses: docker/metadata-action@v5 + with: + images: registry.mkz.me/mycroft/scoreboard-api + tags: | + type=raw,value=latest,enable={{is_default_branch}} + type=ref,event=tag + + - name: Docker login + uses: docker/login-action@v3 + with: + registry: registry.mkz.me + username: ${{ secrets.REGISTRY_USERNAME }} + password: ${{ secrets.REGISTRY_PASSWORD }} + + - name: Build docker image + uses: docker/build-push-action@v6 + with: + context: . + file: ./Containerfile + pull: true + push: true + tags: ${{ steps.meta.outputs.tags }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..156fc76 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +/scoreboard-apid +/anubis-smoke +*.out +/dist/ diff --git a/Containerfile b/Containerfile new file mode 100644 index 0000000..f56148f --- /dev/null +++ b/Containerfile @@ -0,0 +1,33 @@ +# syntax=docker/dockerfile:1 + +# --- build stage --- +FROM golang:1.26 AS build + +WORKDIR /src + +# Cached dependency layer. +COPY go.mod go.sum ./ +RUN --mount=type=cache,target=/go/pkg/mod \ + go mod download + +# Build the static daemon. +COPY . . +RUN --mount=type=cache,target=/go/pkg/mod \ + --mount=type=cache,target=/root/.cache/go-build \ + CGO_ENABLED=0 GOOS=linux go build \ + -trimpath -ldflags="-s -w" \ + -o /out/scoreboard-apid ./cmd/scoreboard-apid + +# --- runtime stage --- +# distroless static includes CA certificates (needed for HTTPS to root-me.org) +# and runs as a non-root user. +FROM gcr.io/distroless/static-debian12:nonroot + +COPY --from=build /out/scoreboard-apid /usr/local/bin/scoreboard-apid + +EXPOSE 8080 9090 + +ENV HTTP_ADDR=:8080 \ + GRPC_ADDR=:9090 + +ENTRYPOINT ["/usr/local/bin/scoreboard-apid"] diff --git a/README.md b/README.md new file mode 100644 index 0000000..f4cb5b0 --- /dev/null +++ b/README.md @@ -0,0 +1,87 @@ +# scoreboard-api + +A small Go daemon that scrapes the first pages of the +[root-me.org](https://www.root-me.org) scoreboard and serves them over **HTTP/JSON** +and **gRPC**. + +root-me.org is fronted by [Anubis](https://github.com/TecharoHQ/anubis), a +proof-of-work anti-scraper proxy. This daemon includes a **native Go Anubis +client** — no headless browser — that transparently solves the challenge and +caches the resulting auth cookie. + +## How it works + +1. **Anubis** (`internal/anubis`) — an `http.RoundTripper` that detects the + interstitial, solves the challenge, calls `pass-challenge`, stores the auth + cookie, and replays the original request. root-me uses Anubis's `preact` + challenge: the answer is `SHA256(randomData)` plus a short server-enforced + wait (it is *not* a nonce proof-of-work). A nonce solver for the `fast`/`slow` + challenges is also included for portability. +2. **Scraper** (`internal/scraper`) — fetches the public, login-free Rankings + fragment + (`?page=structure&inc=modeles/classement&lang=en&ajah=1&debut_classement=N`), + 50 rows per page, and parses each row into an `Entry`. +3. **Store + refresher** (`internal/scoreboard`) — an atomically-swapped + in-memory snapshot with `byRank`/`byUsername` indexes, refreshed on an + interval. The last good snapshot keeps serving if a refresh fails. +4. **Servers** (`internal/server`) — gRPC and a `net/http` JSON mux, both reading + the same store (no scraping in the request path). + +`Rank` is the canonical 1-based position in score-descending order (root-me's +own displayed rank is noisy around ties, so it is not used for ordering). + +## Build & run + +```sh +go build ./cmd/scoreboard-apid +./scoreboard-apid # HTTP :8080, gRPC :9090, refresh every 10m +``` + +### Configuration (flags or env) + +| Flag | Env | Default | +|------|-----|---------| +| `-http-addr` | `HTTP_ADDR` | `:8080` | +| `-grpc-addr` | `GRPC_ADDR` | `:9090` | +| `-refresh-interval` | `REFRESH_INTERVAL` | `10m` | +| `-pages` | `SCOREBOARD_PAGES` | `4` (→ top 200) | +| `-user-agent` | `USER_AGENT` | a Firefox UA | +| `-request-timeout` | `REQUEST_TIMEOUT` | `30s` | +| `-log-level` | `LOG_LEVEL` | `info` | + +## HTTP endpoints + +```sh +curl localhost:8080/readyz +curl 'localhost:8080/v1/scoreboard?limit=10&offset=0' +curl localhost:8080/v1/scoreboard/rank/1 +curl localhost:8080/v1/scoreboard/user/skav +``` + +## gRPC + +Server reflection is enabled: + +```sh +grpcurl -plaintext localhost:9090 list scoreboard.v1.ScoreboardService +grpcurl -plaintext -d '{"limit":2}' localhost:9090 scoreboard.v1.ScoreboardService/ListScoreboard +grpcurl -plaintext -d '{"rank":1}' localhost:9090 scoreboard.v1.ScoreboardService/GetByRank +grpcurl -plaintext -d '{"username":"skav"}' localhost:9090 scoreboard.v1.ScoreboardService/GetByUsername +``` + +## Development + +```sh +go test ./... +go generate ./... # regenerate gen/ from proto/ (needs protoc + plugins) +``` + +`cmd/anubis-smoke` is a small helper that solves Anubis for a URL and dumps the +page — handy for refreshing the parser test fixture. + +## Notes + +- An official JSON API exists at `https://api.www.root-me.org/classement` + (not behind Anubis) but requires an `api_key`. This daemon deliberately uses + the public HTML fragment so no credentials are needed. +- Be a good citizen: the default 10-minute refresh keeps load on root-me low. diff --git a/cmd/anubis-smoke/main.go b/cmd/anubis-smoke/main.go new file mode 100644 index 0000000..82ed93d --- /dev/null +++ b/cmd/anubis-smoke/main.go @@ -0,0 +1,54 @@ +// Command anubis-smoke is a throwaway tool: it solves the Anubis challenge for +// a URL and writes the resulting page to stdout (or a file), so we can inspect +// the real scoreboard HTML and pin scraper selectors. +package main + +import ( + "flag" + "fmt" + "io" + "log/slog" + "os" + + "git.mkz.me/mycroft/root-me-api/internal/anubis" +) + +func main() { + url := flag.String("url", "https://www.root-me.org/?page=classement&lang=en", "URL to fetch") + out := flag.String("out", "", "write body to this file (default stdout)") + flag.Parse() + + slog.SetLogLoggerLevel(slog.LevelDebug) + + tr, err := anubis.New() + if err != nil { + fatal(err) + } + resp, err := tr.Client().Get(*url) + if err != nil { + fatal(err) + } + defer resp.Body.Close() + body, err := io.ReadAll(resp.Body) + if err != nil { + fatal(err) + } + + fmt.Fprintf(os.Stderr, "status=%d bytes=%d\n", resp.StatusCode, len(body)) + + w := os.Stdout + if *out != "" { + f, err := os.Create(*out) + if err != nil { + fatal(err) + } + defer f.Close() + w = f + } + w.Write(body) +} + +func fatal(err error) { + fmt.Fprintln(os.Stderr, "error:", err) + os.Exit(1) +} diff --git a/cmd/scoreboard-apid/main.go b/cmd/scoreboard-apid/main.go new file mode 100644 index 0000000..7212016 --- /dev/null +++ b/cmd/scoreboard-apid/main.go @@ -0,0 +1,130 @@ +// Command scoreboard-apid serves the root-me.org scoreboard over HTTP/JSON and +// gRPC. It scrapes the public Rankings fragment through a native Anubis +// proof-of-work solver, caching the result in memory and refreshing on an +// interval. +package main + +import ( + "context" + "errors" + "fmt" + "log/slog" + "net" + "net/http" + "os" + "os/signal" + "syscall" + "time" + + "google.golang.org/grpc" + "google.golang.org/grpc/reflection" + + pb "git.mkz.me/mycroft/root-me-api/gen/scoreboard/v1" + "git.mkz.me/mycroft/root-me-api/internal/anubis" + "git.mkz.me/mycroft/root-me-api/internal/config" + "git.mkz.me/mycroft/root-me-api/internal/scoreboard" + "git.mkz.me/mycroft/root-me-api/internal/scraper" + "git.mkz.me/mycroft/root-me-api/internal/server" +) + +func main() { + if err := run(os.Args[1:]); err != nil { + slog.Error("fatal", "err", err) + os.Exit(1) + } +} + +func run(args []string) error { + cfg, err := config.Load(args) + if err != nil { + return err + } + logger := setupLogger(cfg.LogLevel) + slog.SetDefault(logger) + + // Anubis-solving HTTP client. + tr, err := anubis.New() + if err != nil { + return err + } + tr.UserAgent = cfg.UserAgent + tr.Logger = logger + client := tr.Client() + client.Timeout = cfg.RequestTimeout + + // Scraper + store + refresher. + sc := scraper.New(client, logger) + store := scoreboard.NewStore() + fetch := func(ctx context.Context) ([]scoreboard.Entry, error) { + return sc.Fetch(ctx, cfg.Pages) + } + refresher := scoreboard.NewRefresher(store, fetch, cfg.RefreshInterval, logger) + + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) + defer stop() + + // Warm start: try once before serving so /readyz flips green quickly. A + // failure here is non-fatal — the refresher will retry on its interval. + warmCtx, cancel := context.WithTimeout(ctx, cfg.RequestTimeout*time.Duration(cfg.Pages+1)) + if err := refresher.RefreshOnce(warmCtx); err != nil { + logger.Warn("initial scoreboard load failed; serving will start unready", "err", err) + } + cancel() + + go refresher.Run(ctx) + + // HTTP server. + httpSrv := &http.Server{ + Addr: cfg.HTTPAddr, + Handler: server.HTTPHandler(store, refresher, logger), + ReadHeaderTimeout: 10 * time.Second, + } + // gRPC server. + grpcSrv := grpc.NewServer() + pb.RegisterScoreboardServiceServer(grpcSrv, server.NewGRPC(store)) + reflection.Register(grpcSrv) + + grpcLis, err := net.Listen("tcp", cfg.GRPCAddr) + if err != nil { + return fmt.Errorf("grpc listen: %w", err) + } + + errCh := make(chan error, 2) + go func() { + logger.Info("HTTP server listening", "addr", cfg.HTTPAddr) + if err := httpSrv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { + errCh <- fmt.Errorf("http: %w", err) + } + }() + go func() { + logger.Info("gRPC server listening", "addr", cfg.GRPCAddr) + if err := grpcSrv.Serve(grpcLis); err != nil { + errCh <- fmt.Errorf("grpc: %w", err) + } + }() + + select { + case <-ctx.Done(): + logger.Info("shutdown signal received") + case err := <-errCh: + logger.Error("server error", "err", err) + } + + // Graceful shutdown. + shutCtx, shutCancel := context.WithTimeout(context.Background(), 10*time.Second) + defer shutCancel() + if err := httpSrv.Shutdown(shutCtx); err != nil { + logger.Warn("http shutdown", "err", err) + } + grpcSrv.GracefulStop() + logger.Info("stopped") + return nil +} + +func setupLogger(level string) *slog.Logger { + var lvl slog.Level + if err := lvl.UnmarshalText([]byte(level)); err != nil { + lvl = slog.LevelInfo + } + return slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: lvl})) +} diff --git a/gen/scoreboard/v1/generate.go b/gen/scoreboard/v1/generate.go new file mode 100644 index 0000000..60165cb --- /dev/null +++ b/gen/scoreboard/v1/generate.go @@ -0,0 +1,11 @@ +// Package scoreboardv1 contains the generated gRPC/protobuf code for the +// scoreboard service. +// +// Regenerate with `go generate ./...` (requires protoc, protoc-gen-go and +// protoc-gen-go-grpc on PATH — install the latter two with: +// +// go install google.golang.org/protobuf/cmd/protoc-gen-go@latest +// go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest +package scoreboardv1 + +//go:generate protoc --proto_path=../../../proto --go_out=../../.. --go_opt=module=git.mkz.me/mycroft/root-me-api --go-grpc_out=../../.. --go-grpc_opt=module=git.mkz.me/mycroft/root-me-api scoreboard/v1/scoreboard.proto diff --git a/gen/scoreboard/v1/scoreboard.pb.go b/gen/scoreboard/v1/scoreboard.pb.go new file mode 100644 index 0000000..a96a6b1 --- /dev/null +++ b/gen/scoreboard/v1/scoreboard.pb.go @@ -0,0 +1,399 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.36.11 +// protoc v7.35.0 +// source: scoreboard/v1/scoreboard.proto + +package scoreboardv1 + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" + unsafe "unsafe" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +// Entry is a single scoreboard row. +type Entry struct { + state protoimpl.MessageState `protogen:"open.v1"` + Rank int32 `protobuf:"varint,1,opt,name=rank,proto3" json:"rank,omitempty"` + Username string `protobuf:"bytes,2,opt,name=username,proto3" json:"username,omitempty"` + ProfilePath string `protobuf:"bytes,3,opt,name=profile_path,json=profilePath,proto3" json:"profile_path,omitempty"` + Country string `protobuf:"bytes,4,opt,name=country,proto3" json:"country,omitempty"` + Grade string `protobuf:"bytes,5,opt,name=grade,proto3" json:"grade,omitempty"` + Score int32 `protobuf:"varint,6,opt,name=score,proto3" json:"score,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *Entry) Reset() { + *x = Entry{} + mi := &file_scoreboard_v1_scoreboard_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *Entry) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Entry) ProtoMessage() {} + +func (x *Entry) ProtoReflect() protoreflect.Message { + mi := &file_scoreboard_v1_scoreboard_proto_msgTypes[0] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Entry.ProtoReflect.Descriptor instead. +func (*Entry) Descriptor() ([]byte, []int) { + return file_scoreboard_v1_scoreboard_proto_rawDescGZIP(), []int{0} +} + +func (x *Entry) GetRank() int32 { + if x != nil { + return x.Rank + } + return 0 +} + +func (x *Entry) GetUsername() string { + if x != nil { + return x.Username + } + return "" +} + +func (x *Entry) GetProfilePath() string { + if x != nil { + return x.ProfilePath + } + return "" +} + +func (x *Entry) GetCountry() string { + if x != nil { + return x.Country + } + return "" +} + +func (x *Entry) GetGrade() string { + if x != nil { + return x.Grade + } + return "" +} + +func (x *Entry) GetScore() int32 { + if x != nil { + return x.Score + } + return 0 +} + +type ListScoreboardRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + // Zero-based offset into the ranked list. + Offset int32 `protobuf:"varint,1,opt,name=offset,proto3" json:"offset,omitempty"` + // Maximum entries to return; 0 means "all from offset". + Limit int32 `protobuf:"varint,2,opt,name=limit,proto3" json:"limit,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ListScoreboardRequest) Reset() { + *x = ListScoreboardRequest{} + mi := &file_scoreboard_v1_scoreboard_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ListScoreboardRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ListScoreboardRequest) ProtoMessage() {} + +func (x *ListScoreboardRequest) ProtoReflect() protoreflect.Message { + mi := &file_scoreboard_v1_scoreboard_proto_msgTypes[1] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ListScoreboardRequest.ProtoReflect.Descriptor instead. +func (*ListScoreboardRequest) Descriptor() ([]byte, []int) { + return file_scoreboard_v1_scoreboard_proto_rawDescGZIP(), []int{1} +} + +func (x *ListScoreboardRequest) GetOffset() int32 { + if x != nil { + return x.Offset + } + return 0 +} + +func (x *ListScoreboardRequest) GetLimit() int32 { + if x != nil { + return x.Limit + } + return 0 +} + +type ListScoreboardResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Entries []*Entry `protobuf:"bytes,1,rep,name=entries,proto3" json:"entries,omitempty"` + // Total entries in the current snapshot. + Total int32 `protobuf:"varint,2,opt,name=total,proto3" json:"total,omitempty"` + // Snapshot time (unix seconds) the data was fetched. + FetchedAt int64 `protobuf:"varint,3,opt,name=fetched_at,json=fetchedAt,proto3" json:"fetched_at,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ListScoreboardResponse) Reset() { + *x = ListScoreboardResponse{} + mi := &file_scoreboard_v1_scoreboard_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ListScoreboardResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ListScoreboardResponse) ProtoMessage() {} + +func (x *ListScoreboardResponse) ProtoReflect() protoreflect.Message { + mi := &file_scoreboard_v1_scoreboard_proto_msgTypes[2] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ListScoreboardResponse.ProtoReflect.Descriptor instead. +func (*ListScoreboardResponse) Descriptor() ([]byte, []int) { + return file_scoreboard_v1_scoreboard_proto_rawDescGZIP(), []int{2} +} + +func (x *ListScoreboardResponse) GetEntries() []*Entry { + if x != nil { + return x.Entries + } + return nil +} + +func (x *ListScoreboardResponse) GetTotal() int32 { + if x != nil { + return x.Total + } + return 0 +} + +func (x *ListScoreboardResponse) GetFetchedAt() int64 { + if x != nil { + return x.FetchedAt + } + return 0 +} + +type GetByRankRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + Rank int32 `protobuf:"varint,1,opt,name=rank,proto3" json:"rank,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetByRankRequest) Reset() { + *x = GetByRankRequest{} + mi := &file_scoreboard_v1_scoreboard_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetByRankRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetByRankRequest) ProtoMessage() {} + +func (x *GetByRankRequest) ProtoReflect() protoreflect.Message { + mi := &file_scoreboard_v1_scoreboard_proto_msgTypes[3] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetByRankRequest.ProtoReflect.Descriptor instead. +func (*GetByRankRequest) Descriptor() ([]byte, []int) { + return file_scoreboard_v1_scoreboard_proto_rawDescGZIP(), []int{3} +} + +func (x *GetByRankRequest) GetRank() int32 { + if x != nil { + return x.Rank + } + return 0 +} + +type GetByUsernameRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + Username string `protobuf:"bytes,1,opt,name=username,proto3" json:"username,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetByUsernameRequest) Reset() { + *x = GetByUsernameRequest{} + mi := &file_scoreboard_v1_scoreboard_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetByUsernameRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetByUsernameRequest) ProtoMessage() {} + +func (x *GetByUsernameRequest) ProtoReflect() protoreflect.Message { + mi := &file_scoreboard_v1_scoreboard_proto_msgTypes[4] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetByUsernameRequest.ProtoReflect.Descriptor instead. +func (*GetByUsernameRequest) Descriptor() ([]byte, []int) { + return file_scoreboard_v1_scoreboard_proto_rawDescGZIP(), []int{4} +} + +func (x *GetByUsernameRequest) GetUsername() string { + if x != nil { + return x.Username + } + return "" +} + +var File_scoreboard_v1_scoreboard_proto protoreflect.FileDescriptor + +const file_scoreboard_v1_scoreboard_proto_rawDesc = "" + + "\n" + + "\x1escoreboard/v1/scoreboard.proto\x12\rscoreboard.v1\"\xa0\x01\n" + + "\x05Entry\x12\x12\n" + + "\x04rank\x18\x01 \x01(\x05R\x04rank\x12\x1a\n" + + "\busername\x18\x02 \x01(\tR\busername\x12!\n" + + "\fprofile_path\x18\x03 \x01(\tR\vprofilePath\x12\x18\n" + + "\acountry\x18\x04 \x01(\tR\acountry\x12\x14\n" + + "\x05grade\x18\x05 \x01(\tR\x05grade\x12\x14\n" + + "\x05score\x18\x06 \x01(\x05R\x05score\"E\n" + + "\x15ListScoreboardRequest\x12\x16\n" + + "\x06offset\x18\x01 \x01(\x05R\x06offset\x12\x14\n" + + "\x05limit\x18\x02 \x01(\x05R\x05limit\"}\n" + + "\x16ListScoreboardResponse\x12.\n" + + "\aentries\x18\x01 \x03(\v2\x14.scoreboard.v1.EntryR\aentries\x12\x14\n" + + "\x05total\x18\x02 \x01(\x05R\x05total\x12\x1d\n" + + "\n" + + "fetched_at\x18\x03 \x01(\x03R\tfetchedAt\"&\n" + + "\x10GetByRankRequest\x12\x12\n" + + "\x04rank\x18\x01 \x01(\x05R\x04rank\"2\n" + + "\x14GetByUsernameRequest\x12\x1a\n" + + "\busername\x18\x01 \x01(\tR\busername2\x82\x02\n" + + "\x11ScoreboardService\x12]\n" + + "\x0eListScoreboard\x12$.scoreboard.v1.ListScoreboardRequest\x1a%.scoreboard.v1.ListScoreboardResponse\x12B\n" + + "\tGetByRank\x12\x1f.scoreboard.v1.GetByRankRequest\x1a\x14.scoreboard.v1.Entry\x12J\n" + + "\rGetByUsername\x12#.scoreboard.v1.GetByUsernameRequest\x1a\x14.scoreboard.v1.EntryBBZ@git.mkz.me/mycroft/scoreboard-api/gen/scoreboard/v1;scoreboardv1b\x06proto3" + +var ( + file_scoreboard_v1_scoreboard_proto_rawDescOnce sync.Once + file_scoreboard_v1_scoreboard_proto_rawDescData []byte +) + +func file_scoreboard_v1_scoreboard_proto_rawDescGZIP() []byte { + file_scoreboard_v1_scoreboard_proto_rawDescOnce.Do(func() { + file_scoreboard_v1_scoreboard_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_scoreboard_v1_scoreboard_proto_rawDesc), len(file_scoreboard_v1_scoreboard_proto_rawDesc))) + }) + return file_scoreboard_v1_scoreboard_proto_rawDescData +} + +var file_scoreboard_v1_scoreboard_proto_msgTypes = make([]protoimpl.MessageInfo, 5) +var file_scoreboard_v1_scoreboard_proto_goTypes = []any{ + (*Entry)(nil), // 0: scoreboard.v1.Entry + (*ListScoreboardRequest)(nil), // 1: scoreboard.v1.ListScoreboardRequest + (*ListScoreboardResponse)(nil), // 2: scoreboard.v1.ListScoreboardResponse + (*GetByRankRequest)(nil), // 3: scoreboard.v1.GetByRankRequest + (*GetByUsernameRequest)(nil), // 4: scoreboard.v1.GetByUsernameRequest +} +var file_scoreboard_v1_scoreboard_proto_depIdxs = []int32{ + 0, // 0: scoreboard.v1.ListScoreboardResponse.entries:type_name -> scoreboard.v1.Entry + 1, // 1: scoreboard.v1.ScoreboardService.ListScoreboard:input_type -> scoreboard.v1.ListScoreboardRequest + 3, // 2: scoreboard.v1.ScoreboardService.GetByRank:input_type -> scoreboard.v1.GetByRankRequest + 4, // 3: scoreboard.v1.ScoreboardService.GetByUsername:input_type -> scoreboard.v1.GetByUsernameRequest + 2, // 4: scoreboard.v1.ScoreboardService.ListScoreboard:output_type -> scoreboard.v1.ListScoreboardResponse + 0, // 5: scoreboard.v1.ScoreboardService.GetByRank:output_type -> scoreboard.v1.Entry + 0, // 6: scoreboard.v1.ScoreboardService.GetByUsername:output_type -> scoreboard.v1.Entry + 4, // [4:7] is the sub-list for method output_type + 1, // [1:4] is the sub-list for method input_type + 1, // [1:1] is the sub-list for extension type_name + 1, // [1:1] is the sub-list for extension extendee + 0, // [0:1] is the sub-list for field type_name +} + +func init() { file_scoreboard_v1_scoreboard_proto_init() } +func file_scoreboard_v1_scoreboard_proto_init() { + if File_scoreboard_v1_scoreboard_proto != nil { + return + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: unsafe.Slice(unsafe.StringData(file_scoreboard_v1_scoreboard_proto_rawDesc), len(file_scoreboard_v1_scoreboard_proto_rawDesc)), + NumEnums: 0, + NumMessages: 5, + NumExtensions: 0, + NumServices: 1, + }, + GoTypes: file_scoreboard_v1_scoreboard_proto_goTypes, + DependencyIndexes: file_scoreboard_v1_scoreboard_proto_depIdxs, + MessageInfos: file_scoreboard_v1_scoreboard_proto_msgTypes, + }.Build() + File_scoreboard_v1_scoreboard_proto = out.File + file_scoreboard_v1_scoreboard_proto_goTypes = nil + file_scoreboard_v1_scoreboard_proto_depIdxs = nil +} diff --git a/gen/scoreboard/v1/scoreboard_grpc.pb.go b/gen/scoreboard/v1/scoreboard_grpc.pb.go new file mode 100644 index 0000000..7e5bb8e --- /dev/null +++ b/gen/scoreboard/v1/scoreboard_grpc.pb.go @@ -0,0 +1,207 @@ +// Code generated by protoc-gen-go-grpc. DO NOT EDIT. +// versions: +// - protoc-gen-go-grpc v1.6.2 +// - protoc v7.35.0 +// source: scoreboard/v1/scoreboard.proto + +package scoreboardv1 + +import ( + context "context" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" +) + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +// Requires gRPC-Go v1.64.0 or later. +const _ = grpc.SupportPackageIsVersion9 + +const ( + ScoreboardService_ListScoreboard_FullMethodName = "/scoreboard.v1.ScoreboardService/ListScoreboard" + ScoreboardService_GetByRank_FullMethodName = "/scoreboard.v1.ScoreboardService/GetByRank" + ScoreboardService_GetByUsername_FullMethodName = "/scoreboard.v1.ScoreboardService/GetByUsername" +) + +// ScoreboardServiceClient is the client API for ScoreboardService service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +// +// ScoreboardService serves the cached root-me.org scoreboard. +type ScoreboardServiceClient interface { + // ListScoreboard returns a page of entries ordered by rank. + ListScoreboard(ctx context.Context, in *ListScoreboardRequest, opts ...grpc.CallOption) (*ListScoreboardResponse, error) + // GetByRank returns the entry at the given canonical rank. + GetByRank(ctx context.Context, in *GetByRankRequest, opts ...grpc.CallOption) (*Entry, error) + // GetByUsername returns the entry for a username (case-insensitive). + GetByUsername(ctx context.Context, in *GetByUsernameRequest, opts ...grpc.CallOption) (*Entry, error) +} + +type scoreboardServiceClient struct { + cc grpc.ClientConnInterface +} + +func NewScoreboardServiceClient(cc grpc.ClientConnInterface) ScoreboardServiceClient { + return &scoreboardServiceClient{cc} +} + +func (c *scoreboardServiceClient) ListScoreboard(ctx context.Context, in *ListScoreboardRequest, opts ...grpc.CallOption) (*ListScoreboardResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(ListScoreboardResponse) + err := c.cc.Invoke(ctx, ScoreboardService_ListScoreboard_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *scoreboardServiceClient) GetByRank(ctx context.Context, in *GetByRankRequest, opts ...grpc.CallOption) (*Entry, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(Entry) + err := c.cc.Invoke(ctx, ScoreboardService_GetByRank_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *scoreboardServiceClient) GetByUsername(ctx context.Context, in *GetByUsernameRequest, opts ...grpc.CallOption) (*Entry, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(Entry) + err := c.cc.Invoke(ctx, ScoreboardService_GetByUsername_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +// ScoreboardServiceServer is the server API for ScoreboardService service. +// All implementations must embed UnimplementedScoreboardServiceServer +// for forward compatibility. +// +// ScoreboardService serves the cached root-me.org scoreboard. +type ScoreboardServiceServer interface { + // ListScoreboard returns a page of entries ordered by rank. + ListScoreboard(context.Context, *ListScoreboardRequest) (*ListScoreboardResponse, error) + // GetByRank returns the entry at the given canonical rank. + GetByRank(context.Context, *GetByRankRequest) (*Entry, error) + // GetByUsername returns the entry for a username (case-insensitive). + GetByUsername(context.Context, *GetByUsernameRequest) (*Entry, error) + mustEmbedUnimplementedScoreboardServiceServer() +} + +// UnimplementedScoreboardServiceServer must be embedded to have +// forward compatible implementations. +// +// NOTE: this should be embedded by value instead of pointer to avoid a nil +// pointer dereference when methods are called. +type UnimplementedScoreboardServiceServer struct{} + +func (UnimplementedScoreboardServiceServer) ListScoreboard(context.Context, *ListScoreboardRequest) (*ListScoreboardResponse, error) { + return nil, status.Error(codes.Unimplemented, "method ListScoreboard not implemented") +} +func (UnimplementedScoreboardServiceServer) GetByRank(context.Context, *GetByRankRequest) (*Entry, error) { + return nil, status.Error(codes.Unimplemented, "method GetByRank not implemented") +} +func (UnimplementedScoreboardServiceServer) GetByUsername(context.Context, *GetByUsernameRequest) (*Entry, error) { + return nil, status.Error(codes.Unimplemented, "method GetByUsername not implemented") +} +func (UnimplementedScoreboardServiceServer) mustEmbedUnimplementedScoreboardServiceServer() {} +func (UnimplementedScoreboardServiceServer) testEmbeddedByValue() {} + +// UnsafeScoreboardServiceServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to ScoreboardServiceServer will +// result in compilation errors. +type UnsafeScoreboardServiceServer interface { + mustEmbedUnimplementedScoreboardServiceServer() +} + +func RegisterScoreboardServiceServer(s grpc.ServiceRegistrar, srv ScoreboardServiceServer) { + // If the following call panics, it indicates UnimplementedScoreboardServiceServer was + // embedded by pointer and is nil. This will cause panics if an + // unimplemented method is ever invoked, so we test this at initialization + // time to prevent it from happening at runtime later due to I/O. + if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { + t.testEmbeddedByValue() + } + s.RegisterService(&ScoreboardService_ServiceDesc, srv) +} + +func _ScoreboardService_ListScoreboard_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(ListScoreboardRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ScoreboardServiceServer).ListScoreboard(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: ScoreboardService_ListScoreboard_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ScoreboardServiceServer).ListScoreboard(ctx, req.(*ListScoreboardRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _ScoreboardService_GetByRank_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetByRankRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ScoreboardServiceServer).GetByRank(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: ScoreboardService_GetByRank_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ScoreboardServiceServer).GetByRank(ctx, req.(*GetByRankRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _ScoreboardService_GetByUsername_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetByUsernameRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ScoreboardServiceServer).GetByUsername(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: ScoreboardService_GetByUsername_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ScoreboardServiceServer).GetByUsername(ctx, req.(*GetByUsernameRequest)) + } + return interceptor(ctx, in, info, handler) +} + +// ScoreboardService_ServiceDesc is the grpc.ServiceDesc for ScoreboardService service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var ScoreboardService_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "scoreboard.v1.ScoreboardService", + HandlerType: (*ScoreboardServiceServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "ListScoreboard", + Handler: _ScoreboardService_ListScoreboard_Handler, + }, + { + MethodName: "GetByRank", + Handler: _ScoreboardService_GetByRank_Handler, + }, + { + MethodName: "GetByUsername", + Handler: _ScoreboardService_GetByUsername_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "scoreboard/v1/scoreboard.proto", +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..3301c70 --- /dev/null +++ b/go.mod @@ -0,0 +1,18 @@ +module git.mkz.me/mycroft/root-me-api + +go 1.26.3 + +require ( + github.com/PuerkitoBio/goquery v1.12.0 + golang.org/x/sync v0.20.0 + google.golang.org/grpc v1.81.1 + google.golang.org/protobuf v1.36.11 +) + +require ( + github.com/andybalholm/cascadia v1.3.3 // indirect + golang.org/x/net v0.52.0 // indirect + golang.org/x/sys v0.42.0 // indirect + golang.org/x/text v0.35.0 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..c4c0309 --- /dev/null +++ b/go.sum @@ -0,0 +1,109 @@ +github.com/PuerkitoBio/goquery v1.12.0 h1:pAcL4g3WRXekcB9AU/y1mbKez2dbY2AajVhtkO8RIBo= +github.com/PuerkitoBio/goquery v1.12.0/go.mod h1:802ej+gV2y7bbIhOIoPY5sT183ZW0YFofScC4q/hIpQ= +github.com/andybalholm/cascadia v1.3.3 h1:AG2YHrzJIm4BZ19iwJ/DAua6Btl3IwJX+VI4kktS1LM= +github.com/andybalholm/cascadia v1.3.3/go.mod h1:xNd9bqTn98Ln4DwST8/nG+H0yuB8Hmgu1YHNnWw0GeA= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= +github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= +github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= +go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= +go.opentelemetry.io/otel v1.43.0 h1:mYIM03dnh5zfN7HautFE4ieIig9amkNANT+xcVxAj9I= +go.opentelemetry.io/otel v1.43.0/go.mod h1:JuG+u74mvjvcm8vj8pI5XiHy1zDeoCS2LB1spIq7Ay0= +go.opentelemetry.io/otel/metric v1.43.0 h1:d7638QeInOnuwOONPp4JAOGfbCEpYb+K6DVWvdxGzgM= +go.opentelemetry.io/otel/metric v1.43.0/go.mod h1:RDnPtIxvqlgO8GRW18W6Z/4P462ldprJtfxHxyKd2PY= +go.opentelemetry.io/otel/sdk v1.43.0 h1:pi5mE86i5rTeLXqoF/hhiBtUNcrAGHLKQdhg4h4V9Dg= +go.opentelemetry.io/otel/sdk v1.43.0/go.mod h1:P+IkVU3iWukmiit/Yf9AWvpyRDlUeBaRg6Y+C58QHzg= +go.opentelemetry.io/otel/sdk/metric v1.43.0 h1:S88dyqXjJkuBNLeMcVPRFXpRw2fuwdvfCGLEo89fDkw= +go.opentelemetry.io/otel/sdk/metric v1.43.0/go.mod h1:C/RJtwSEJ5hzTiUz5pXF1kILHStzb9zFlIEe85bhj6A= +go.opentelemetry.io/otel/trace v1.43.0 h1:BkNrHpup+4k4w+ZZ86CZoHHEkohws8AY+WTX09nk+3A= +go.opentelemetry.io/otel/trace v1.43.0/go.mod h1:/QJhyVBUUswCphDVxq+8mld+AvhXZLhe+8WVFxiFff0= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc= +golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= +golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8= +golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= +golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk= +golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44= +golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM= +golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4= +golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0= +golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y= +golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4= +golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo= +golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= +golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= +golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU= +golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk= +golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY= +golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= +golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ= +golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8= +golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= +golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58= +golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= +gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171 h1:ggcbiqK8WWh6l1dnltU4BgWGIGo+EVYxCaAPih/zQXQ= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= +google.golang.org/grpc v1.81.1 h1:VnnIIZ88UzOOKLukQi+ImGz8O1Wdp8nAGGnvOfEIWQQ= +google.golang.org/grpc v1.81.1/go.mod h1:xGH9GfzOyMTGIOXBJmXt+BX/V0kcdQbdcuwQ/zNw42I= +google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= +google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= diff --git a/internal/anubis/challenge.go b/internal/anubis/challenge.go new file mode 100644 index 0000000..db4d82e --- /dev/null +++ b/internal/anubis/challenge.go @@ -0,0 +1,111 @@ +package anubis + +import ( + "encoding/json" + "fmt" + "regexp" +) + +// Anubis embeds several JSON blobs in its interstitial as +// elements. We read two: +// +// - anubis_challenge: the canonical challenge (id, randomData, rules) +// - preact_info: the preact frontend's view, crucially the `redir` +// (the fully-formed pass-challenge URL) and `challenge` string. +// +// root-me.org uses the "preact" challenge: the answer is simply +// SHA-256(randomData) (no proof-of-work nonce), gated by a minimum wait of +// difficulty*80ms server-side. +type anubisChallenge struct { + Challenge struct { + ID string `json:"id"` + Method string `json:"method"` + RandomData string `json:"randomData"` + IssuedAt string `json:"issuedAt"` + } `json:"challenge"` + Rules struct { + Difficulty int `json:"difficulty"` + Algorithm string `json:"algorithm"` + } `json:"rules"` +} + +type preactInfo struct { + Challenge string `json:"challenge"` + Difficulty int `json:"difficulty"` + Redir string `json:"redir"` // relative pass-challenge URL with id+redir baked in +} + +// challenge is the normalized view the transport acts on. +type challenge struct { + algorithm string + id string + randomData string + difficulty int + redir string // preact: server-provided relative pass-challenge URL +} + +func scriptRe(id string) *regexp.Regexp { + return regexp.MustCompile( + `(?is)]*\bid=["']` + regexp.QuoteMeta(id) + `["'][^>]*>(.*?)`) +} + +var ( + anubisChallengeRe = scriptRe("anubis_challenge") + preactInfoRe = scriptRe("preact_info") +) + +// isInterstitial reports whether an HTML body is an Anubis challenge page. +func isInterstitial(body []byte) bool { + return anubisChallengeRe.Match(body) +} + +func extractJSON(re *regexp.Regexp, body []byte, into any) error { + m := re.FindSubmatch(body) + if m == nil { + return fmt.Errorf("anubis: script element not found") + } + if err := json.Unmarshal(m[1], into); err != nil { + return fmt.Errorf("anubis: decode embedded JSON: %w", err) + } + return nil +} + +// parseChallenge extracts and normalizes the Anubis challenge from +// interstitial HTML. +func parseChallenge(body []byte) (*challenge, error) { + var ac anubisChallenge + if err := extractJSON(anubisChallengeRe, body, &ac); err != nil { + return nil, fmt.Errorf("anubis: parse anubis_challenge: %w", err) + } + if ac.Challenge.RandomData == "" || ac.Rules.Difficulty <= 0 { + return nil, fmt.Errorf("anubis: incomplete challenge (randomData=%q difficulty=%d)", + ac.Challenge.RandomData, ac.Rules.Difficulty) + } + + c := &challenge{ + algorithm: ac.Rules.Algorithm, + id: ac.Challenge.ID, + randomData: ac.Challenge.RandomData, + difficulty: ac.Rules.Difficulty, + } + + // The preact challenge carries the fully-formed pass-challenge URL in + // preact_info.redir; grab it when present. + if c.algorithm == "preact" { + var pi preactInfo + if err := extractJSON(preactInfoRe, body, &pi); err != nil { + return nil, fmt.Errorf("anubis: parse preact_info: %w", err) + } + if pi.Redir == "" { + return nil, fmt.Errorf("anubis: preact_info missing redir") + } + c.redir = pi.Redir + if pi.Challenge != "" { + c.randomData = pi.Challenge + } + if pi.Difficulty > 0 { + c.difficulty = pi.Difficulty + } + } + return c, nil +} diff --git a/internal/anubis/http_helpers.go b/internal/anubis/http_helpers.go new file mode 100644 index 0000000..136ce31 --- /dev/null +++ b/internal/anubis/http_helpers.go @@ -0,0 +1,52 @@ +package anubis + +import ( + "bytes" + "io" + "net/http" + "net/url" + "strings" +) + +// resolveRef resolves a (possibly relative) URL reference against a base URL, +// preserving the base's scheme and host. Anubis's preact redir is host-relative +// (e.g. "/.within.website/..."). +func resolveRef(base *url.URL, ref string) *url.URL { + u, err := url.Parse(ref) + if err != nil { + // Fall back to a copy of base; the caller's cookie check will catch it. + c := *base + return &c + } + return base.ResolveReference(u) +} + +// maybeHTML reports whether a response could be an HTML page (and thus possibly +// an Anubis interstitial). Non-HTML responses are passed through untouched. +func maybeHTML(resp *http.Response) bool { + ct := resp.Header.Get("Content-Type") + if ct == "" { + return true // unknown; be safe and inspect + } + return strings.Contains(strings.ToLower(ct), "text/html") +} + +// withBody returns resp with its body replaced by an in-memory reader over b, +// so the (already consumed) body can be read again by the caller. +func withBody(resp *http.Response, b []byte) *http.Response { + resp.Body = io.NopCloser(bytes.NewReader(b)) + resp.ContentLength = int64(len(b)) + resp.Header.Del("Content-Length") + return resp +} + +// applyCookies replaces the request's Cookie header with the cookies the shared +// jar holds for the request URL. The replayed request goes through the base +// transport directly (bypassing the client jar), so we must attach the freshly +// obtained auth cookie ourselves. +func (t *Transport) applyCookies(req *http.Request) { + req.Header.Del("Cookie") + for _, c := range t.Jar.Cookies(req.URL) { + req.AddCookie(c) + } +} diff --git a/internal/anubis/pow.go b/internal/anubis/pow.go new file mode 100644 index 0000000..b6f5784 --- /dev/null +++ b/internal/anubis/pow.go @@ -0,0 +1,63 @@ +// Package anubis implements a native Go client for getting past the Anubis +// (TecharoHQ) proof-of-work anti-scraper proxy without a headless browser. +// +// The challenge is embedded in the interstitial HTML as a JSON document inside +// a