From 52a965a8e896e161330d9747f24910f94e3b6b63 Mon Sep 17 00:00:00 2001 From: Caleb Kinney Date: Thu, 3 Dec 2026 08:28:17 -0500 Subject: [PATCH 01/17] Add read-only leaderboard support with URL handling and view key validation - Introduced support for fetching private leaderboards using a URL or year/board ID. - Enhanced error handling for invalid URLs and credentials. - Updated CLI commands to accept leaderboard URLs. - Added tests for new functionality and credential handling. --- elf/__init__.py | 1 + elf/aoc_client.py | 93 +++++++---- elf/cli.py | 34 +++- elf/client.py | 21 ++- elf/leaderboard.py | 101 +++++++++--- elf/utils.py | 6 + tests/test_aoc_client.py | 48 ++++++ tests/test_cli_commands.py | 2 +- tests/test_client_api.py | 3 +- tests/test_leaderboard_auth.py | 286 +++++++++++++++++++++++++++++++++ 10 files changed, 520 insertions(+), 75 deletions(-) create mode 100644 tests/test_leaderboard_auth.py diff --git a/elf/__init__.py b/elf/__init__.py index ed787a1..da9be78 100644 --- a/elf/__init__.py +++ b/elf/__init__.py @@ -6,6 +6,7 @@ - get_puzzle_input(year, day, session=None) -> str - submit_puzzle_answer(year, day, part, answer, session=None) -> SubmissionResult - get_private_leaderboard(year, board_id, session=None, view_key=None, fmt=OutputFormat.MODEL) +- get_private_leaderboard(url=leaderboard_url, fmt=OutputFormat.MODEL) - get_user_status(year, session=None, fmt=OutputFormat.MODEL) The session token can be passed explicitly or via the AOC_SESSION environment variable. diff --git a/elf/aoc_client.py b/elf/aoc_client.py index 43c078b..d1c6804 100644 --- a/elf/aoc_client.py +++ b/elf/aoc_client.py @@ -1,18 +1,38 @@ from __future__ import annotations +import logging import os import re import time import warnings +from collections.abc import Callable +from contextvars import ContextVar from types import TracebackType from typing import Self import httpx from .constants import VERSION +from .utils import resolve_session, validate_view_key _user_agent_prefix = f"elf/{VERSION}" _default_user_agent = "+https://github.com/typeerror/elf" +_leaderboard_in_flight = ContextVar("elf_leaderboard_in_flight", default=False) + + +def _allow_wire_log(record: logging.LogRecord) -> bool: + # HTTPX logs the query string, and protocol traces can include response headers. + return not _leaderboard_in_flight.get() + + +def _get_with_retries(send: Callable[[], httpx.Response]) -> httpx.Response: + """Retry transport failures with backoff, leaving HTTP responses to the endpoint.""" + for delay in (0.5, 1.0): + try: + return send() + except httpx.TransportError: + time.sleep(delay) + return send() def _build_http_client() -> httpx.Client: @@ -75,11 +95,9 @@ def __init__( self._client = http_client if http_client is not None else _build_http_client() self._owns_client = http_client is None - def _get(self, path: str, params: dict[str, str] | None = None) -> httpx.Response: + def _get(self, path: str) -> httpx.Response: cookies = {"session": self.session_token} if self.session_token else None - request = self._client.build_request( - "GET", f"{self.base_url}{path}", params=params, cookies=cookies - ) + request = self._client.build_request("GET", f"{self.base_url}{path}", cookies=cookies) return self._client.send(request) def _post(self, path: str, data: dict[str, str]) -> httpx.Response: @@ -89,28 +107,6 @@ def _post(self, path: str, data: dict[str, str]) -> httpx.Response: ) return self._client.send(request, follow_redirects=False) - def _get_with_retries( - self, - path: str, - *, - retries: int = 2, - backoff: float = 0.5, - params: dict[str, str] | None = None, - ) -> httpx.Response: - """Retry transport failures on GET with exponential backoff. - - HTTP responses are returned for the endpoint to interpret. - """ - attempt = 0 - while True: - try: - return self._get(path, params=params) - except (httpx.TimeoutException, httpx.TransportError): - if attempt >= retries: - raise - time.sleep(backoff * (2**attempt)) - attempt += 1 - def __enter__(self) -> Self: return self @@ -131,7 +127,7 @@ def fetch_input(self, year: int, day: int) -> httpx.Response: """ Fetch the puzzle input for a specific year and day. """ - return self._get_with_retries(f"/{year}/day/{day}/input") + return _get_with_retries(lambda: self._get(f"/{year}/day/{day}/input")) def submit_answer(self, year: int, day: int, answer: str, part: int) -> httpx.Response: """ @@ -149,15 +145,44 @@ def fetch_leaderboard( Fetch a private leaderboard for a specific year. If a view_key is provided, it will be included in the request. """ - params = {"view_key": view_key} if view_key else None - response = self._get_with_retries( - f"/{year}/leaderboard/private/view/{board_id}.json", - params=params, - ) - return response + if not isinstance(year, int) or not isinstance(board_id, int): + raise TypeError("Year and board ID must be integers.") + endpoint = f"https://adventofcode.com/{year}/leaderboard/private/view/{board_id}.json" + request = self._client.build_request("GET", endpoint) + # Keep configured headers and timeouts, but select the origin, query and + # authentication here. build_request also merges client-wide cookies and params. + request.headers["Host"] = "adventofcode.com" + request.headers.pop("Authorization", None) + if view_key is not None: + validate_view_key(view_key) + request.url = httpx.URL(endpoint, params={"view_key": view_key}) + request.headers.pop("Cookie", None) + else: + request.url = httpx.URL(endpoint) + # An injected HTTP client's cookie jar can already authorize this URL. + if self.session_token is not None or "Cookie" not in request.headers: + request.headers["Cookie"] = f"session={resolve_session(self.session_token)}" + # Logger filters apply at the emitting logger. The context variable keeps + # unrelated requests in other threads and tasks visible to the caller. + for name in ("httpx", "httpcore.http11", "httpcore.http2", "hpack.hpack", "hpack.table"): + logging.getLogger(name).addFilter(_allow_wire_log) + token = _leaderboard_in_flight.set(True) + try: + return _get_with_retries( + lambda: self._client.send(request, auth=None, follow_redirects=False) + ) + except httpx.RequestError as exc: + # Keep the transport exception type, but strip the credential-bearing + # request and any server-supplied diagnostic from the exception. + safe_request = httpx.Request("GET", request.url.copy_with(query=None)) + raise type(exc)("Leaderboard request failed.", request=safe_request) from None + except httpx.InvalidURL: + raise httpx.InvalidURL("Invalid URL in leaderboard response.") from None + finally: + _leaderboard_in_flight.reset(token) def fetch_event(self, year: int) -> httpx.Response: """ Fetch general event information for a specific year (html). """ - return self._get_with_retries(f"/{year}") + return _get_with_retries(lambda: self._get(f"/{year}")) diff --git a/elf/cli.py b/elf/cli.py index 678436b..301fba3 100644 --- a/elf/cli.py +++ b/elf/cli.py @@ -25,6 +25,7 @@ help="Advent of Code CLI", no_args_is_help=True, rich_markup_mode="rich", + pretty_exceptions_show_locals=False, ) console = Console() @@ -139,7 +140,7 @@ def handle_cli_errors(func): def wrapper(*args, **kwargs): try: return func(*args, **kwargs) - except typer.Exit: + except (typer.Exit, typer.BadParameter): raise except KeyboardInterrupt as exc: raise typer.Exit(code=130) from exc @@ -242,24 +243,43 @@ def answer_cmd( @app.command("leaderboard") @handle_cli_errors def leaderboard_cmd( - year: RequiredYearArg, - board_id: Annotated[int, typer.Argument(help="Private leaderboard ID")], + year: Annotated[ + str | None, typer.Argument(metavar="YEAR|URL", help="Event year or leaderboard URL") + ] = None, + board_id: Annotated[str | None, typer.Argument(help="Private leaderboard ID")] = None, view_key: Annotated[ str | None, - typer.Option(help="View key for the private leaderboard, if required"), + typer.Option(help="Read-only key for this board. Takes precedence over the session."), ] = None, session: SessionOpt = None, output_format: LeaderboardFormatOpt = OutputFormat.TABLE, + url: Annotated[ + str | None, + typer.Option(help="Official HTML or JSON leaderboard URL, including a view key if shared."), + ] = None, ) -> None: """ - Show or export a private leaderboard using a session cookie or view key. + Show or export a private leaderboard. Supply YEAR BOARD_ID, a URL, or --url URL. """ + target: int | str | None = year + try: + board = int(board_id) if board_id is not None else None + if year is not None and "://" not in year: + target = int(year) + except ValueError: + # Typer's default integer error echoes the argument, which could be a share link. + raise typer.BadParameter("Expected numeric YEAR BOARD_ID or a leaderboard URL.") from None + if isinstance(target, int) and target < 2015: + raise typer.BadParameter("The event year must be at least 2015.") + if url is None and not isinstance(target, str) and (target is None or board is None): + raise typer.BadParameter("Supply YEAR BOARD_ID or a leaderboard URL.") leaderboard_data = get_leaderboard( - year=year, + year=target, session=session, - board_id=board_id, + board_id=board, view_key=view_key, fmt=output_format, + url=url, ) _print_formatted_output(leaderboard_data, output_format) diff --git a/elf/client.py b/elf/client.py index 5e1f49f..5505d2e 100644 --- a/elf/client.py +++ b/elf/client.py @@ -109,11 +109,13 @@ def submit_puzzle_answer( def get_private_leaderboard( - year: int, - board_id: int, + year: int | str | None = None, + board_id: int | None = None, session: str | None = None, view_key: str | None = None, fmt: OutputFormat = OutputFormat.MODEL, + *, + url: str | None = None, ) -> Leaderboard | str | Table: """ Retrieve a private leaderboard for a given year. @@ -124,7 +126,7 @@ def get_private_leaderboard( Parameters ---------- year - The event year. + The event year, or a full leaderboard URL as the sole positional argument. board_id The numeric ID of the private leaderboard. session @@ -135,8 +137,11 @@ def get_private_leaderboard( token is unused. fmt ``MODEL`` returns a Leaderboard, ``TABLE`` returns a Rich table, - ``JSON`` preserves the Advent of Code payload, and ``CSV`` produces + ``JSON`` preserves upstream fields with credentials redacted, and ``CSV`` produces one summary row per member. + url + An official HTML or JSON private leaderboard URL. Pass it in place of + ``year`` and ``board_id``. A ``view_key`` in the URL authorizes this board. Returns ------- @@ -159,13 +164,7 @@ def get_private_leaderboard( Responses are cached for 15 minutes per event, board, and credential. A view key authorizes the request on its own and determines the cache scope. """ - if year < 2015: - raise ValueError(f"Invalid year {year!r}. Advent of Code started in 2015.") - - if board_id <= 0: - raise ValueError("Board ID must be a positive integer.") - - return get_leaderboard(year, session, board_id, view_key, fmt) + return get_leaderboard(year, session, board_id, view_key, fmt, url=url) def get_user_status( diff --git a/elf/leaderboard.py b/elf/leaderboard.py index 8f261d0..3160a68 100644 --- a/elf/leaderboard.py +++ b/elf/leaderboard.py @@ -1,11 +1,13 @@ import csv import json +import re import time import warnings from datetime import UTC, datetime, timedelta from io import StringIO from pathlib import Path from typing import Any +from urllib.parse import unquote_plus import httpx from pydantic import ValidationError @@ -21,17 +23,40 @@ ) from .exceptions import LeaderboardFetchError from .models import Leaderboard, Member, OutputFormat -from .utils import handle_http_errors, resolve_session +from .utils import handle_http_errors, resolve_session, validate_view_key LEADERBOARD_CACHE_TTL = timedelta(minutes=15) +_CREDENTIAL_IN_TEXT = re.compile(r"(?<=[?&]view_key=)[^&#\s]+|(?<=\bsession=)[^;\s]+") + + +def _parse_leaderboard_url(url: str) -> tuple[int, int, str | None]: + """Extract only the components of an official HTML or JSON share link.""" + match = re.fullmatch( + r"(?ai:https://adventofcode\.com)(?::443)?/([0-9]{4})/leaderboard/private/view/" + r"([0-9]+)(?:\.json)?(?:\?view_key=([^&#\s]+))?", + url, + ) + if not match: + raise ValueError("Expected an HTTPS Advent of Code private leaderboard URL.") + year, board_id, key = match.groups() + if key is not None: + if re.search(r"%(?![0-9a-fA-F]{2})", key): + raise ValueError("Invalid encoding in leaderboard URL.") + try: + key = unquote_plus(key, errors="strict") + except UnicodeDecodeError: + raise ValueError("Invalid encoding in leaderboard URL.") from None + return int(year), int(board_id), key def get_leaderboard( - year: int, - session: str | None, - board_id: int, - view_key: str | None, + year: int | str | None = None, + session: str | None = None, + board_id: int | None = None, + view_key: str | None = None, fmt: OutputFormat = OutputFormat.MODEL, + *, + url: str | None = None, ) -> Leaderboard | str | Table: """ Fetch a private leaderboard for a specific year. @@ -41,8 +66,23 @@ def get_leaderboard( session: Your Advent of Code session token (optional if view_key is supplied). board_id: The ID of the private leaderboard. view_key: The view key for the private leaderboard, if required. + url: An HTML or JSON leaderboard URL supplied in place of year and board_id. """ + if isinstance(year, str): + if url is not None: + raise ValueError("Supply a single leaderboard URL.") + url, year = year, None + if url is not None: + if year is not None or board_id is not None: + raise ValueError("Supply either a leaderboard URL or a year and board ID.") + year, board_id, url_key = _parse_leaderboard_url(url) + if url_key is not None: + if view_key is not None and view_key != url_key: + raise ValueError("The URL and explicit view keys disagree.") + view_key = url_key + if year is None or board_id is None: + raise TypeError("Supply a year and board ID or a leaderboard URL.") if year < 2015: raise ValueError(f"Invalid year {year!r}. Advent of Code started in 2015.") @@ -50,7 +90,9 @@ def get_leaderboard( raise ValueError("Board ID must be a positive integer.") # Authorize the request with the same credential used to scope its cache. - session_token = None if view_key else resolve_session(session) + if view_key is not None: + validate_view_key(view_key) + session_token = None if view_key is not None else resolve_session(session) cache_file = get_cache_leaderboard_file( year, @@ -116,15 +158,20 @@ def _fetch_leaderboard_payload( try: with AOCClient(session_token=session_token) as client: response = client.fetch_leaderboard(year, board_id, view_key) - except httpx.TimeoutException as exc: + except httpx.TimeoutException: raise LeaderboardFetchError( "Timed out while fetching leaderboard. Try again or check your network." - ) from exc - except httpx.RequestError: + ) from None + except (httpx.RequestError, httpx.InvalidURL): raise LeaderboardFetchError( "Network error while fetching the private leaderboard." ) from None + if response.status_code in (401, 403): + credential = "view key" if view_key is not None else "session cookie" + raise LeaderboardFetchError( + f"Leaderboard access denied (HTTP {response.status_code}). Check the {credential}." + ) handle_http_errors( response, exc_cls=LeaderboardFetchError, @@ -132,23 +179,20 @@ def _fetch_leaderboard_payload( bad_request_message=( "Bad request (HTTP 400). Your session token or view key may be invalid." ), - server_error_message=( - "Server error from Advent of Code (HTTP {status_code}). " - "Your session token may be invalid." - ), + server_error_message="Server error from Advent of Code (HTTP {status_code}).", unexpected_status_message="Unexpected HTTP error: {status_code}.", ) try: payload = response.json() - except ValueError as exc: + except ValueError: raise LeaderboardFetchError( "Failed to decode leaderboard JSON. Your session/view key may be invalid." - ) from exc + ) from None if not isinstance(payload, dict): raise LeaderboardFetchError("Unexpected leaderboard schema from Advent of Code.") - return payload, _validate_leaderboard(payload) + return _prepare_leaderboard(payload) def _read_fresh_cache(cache_file: Path) -> tuple[dict[str, Any], Leaderboard] | None: @@ -168,7 +212,7 @@ def _read_fresh_cache(cache_file: Path) -> tuple[dict[str, Any], Leaderboard] | payload = json.loads(cache_file.read_text(encoding="utf-8")) if not isinstance(payload, dict): raise ValueError("Leaderboard cache must contain a JSON object.") - return payload, _validate_leaderboard(payload) + return _prepare_leaderboard(payload) except (OSError, ValueError, ValidationError, LeaderboardFetchError) as exc: raise LeaderboardFetchError( "The fresh leaderboard cache is unreadable or malformed. " @@ -177,11 +221,26 @@ def _read_fresh_cache(cache_file: Path) -> tuple[dict[str, Any], Leaderboard] | ) from exc -def _validate_leaderboard(payload: dict[str, Any]) -> Leaderboard: +def _redact_share_data(value: Any) -> Any: + """Mask credential fields and links, including those in extra JSON metadata.""" + if isinstance(value, dict): + for key, item in value.items(): + value[key] = ( + "[redacted]" if key in ("session", "view_key") else _redact_share_data(item) + ) + elif isinstance(value, list): + return [_redact_share_data(item) for item in value] + elif isinstance(value, str): + return _CREDENTIAL_IN_TEXT.sub("[redacted]", value) + return value + + +def _prepare_leaderboard(payload: dict[str, Any]) -> tuple[dict[str, Any], Leaderboard]: + _redact_share_data(payload) try: - return Leaderboard.model_validate(payload) - except ValidationError as exc: - raise LeaderboardFetchError("Unexpected leaderboard schema from Advent of Code.") from exc + return payload, Leaderboard.model_validate(payload) + except ValidationError: + raise LeaderboardFetchError("Unexpected leaderboard schema from Advent of Code.") from None def _first_star_timestamp(member: Member) -> int | None: diff --git a/elf/utils.py b/elf/utils.py index 1c75862..8bb8f7f 100644 --- a/elf/utils.py +++ b/elf/utils.py @@ -127,6 +127,12 @@ def get_unlock_status(year: int, day: int) -> UnlockStatus: ) +def validate_view_key(key: str) -> None: + """Reject blank keys and whitespace without echoing the credential.""" + if not key or not key.isprintable() or any(char.isspace() for char in key): + raise ValueError("Invalid leaderboard view key.") + + def resolve_session(session: str | None, env_var: str = "AOC_SESSION") -> str: """Resolve a session token from an explicit arg or environment variable.""" token = (session or os.getenv(env_var) or "").strip() diff --git a/tests/test_aoc_client.py b/tests/test_aoc_client.py index 57c4bc8..71cb386 100644 --- a/tests/test_aoc_client.py +++ b/tests/test_aoc_client.py @@ -1,3 +1,4 @@ +import logging import os import httpx @@ -98,3 +99,50 @@ def respond(request): assert response.status_code == 307 assert len(requests) == 1 assert requests[0].method == "POST" + + +@pytest.mark.parametrize("view_key", [None, "chosen-key"]) +def test_leaderboard_auth_is_scoped_to_request_with_injected_client(view_key, caplog): + requests = [] + + def respond(request): + requests.append(request) + return httpx.Response(200) + + with httpx.Client( + transport=httpx.MockTransport(respond), + cookies={"session": "jar-cookie"}, + params={"view_key": "client-key"}, + auth=("client-user", "client-password"), + headers={"User-Agent": "test-user-agent", "Accept": "application/json"}, + follow_redirects=True, + ) as transport: + client = AOCClient("chosen-session", http_client=transport) + with caplog.at_level(logging.DEBUG): + client.fetch_leaderboard(2025, 42, view_key) + transport.get("https://example.org/ordinary-request") + assert len(requests) == 2 + request = requests[0] + assert request.url.host == "adventofcode.com" + assert request.headers["user-agent"] == "test-user-agent" + assert request.headers["accept"] == "application/json" + assert "authorization" not in request.headers + assert request.headers.get("cookie") == (None if view_key else "session=chosen-session") + assert dict(request.url.params) == ({"view_key": view_key} if view_key else {}) + assert "chosen-key" not in caplog.text and "chosen-session" not in caplog.text + assert "ordinary-request" in caplog.text + + +def test_session_in_injected_cookie_jar_still_authorizes_leaderboard(): + requests = [] + + def respond(request): + requests.append(request) + return httpx.Response(200) + + with httpx.Client(transport=httpx.MockTransport(respond)) as transport: + transport.cookies.set("session", "jar-cookie", domain="adventofcode.com") + client = AOCClient(None, http_client=transport) + client.fetch_leaderboard(2025, 42) + assert requests[0].headers["cookie"] == "session=jar-cookie" + assert not requests[0].url.query diff --git a/tests/test_cli_commands.py b/tests/test_cli_commands.py index 2e797f3..d28135d 100644 --- a/tests/test_cli_commands.py +++ b/tests/test_cli_commands.py @@ -62,7 +62,7 @@ def make_result(status): def test_leaderboard_cmd_forwards_options(monkeypatch): captured = {} - def fake_get_leaderboard(year, session, board_id, view_key, fmt): + def fake_get_leaderboard(year, session, board_id, view_key, fmt, *, url): captured.update( { "year": year, diff --git a/tests/test_client_api.py b/tests/test_client_api.py index 96de6b2..badb063 100644 --- a/tests/test_client_api.py +++ b/tests/test_client_api.py @@ -63,7 +63,8 @@ def test_puzzle_apis_use_environment_session(monkeypatch, tmp_path): def test_get_private_leaderboard_forwards_credentials(monkeypatch): calls = [] - def fake_get_leaderboard(year, session, board_id, view_key, fmt): + def fake_get_leaderboard(year, session, board_id, view_key, fmt, *, url): + assert url is None calls.append((year, session, board_id, view_key, fmt)) return "leaderboard-data" diff --git a/tests/test_leaderboard_auth.py b/tests/test_leaderboard_auth.py new file mode 100644 index 0000000..a4db31d --- /dev/null +++ b/tests/test_leaderboard_auth.py @@ -0,0 +1,286 @@ +import json +import logging +import traceback + +import httpx +import pytest +from typer.testing import CliRunner + +from elf import ( + OutputFormat, + get_private_leaderboard, + get_puzzle_input, + get_user_status, + submit_puzzle_answer, +) +from elf.cli import app +from elf.exceptions import LeaderboardFetchError, MissingSessionTokenError + + +@pytest.fixture +def leaderboard_http(monkeypatch, tmp_path): + """Exercise the public entry points and cache against a recording transport.""" + monkeypatch.setenv("ELF_CACHE_DIR", str(tmp_path)) + monkeypatch.delenv("AOC_SESSION", raising=False) + requests = [] + + def install(handler=None): + def respond(request): + requests.append(request) + if handler: + return handler(request) + return httpx.Response( + 200, + json={ + "event": "2025", + "num_days": 12, + "day1_ts": 1, + "owner_id": 1, + "members": {}, + }, + ) + + def build_client(): + return httpx.Client( + transport=httpx.MockTransport(respond), + headers={"User-Agent": "elf/test (test@example.org)"}, + follow_redirects=True, + ) + + monkeypatch.setattr("elf.aoc_client._build_http_client", build_client) + return requests + + return install + + +_BOARD = "https://adventofcode.com/2025/leaderboard/private/view/42" + + +def test_share_urls_and_numeric_calls_share_only_the_matching_cache(leaderboard_http, tmp_path): + requests = leaderboard_http() + key = "fake+key/one" + query = "?view_key=fake%2Bkey%2Fone" + assert get_private_leaderboard(_BOARD + query).event == "2025" + assert json.loads(get_private_leaderboard(url=_BOARD + ".json" + query, fmt=OutputFormat.JSON)) + get_private_leaderboard(2025, 42, "ignored-cookie", key) + get_private_leaderboard(2025, 42, view_key="second-fake-key") + get_private_leaderboard(2025, 43, view_key="second-fake-key") + get_private_leaderboard(2025, 42, session="session-only") + assert len(requests) == 4 + assert [r.url.params.get("view_key") for r in requests] == [ + key, + "second-fake-key", + "second-fake-key", + None, + ] + for request in requests: + assert request.url.host == "adventofcode.com" + assert request.url.scheme == "https" + assert request.headers["User-Agent"] == "elf/test (test@example.org)" + assert requests[0].url.path == "/2025/leaderboard/private/view/42.json" + assert requests[2].url.path == "/2025/leaderboard/private/view/43.json" + assert all("cookie" not in r.headers for r in requests[:3]) + assert requests[3].headers["cookie"] == "session=session-only" + for path in tmp_path.rglob("*"): + data = str(path) + (path.read_text() if path.is_file() else "") + assert all(secret not in data for secret in (key, "second-fake-key", "session-only")) + + +def test_keyless_url_uses_environment_or_explicit_session(leaderboard_http, monkeypatch): + requests = leaderboard_http() + monkeypatch.setenv("AOC_SESSION", "ambient-cookie") + get_private_leaderboard(url=_BOARD + ".json") + get_private_leaderboard(url=_BOARD, session="chosen-cookie") + get_private_leaderboard(2025, 42, "chosen-cookie") + assert [r.headers["cookie"] for r in requests] == [ + "session=ambient-cookie", + "session=chosen-cookie", + ] + assert not any(r.url.query for r in requests) + + +@pytest.mark.parametrize( + "url", + [ + "http://adventofcode.com/2025/leaderboard/private/view/42", + "httpſ://adventofcode.com/2025/leaderboard/private/view/42", + _BOARD.replace(".com", ".com.example.org"), + _BOARD.replace(".com", ".com@elsewhere.example"), + _BOARD.replace(".com", ".com:444"), + _BOARD.replace("https://", "https://user@"), + _BOARD.replace("https:", ""), + _BOARD.replace("/2025/", "/2014/"), + _BOARD.replace("/2025/", "/2025/../"), + _BOARD.replace("/42", "/0"), + _BOARD + ".html", + _BOARD + "/", + _BOARD + "#fragment", + _BOARD + "?view_key=", + _BOARD + "?view_kee=private-example", + _BOARD + "?view_key=private-example&view_key=two", + _BOARD + "?view_key=%0Aprivate-example", + _BOARD + "?view_key=%zzprivate-example", + _BOARD + "?view_key=%FFprivate-example", + ], +) +def test_invalid_url_never_uses_cookie_or_cache(url, leaderboard_http, tmp_path, monkeypatch): + requests = leaderboard_http() + monkeypatch.setenv("AOC_SESSION", "session-only") + with pytest.raises(ValueError) as error: + get_private_leaderboard(url=url) + assert "private-example" not in "".join(traceback.format_exception(error.value)) + assert requests == [] + assert list(tmp_path.iterdir()) == [] + + +@pytest.mark.parametrize( + "arguments", + [ + {"year": 2025, "url": _BOARD}, + {"board_id": 42, "url": _BOARD}, + {"url": _BOARD + "?view_key=test-one", "view_key": "test-two"}, + {"url": _BOARD, "view_key": ""}, + {"year": 2025, "board_id": 42, "view_key": " "}, + ], +) +def test_ambiguous_or_empty_credentials_fail_locally(arguments, leaderboard_http): + requests = leaderboard_http() + with pytest.raises(ValueError) as error: + get_private_leaderboard(session="always-valid", **arguments) + assert "test-one" not in str(error.value) and "test-two" not in str(error.value) + assert not requests + + +@pytest.mark.parametrize("mode", ["key", "session"]) +@pytest.mark.parametrize("status", [200, 302, 401, 403, 429]) +def test_failed_auth_never_redirects_falls_back_or_caches( + leaderboard_http, + monkeypatch, + caplog, + tmp_path, + mode, + status, +): + caplog.set_level(logging.DEBUG) + monkeypatch.setenv("AOC_SESSION", "private-cookie") + key = "private-test-key" + + def failure(request): + return httpx.Response( + status, + text=f"Login required: {key}", + headers={"Location": f"https://example.org/?view_key={key}"}, + ) + + requests = leaderboard_http(failure) + url = _BOARD + ("?view_key=" + key if mode == "key" else "") + with pytest.raises(LeaderboardFetchError) as error: + get_private_leaderboard(url=url) + assert len(requests) == 1 + assert ("cookie" in requests[0].headers) == (mode == "session") + assert ("view_key" in requests[0].url.params) == (mode == "key") + assert not list(tmp_path.rglob("*.json")) + diagnostic = caplog.text + "".join(traceback.format_exception(error.value)) + assert key not in diagnostic and "private-cookie" not in diagnostic + + +@pytest.mark.parametrize("error_type", [httpx.ReadTimeout, httpx.ConnectError]) +def test_transport_retry_keeps_key_and_redacts_traceback( + leaderboard_http, + monkeypatch, + caplog, + error_type, +): + monkeypatch.setattr("elf.aoc_client.time.sleep", lambda _: None) + caplog.set_level(logging.DEBUG) + + def timeout(request): + raise error_type(f"Failed fetching {request.url}", request=request) + + requests = leaderboard_http(timeout) + url = _BOARD + "?view_key=private-test-key" + session = "private-cookie" + with pytest.raises(LeaderboardFetchError) as error: + get_private_leaderboard(url=url, session=session) + assert len(requests) == 3 + assert all(r.url.params["view_key"] == "private-test-key" for r in requests) + assert all("cookie" not in r.headers for r in requests) + diagnostic = caplog.text + "".join(traceback.format_exception(error.value)) + assert "private-test-key" not in diagnostic and "private-cookie" not in diagnostic + + +def test_cli_share_link_export_and_validation(leaderboard_http): + requests = leaderboard_http() + runner = CliRunner() + url = _BOARD + "?view_key=private-example" + for arguments in [[url], ["--url", url.replace("/42", "/42.json")]]: + result = runner.invoke( + app, + ["leaderboard", *arguments, "-f", "csv"], + ) + assert result.exit_code == 0 + assert result.stdout.startswith("year,board_id,rank") + assert "private-example" not in result.output + error = runner.invoke(app, ["leaderboard", "--url", url.replace(".com", ".invalid")]) + assert error.exit_code != 0 + assert error.stdout == "" + assert "private-example" not in error.stderr + assert len(requests) == 1 + + +def test_cli_misplaced_share_url_is_not_echoed(): + result = CliRunner().invoke(app, ["leaderboard", "2025", _BOARD + "?view_key=private-example"]) + assert result.exit_code == 2 + assert "private-example" not in result.output + + +def test_read_only_access_does_not_authorize_account_operations(leaderboard_http): + requests = leaderboard_http() + get_private_leaderboard(url=_BOARD + "?view_key=example") + for operation, args in [ + (get_private_leaderboard, (2025, 42)), + (get_puzzle_input, (2025, 1)), + (get_user_status, (2025,)), + (submit_puzzle_answer, (2025, 1, 1, 42)), + ]: + with pytest.raises(MissingSessionTokenError): + operation(*args) + assert len(requests) == 1 + + +def test_credential_fields_and_links_are_redacted_before_export_and_cache( + leaderboard_http, tmp_path +): + key = "test-share-key" + session = "cookie&secret" + url = _BOARD + "?view_key=" + key + payload = { + "event": "2025", + "num_days": 12, + "day1_ts": 1, + "owner_id": 1, + "members": { + "1": { + "id": 1, + "stars": 0, + "local_score": 0, + "last_star_ts": 0, + "name": url, + }, + }, + "extra": {"links": [url], "view_key": key, "session": session, "note": "keep me"}, + "cookie": f"session={session}; Secure", + } + requests = leaderboard_http(lambda _: httpx.Response(200, json=payload)) + exported = get_private_leaderboard(url=url, fmt=OutputFormat.JSON) + assert json.loads(exported)["extra"]["note"] == "keep me" + assert key not in exported and session not in exported + (cache_file,) = tmp_path.rglob("*.json") + cached = cache_file.read_text() + assert key not in cached and session not in cached + + # A cache produced by an older Elf must also be safe to export during its TTL. + cache_file.write_text(json.dumps(payload)) + csv = get_private_leaderboard(url=url, fmt=OutputFormat.CSV) + assert key not in csv and "[redacted]" in csv + assert len(requests) == 1 From def8e2e9edd698ed2b511a7af0db8f81e1bae469 Mon Sep 17 00:00:00 2001 From: Caleb Kinney Date: Thu, 3 Dec 2026 08:28:57 -0500 Subject: [PATCH 02/17] Enhance leaderboard functionality: support fetching via URL and improve documentation on read-only access and usage examples --- README.md | 39 +++++++++++++++++++++++++++++----- user_guide/command-line.qmd | 36 ++++++++++++++++++++++++++++++- user_guide/getting-started.qmd | 2 ++ 3 files changed, 71 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index ae3a803..5cdf855 100644 --- a/README.md +++ b/README.md @@ -258,10 +258,17 @@ Time (UTC) Guess Status ### `elf leaderboard` -Fetch private leaderboards. Provide a view key for read-only access or a session cookie for authenticated access. A view key is the read-only share token you can generate on your AoC leaderboard page. +Fetch a private leaderboard by year and board ID, or pass the read-only link from the board owner. Elf extracts the event year, board ID, and view key from either official URL form. + +```text +https://adventofcode.com/YEAR/leaderboard/private/view/BOARD_ID?view_key=KEY +https://adventofcode.com/YEAR/leaderboard/private/view/BOARD_ID.json?view_key=KEY +``` ```sh Usage: elf leaderboard YEAR BOARD_ID + elf leaderboard URL + elf leaderboard --url URL Options: --view-key TEXT @@ -273,10 +280,17 @@ Supports: - **table:** pretty Rich table - **csv:** one summary row per member -- **json:** raw JSON +- **json:** upstream JSON with credential fields and share keys redacted - **model:** structured Pydantic model -With a view key, elf sends the key alone, even when a session cookie is configured. The upstream API takes the key in the query string, so keep HTTP client request logs private. +Each board can have its own link or key. These commands use shell variables populated by your secret manager. + +```sh +elf leaderboard --url "$TEAM_BOARD_URL" --format csv > team.csv +elf leaderboard 2025 654321 --view-key "$CLUB_VIEW_KEY" --format json > club.json +``` + +A URL key or explicit `--view-key` takes precedence over `--session` and `AOC_SESSION`. Elf sends only the selected credential. An authentication failure ends the request. A URL without a key uses the usual session configuration. Puzzle inputs, submissions, and personal status require a session cookie. Leaderboard JSON is cached for 15 minutes, matching Advent of Code's minimum request interval. Cache entries are isolated by event, leaderboard ID, and a one-way fingerprint of the session cookie or view key. @@ -454,7 +468,7 @@ print(members[0].name, members[0].stars) ### Exporting Leaderboard Data -CSV provides one summary row per member for tabular analysis. JSON preserves the complete Advent of Code response, including individual star completions. The Python model remains available for more advanced processing, and all formats work with any tool that understands standard CSV or JSON. +CSV provides one summary row per member for tabular analysis. JSON preserves upstream fields, including individual star completions. Elf masks session and view-key fields and credential-bearing links before caching or formatting the data. ```sh elf leaderboard 2025 123456 --format csv > leaderboard.csv @@ -469,6 +483,19 @@ csv_data = get_private_leaderboard(2025, board_id=123456, fmt=OutputFormat.CSV) json_data = get_private_leaderboard(2025, board_id=123456, fmt=OutputFormat.JSON) ``` +Python can read each board’s link or key from the environment. + +```python +import os + +from elf import get_private_leaderboard + +team = get_private_leaderboard(url=os.environ["TEAM_BOARD_URL"]) +club = get_private_leaderboard(2025, 654321, view_key=os.environ["CLUB_VIEW_KEY"]) +``` + +The [command-line guide](user_guide/command-line.qmd#github-actions) includes a GitHub Actions example for multiple private boards. + ### Status Example ```sh @@ -551,7 +578,9 @@ Edit the guides in `user_guide/` and the API reference in the public Python docs ### Hosting and releases -The docs workflow deploys to GitHub Pages from `typeerror/elf`. To serve it at `https://typeerror.com/elf/`, configure `typeerror.com` on the account’s Pages site. In the `elf` repository’s Pages settings, select **GitHub Actions** as the source and leave the project-level custom domain blank so the project inherits the account domain. [GitHub Pages custom domains](https://docs.github.com/en/pages/configuring-a-custom-domain-for-your-github-pages-site/about-custom-domains-and-github-pages) +Publishing a stable GitHub release runs the quality checks and publishes the package to PyPI. After PyPI succeeds, the docs workflow builds that same commit and checks the rendered version badge against the release tag. Only the latest stable release deploys to GitHub Pages. Use the local preview above for unreleased changes. + +In the repository’s Pages settings, select **GitHub Actions** as the source. The docs workflow runs from the default branch and checks out the publish run’s commit, so the `github-pages` environment can keep its `main` branch restriction. The project inherits `typeerror.com` from the account’s Pages site. [GitHub Pages custom domains](https://docs.github.com/en/pages/configuring-a-custom-domain-for-your-github-pages-site/about-custom-domains-and-github-pages) The release workflow uses PyPI Trusted Publishing. Configure the `elf` project on PyPI with owner `typeerror`, repository `elf`, workflow `publish.yml`, and environment `pypi`. [PyPI Trusted Publishing setup](https://docs.pypi.org/trusted-publishers/adding-a-publisher/) diff --git a/user_guide/command-line.qmd b/user_guide/command-line.qmd index f6eda2c..b645f6c 100644 --- a/user_guide/command-line.qmd +++ b/user_guide/command-line.qmd @@ -28,7 +28,41 @@ elf status 2025 --format json > status.json elf leaderboard 2025 123456 --format csv > leaderboard.csv ``` -Replace `123456` with the board ID from the private leaderboard page. Authenticate with your session cookie or supply the board’s read-only share token through `--view-key`. +Replace `123456` with the board ID from the private leaderboard page. This form uses your session cookie. With a read-only link or key supplied by the owner, you can export the board without configuring a session. + +```sh +elf leaderboard --url "$TEAM_BOARD_URL" --format json > team.json +elf leaderboard 2025 654321 --view-key "$CLUB_VIEW_KEY" --format csv > club.csv +``` + +Pass the full HTML or JSON URL with `--url`. Elf extracts the year, board ID, and optional `view_key` and requests the JSON endpoint on `https://adventofcode.com`. A view key applies only to that invocation. A failed key ends the request, even if a session is available. + +### GitHub Actions + +In a job with Elf installed, store each board’s full link or standalone key in its own Actions secret. Set the `AOC_USER_AGENT` repository variable to your contact email. The following step writes one export per board to the runner’s temporary directory. + +```yaml +- name: Export team and club leaderboards + env: + AOC_USER_AGENT: ${{ vars.AOC_USER_AGENT }} + TEAM_BOARD_URL: ${{ secrets.TEAM_BOARD_URL }} + CLUB_VIEW_KEY: ${{ secrets.CLUB_VIEW_KEY }} + run: | + elf leaderboard --url "$TEAM_BOARD_URL" --format json > "$RUNNER_TEMP/team.json" + elf leaderboard 2025 654321 --view-key "$CLUB_VIEW_KEY" --format csv > "$RUNNER_TEMP/club.csv" +``` + +For a session-authenticated job, set `AOC_SESSION` from an Actions secret on the step that needs it. + +```yaml +- name: Export my private leaderboard + env: + AOC_USER_AGENT: ${{ vars.AOC_USER_AGENT }} + AOC_SESSION: ${{ secrets.AOC_SESSION }} + run: elf leaderboard 2025 123456 --format json > "$RUNNER_TEMP/board.json" +``` + +Allow at least 15 minutes between exports of the same board across fresh runners. Each fresh runner starts with an empty local cache. ## Diagnose setup and find cached data diff --git a/user_guide/getting-started.qmd b/user_guide/getting-started.qmd index de64efa..6ec95ec 100644 --- a/user_guide/getting-started.qmd +++ b/user_guide/getting-started.qmd @@ -25,6 +25,8 @@ uv run elf doctor In PowerShell, use `$env:AOC_SESSION = "your-session-cookie"` and `$env:AOC_USER_AGENT = "you@example.com"`. Launch Positron from a configured environment or set the variables in the environment used by its Python session. Keep the cookie out of scripts and version control. `elf doctor` checks local configuration without contacting Advent of Code. +For leaderboard-only use, ask the board owner for its read-only share link and set `AOC_USER_AGENT`. With the link stored in a private shell variable, run `uv run elf leaderboard --url "$TEAM_BOARD_URL"`. The same link works in Python with `get_private_leaderboard(url=...)`. Treat the full link as a credential. + ## Solve a puzzle in Positron ```bash From 40c672f828b16d8f8d48ebf89cf4dbed2ad5e266 Mon Sep 17 00:00:00 2001 From: Caleb Kinney Date: Thu, 3 Dec 2026 08:29:19 -0500 Subject: [PATCH 03/17] Refactor CI workflow for documentation release and add versioning script --- .github/workflows/docs.yml | 101 +++++++++++++------------------------ great-docs.yml | 2 + scripts/docs_version.py | 13 +++++ 3 files changed, 51 insertions(+), 65 deletions(-) create mode 100644 scripts/docs_version.py diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index b73782d..3a90bc5 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -1,104 +1,75 @@ -name: CI Docs +name: Release docs on: - push: - branches: - - main - pull_request: - workflow_dispatch: + workflow_run: + workflows: [Publish] + types: [completed] permissions: contents: read jobs: build-docs: - name: "Build Docs" + if: >- + github.event.workflow_run.event == 'release' && + github.event.workflow_run.conclusion == 'success' && + github.event.workflow_run.head_repository.full_name == github.repository runs-on: ubuntu-latest steps: - - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - fetch-depth: 0 # Full history for accurate page timestamps + ref: ${{ github.event.workflow_run.head_sha }} + fetch-depth: 0 persist-credentials: false - - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 + - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 with: python-version: "3.11" - - name: Install package and dependencies - run: | - python -m pip install uv - uv sync --locked --no-default-groups --group docs - - name: Set up Quarto uses: quarto-dev/quarto-actions/setup@8a96df13519ee81fd526f2dfca5962811136661b # v2 with: version: "1.11.9" - - name: Lint docs - run: uv run --locked --no-default-groups --group docs great-docs lint - - - name: Build docs - run: uv run --locked --no-default-groups --group docs great-docs build + - name: Lint and build release docs + env: + RELEASE_TAG: ${{ github.event.workflow_run.head_branch }} + run: | + uv sync --locked --no-default-groups --group docs + source .venv/bin/activate + great-docs lint + great-docs build + grep -F 'class="version-badge"' great-docs/_site/index.html | grep -Fq ">$RELEASE_TAG" - - name: Save docs artifact - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + - name: Upload Pages artifact + uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5 with: - name: docs-html path: great-docs/_site include-hidden-files: true - - name: How to preview this build locally - if: github.event_name == 'pull_request' - run: uv run --locked --no-default-groups --group docs great-docs ci notice --run ${{ github.run_id }} --pr ${{ github.event.number }} - - - name: Upload build timings - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 - with: - name: build-timings - path: great-docs/_site/build-timings.json - publish-docs: - name: "Publish Docs" + needs: build-docs runs-on: ubuntu-latest - needs: "build-docs" - if: github.ref == 'refs/heads/main' + concurrency: + group: release-docs-pages + cancel-in-progress: false permissions: + contents: read pages: write id-token: write environment: name: github-pages url: ${{ steps.deployment.outputs.page_url }} steps: - - uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7 - with: - name: docs-html - path: great-docs/_site - - - name: Upload Pages artifact - uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5 - with: - path: great-docs/_site - include-hidden-files: true + - name: Identify latest stable release before deployment + id: latest + env: + GH_TOKEN: ${{ github.token }} + run: | + tag=$(gh api "repos/$GITHUB_REPOSITORY/releases/latest" --jq .tag_name) + echo "tag=$tag" >> "$GITHUB_OUTPUT" - name: Deploy to GitHub Pages + if: steps.latest.outputs.tag == github.event.workflow_run.head_branch id: deployment uses: actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346 # v5 - - preview-docs: - name: "Preview Docs" - runs-on: ubuntu-latest - needs: "build-docs" - if: github.event_name == 'pull_request' - permissions: - pull-requests: write - steps: - # Post (and keep updated) a sticky PR comment with the local-preview - # command, pinned to this run so it reproduces the build under review. - # Runs the released great-docs via pipx (no install step needed); kept as - # its own minimal job so the docs build never holds a pull-requests:write - # token. continue-on-error so fork PRs (read-only token) don't fail the run. - - name: Post preview instructions to the PR - continue-on-error: true - run: pipx run --spec great-docs==0.17.0 great-docs ci pr-comment --run ${{ github.run_id }} --pr ${{ github.event.number }} - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/great-docs.yml b/great-docs.yml index f1ceec3..328e187 100644 --- a/great-docs.yml +++ b/great-docs.yml @@ -2,6 +2,8 @@ parser: numpy dynamic: false site_url: "https://typeerror.com/elf/" +pre_render: + - scripts/docs_version.py authors: - name: cak diff --git a/scripts/docs_version.py b/scripts/docs_version.py new file mode 100644 index 0000000..ec1e2ed --- /dev/null +++ b/scripts/docs_version.py @@ -0,0 +1,13 @@ +"""Set the Great Docs navbar badge from the package being documented.""" + +import json +import tomllib +from pathlib import Path + +# Quarto runs pre-render scripts in the generated great-docs project directory. +with Path("../pyproject.toml").open("rb") as source: + version = tomllib.load(source)["project"]["version"] +badge = Path("_package_meta.json") +# Keep the release date only when Great Docs found the matching GitHub release. +if not badge.exists() or json.loads(badge.read_text(encoding="utf-8")).get("version") != version: + badge.write_text(json.dumps({"version": version}), encoding="utf-8") From 63e1f27fabc807c35d28a261ee7654ef6ec62473 Mon Sep 17 00:00:00 2001 From: Caleb Kinney Date: Thu, 3 Dec 2026 08:29:27 -0500 Subject: [PATCH 04/17] Update CHANGELOG for version 1.2.3: add new features, fixes, and security improvements --- CHANGELOG.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index cc656a0..9924a6b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,22 @@ Notable user-facing changes to elf are documented here. +## 1.2.3 (unreleased) + +### Added + +- `elf leaderboard --url URL` and `get_private_leaderboard(url=...)` accept official HTML and JSON private leaderboard links. Elf extracts the year, board ID, and optional read-only view key. +- GitHub Actions examples show how to export multiple boards with independent secrets and how to use an existing session cookie. + +### Fixed + +- The documentation version badge now uses the package version in the checkout. Production documentation builds from the release commit after a successful stable PyPI publication. + +### Security + +- Leaderboard requests send one credential to the official JSON endpoint. Redirects, malformed share links, and conflicting keys fail without retrying with another credential. +- HTTP diagnostics omit keyed leaderboard URLs. Cached payloads and exports redact credential fields and keys embedded in links. Equivalent URL and numeric requests reuse the existing 15-minute cache for the same event, board, and credential. + ## 1.2.2 ### Added From b5865b5bf953a9cb71c884db96e21c093a6b4a9a Mon Sep 17 00:00:00 2001 From: Caleb Kinney Date: Thu, 3 Dec 2026 12:50:02 -0500 Subject: [PATCH 05/17] Add DoctorReport, DoctorCheck, and CheckStatus to leaderboard reference section --- great-docs.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/great-docs.yml b/great-docs.yml index 328e187..9f366f3 100644 --- a/great-docs.yml +++ b/great-docs.yml @@ -33,6 +33,9 @@ reference: - YearStatus - Leaderboard - OutputFormat + - DoctorReport + - DoctorCheck + - CheckStatus - title: Puzzle helpers contents: From 0fb3989b83470b5992a6c5b009a941c264573ad2 Mon Sep 17 00:00:00 2001 From: Caleb Kinney Date: Thu, 3 Dec 2026 12:50:10 -0500 Subject: [PATCH 06/17] Bump version to 1.2.3 in pyproject.toml --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 3f4b7d5..ce739c9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "elf" -version = "1.2.2" +version = "1.2.3" description = "Advent of Code helper for Python: fetch and cache inputs, submit answers, and pull private leaderboards." readme = "README.md" license = "MIT" From c431c2310c64ab89796c99169e8fc2bfd82b522e Mon Sep 17 00:00:00 2001 From: Caleb Kinney Date: Thu, 3 Dec 2026 12:50:27 -0500 Subject: [PATCH 07/17] Add Member, StarCompletion, and SubmissionStatus to public API --- elf/__init__.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/elf/__init__.py b/elf/__init__.py index da9be78..68be322 100644 --- a/elf/__init__.py +++ b/elf/__init__.py @@ -25,16 +25,22 @@ from .models import ( DayStatus, Leaderboard, + Member, OutputFormat, + StarCompletion, SubmissionResult, + SubmissionStatus, YearStatus, ) __all__ = [ "DayStatus", "Leaderboard", + "Member", "OutputFormat", + "StarCompletion", "SubmissionResult", + "SubmissionStatus", "YearStatus", "get_private_leaderboard", "get_puzzle_input", From 2eb7894c90a24d9dda4b6c068de66472cb1c4134 Mon Sep 17 00:00:00 2001 From: Caleb Kinney Date: Thu, 3 Dec 2026 12:50:32 -0500 Subject: [PATCH 08/17] Enhance documentation for CheckStatus, DoctorCheck, and DoctorReport classes --- elf/doctor.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/elf/doctor.py b/elf/doctor.py index 52cd38e..2194cd4 100644 --- a/elf/doctor.py +++ b/elf/doctor.py @@ -18,6 +18,8 @@ class CheckStatus(StrEnum): + """Outcome of one local configuration check.""" + OK = "ok" WARNING = "warning" ERROR = "error" @@ -25,6 +27,8 @@ class CheckStatus(StrEnum): @dataclass(frozen=True, slots=True) class DoctorCheck: + """Named diagnostic result with a safe, human-readable detail.""" + name: str status: CheckStatus detail: str @@ -32,10 +36,13 @@ class DoctorCheck: @dataclass(frozen=True, slots=True) class DoctorReport: + """Collection of configuration checks from a doctor run.""" + checks: tuple[DoctorCheck, ...] @property def has_errors(self) -> bool: + """Whether any check failed.""" return any(check.status is CheckStatus.ERROR for check in self.checks) From 25066fcc72ce3afad8c2153b0da5cb89d9f25886 Mon Sep 17 00:00:00 2001 From: Caleb Kinney Date: Thu, 3 Dec 2026 12:50:38 -0500 Subject: [PATCH 09/17] Add docstrings for Guess, CachedGuessCheck, UnlockStatus, and OpenKind classes --- elf/models.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/elf/models.py b/elf/models.py index e557f0e..6dc14dd 100644 --- a/elf/models.py +++ b/elf/models.py @@ -144,6 +144,8 @@ def __repr__(self) -> str: @dataclass(slots=True) class Guess: + """One recorded answer attempt, including an optional retry deadline.""" + timestamp: datetime part: int guess: int | str @@ -153,6 +155,8 @@ class Guess: @dataclass(frozen=True, slots=True) class CachedGuessCheck: + """Result of checking an answer against local guess history.""" + guess: int | str previous_guess: int | str | None previous_timestamp: datetime | None @@ -163,6 +167,8 @@ class CachedGuessCheck: @dataclass(slots=True) class UnlockStatus: + """Puzzle unlock state and the timestamps used to determine it.""" + unlocked: bool now: datetime unlock_time: datetime @@ -183,6 +189,8 @@ class OutputFormat(str, Enum): class OpenKind(str, Enum): + """Type of Advent of Code page to open.""" + WEBSITE = "website" PUZZLE = "puzzle" INPUT = "input" From 07e8b4f21d638058584c9c7bb789b38556fd6caf Mon Sep 17 00:00:00 2001 From: Caleb Kinney Date: Thu, 3 Dec 2026 12:50:44 -0500 Subject: [PATCH 10/17] Bump version of elf package to 1.2.3 in uv.lock --- uv.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/uv.lock b/uv.lock index a607287..efb321a 100644 --- a/uv.lock +++ b/uv.lock @@ -572,7 +572,7 @@ wheels = [ [[package]] name = "elf" -version = "1.2.2" +version = "1.2.3" source = { editable = "." } dependencies = [ { name = "beautifulsoup4" }, From 357a930903ed19930aebb942485fc90a6fb2cdf0 Mon Sep 17 00:00:00 2001 From: Caleb Kinney Date: Thu, 3 Dec 2026 12:52:27 -0500 Subject: [PATCH 11/17] Add docstrings to AocResponseParser methods and AocMessageType class --- elf/answer.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/elf/answer.py b/elf/answer.py index 584ac05..98f75ed 100644 --- a/elf/answer.py +++ b/elf/answer.py @@ -56,22 +56,28 @@ def __init__(self) -> None: self.content: list[str] = [] def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: + """Start collecting text when an article element begins.""" if tag == "article": self.in_article = True def handle_endtag(self, tag: str) -> None: + """Stop collecting text when the article element closes.""" if tag == "article": self.in_article = False def handle_data(self, data: str) -> None: + """Append text from inside the article element.""" if self.in_article: self.content.append(data) def text(self) -> str: + """Return the collected article text.""" return "".join(self.content).strip() class AocMessageType(Enum): + """Categories recognized in an Advent of Code answer response.""" + EMPTY = auto() CORRECT = auto() TOO_HIGH = auto() @@ -83,6 +89,7 @@ class AocMessageType(Enum): def classify_message(content: str) -> AocMessageType: + """Classify an Advent of Code response message by its meaning.""" if not content: return AocMessageType.EMPTY From 9f96787f6be3486b1a357e5074e4183e639cc40a Mon Sep 17 00:00:00 2001 From: Caleb Kinney Date: Thu, 3 Dec 2026 12:52:33 -0500 Subject: [PATCH 12/17] Add docstrings for version_callback and main functions in CLI --- elf/cli.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/elf/cli.py b/elf/cli.py index 301fba3..633623b 100644 --- a/elf/cli.py +++ b/elf/cli.py @@ -158,6 +158,7 @@ def wrapper(*args, **kwargs): def version_callback(value: bool) -> None: + """Print the installed Elf version and stop CLI processing when requested.""" if not value: return @@ -382,6 +383,7 @@ def doctor_cmd() -> None: def main() -> None: + """Run the Elf command-line application.""" app() From 82c3a3cb672ebfdb92b9c0ec993b08314dbb6cdd Mon Sep 17 00:00:00 2001 From: Caleb Kinney Date: Thu, 3 Dec 2026 12:52:38 -0500 Subject: [PATCH 13/17] Add SubmissionStatus and OpenKind to reference section in great-docs.yml --- great-docs.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/great-docs.yml b/great-docs.yml index 9f366f3..ae5bfbe 100644 --- a/great-docs.yml +++ b/great-docs.yml @@ -36,6 +36,8 @@ reference: - DoctorReport - DoctorCheck - CheckStatus + - SubmissionStatus + - OpenKind - title: Puzzle helpers contents: @@ -63,6 +65,7 @@ reference: - exceptions.SubmissionError - exceptions.LeaderboardFetchError - exceptions.StatusFetchError + - exceptions.TemplateCreationError seo: canonical: From ca814b3232f0e9e0f08628a962622bcc71de3665 Mon Sep 17 00:00:00 2001 From: Caleb Kinney Date: Thu, 3 Dec 2026 13:01:55 -0500 Subject: [PATCH 14/17] Add support for passing leaderboard URL as a positional argument --- user_guide/command-line.qmd | 2 ++ 1 file changed, 2 insertions(+) diff --git a/user_guide/command-line.qmd b/user_guide/command-line.qmd index b645f6c..bc60f8b 100644 --- a/user_guide/command-line.qmd +++ b/user_guide/command-line.qmd @@ -37,6 +37,8 @@ elf leaderboard 2025 654321 --view-key "$CLUB_VIEW_KEY" --format csv > club.csv Pass the full HTML or JSON URL with `--url`. Elf extracts the year, board ID, and optional `view_key` and requests the JSON endpoint on `https://adventofcode.com`. A view key applies only to that invocation. A failed key ends the request, even if a session is available. +You can also pass the URL as the first positional argument with `elf leaderboard "$TEAM_BOARD_URL"`. Both URL forms work without `AOC_SESSION`. Use `--view-key` for a key provided separately. + ### GitHub Actions In a job with Elf installed, store each board’s full link or standalone key in its own Actions secret. Set the `AOC_USER_AGENT` repository variable to your contact email. The following step writes one export per board to the runner’s temporary directory. From 23391018aacbfe7fafa04b99dce2db8a6cc348d1 Mon Sep 17 00:00:00 2001 From: Caleb Kinney Date: Thu, 3 Dec 2026 13:02:00 -0500 Subject: [PATCH 15/17] Enhance get_private_leaderboard documentation for read-only access and URL support --- elf/client.py | 27 ++++++++++++++++++++++----- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/elf/client.py b/elf/client.py index 5505d2e..c10a5bc 100644 --- a/elf/client.py +++ b/elf/client.py @@ -118,10 +118,11 @@ def get_private_leaderboard( url: str | None = None, ) -> Leaderboard | str | Table: """ - Retrieve a private leaderboard for a given year. + Retrieve a private leaderboard using a session or its read-only view key. - Use a session cookie with access to the board or the board’s read-only - view key. The default output is a structured leaderboard model. + Pass the year and board ID, or provide an official HTML or JSON share URL. + A URL or explicit view key works without a session cookie. The default + output is a structured leaderboard model. Parameters ---------- @@ -153,16 +154,32 @@ def get_private_leaderboard( ------ MissingSessionTokenError If no session token is available and no view key is provided. + TypeError + If neither a URL nor both a year and board ID are supplied. LeaderboardFetchError If fetching, decoding, validating, or reading the cache fails. ValueError - If the year predates Advent of Code, the board ID is nonpositive, - or the output format is unsupported. + If the URL is invalid, URL and explicit keys conflict, the year + predates Advent of Code, the board ID is nonpositive, the view key + is invalid, or the output format is unsupported. Notes ----- Responses are cached for 15 minutes per event, board, and credential. A view key authorizes the request on its own and determines the cache scope. + Session cookies and view keys are not included in cached paths or output. + + Examples + -------- + Fetch a board using its read-only share URL. + + >>> board = get_private_leaderboard( + ... url="https://adventofcode.com/2025/leaderboard/private/view/123456?view_key=KEY" + ... ) # doctest: +SKIP + + Fetch a board using a separate key. + + >>> board = get_private_leaderboard(2025, 123456, view_key="KEY") # doctest: +SKIP """ return get_leaderboard(year, session, board_id, view_key, fmt, url=url) From 86f0aa4a628406c63cdb60c3062a9f3573de397f Mon Sep 17 00:00:00 2001 From: Caleb Kinney Date: Thu, 3 Dec 2026 13:02:07 -0500 Subject: [PATCH 16/17] Update README.md to include read-only key and leaderboard URL options --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 5cdf855..f118cc6 100644 --- a/README.md +++ b/README.md @@ -271,9 +271,10 @@ Usage: elf leaderboard YEAR BOARD_ID elf leaderboard --url URL Options: - --view-key TEXT - --session TEXT - --format table|csv|json|model + --view-key TEXT Read-only key for this board + --session, -s AoC session cookie (env: AOC_SESSION) + --format, -f table|csv|json|model + --url TEXT Official HTML or JSON leaderboard URL ``` Supports: From 9f2b600046845eee27a698030735f4999044c89e Mon Sep 17 00:00:00 2001 From: Caleb Kinney Date: Thu, 3 Dec 2026 13:02:12 -0500 Subject: [PATCH 17/17] Refactor great-docs.yml to reorganize reference sections and ensure proper model references --- great-docs.yml | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/great-docs.yml b/great-docs.yml index ae5bfbe..1677c84 100644 --- a/great-docs.yml +++ b/great-docs.yml @@ -33,11 +33,14 @@ reference: - YearStatus - Leaderboard - OutputFormat - - DoctorReport - - DoctorCheck - - CheckStatus - - SubmissionStatus - - OpenKind + - models.SubmissionStatus + - models.OpenKind + + - title: Local diagnostics + contents: + - doctor.DoctorReport + - doctor.DoctorCheck + - doctor.CheckStatus - title: Puzzle helpers contents: @@ -52,7 +55,6 @@ reference: - title: Submission and leaderboard models contents: - - models.SubmissionStatus - models.Member - models.StarCompletion