add github auth headers if there are GITHUB_TOKEN/GH_TOKEN set

This commit is contained in:
zryfish
2025-09-15 00:06:08 +08:00
parent 60b015a094
commit 70413f5214

View File

@@ -52,6 +52,19 @@ import truststore
ssl_context = truststore.SSLContext(ssl.PROTOCOL_TLS_CLIENT) ssl_context = truststore.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
client = httpx.Client(verify=ssl_context) client = httpx.Client(verify=ssl_context)
def _github_token() -> str | None:
return os.getenv("GH_TOKEN") or os.getenv("GITHUB_TOKEN")
def _github_auth_headers() -> dict:
"""Headers for GitHub REST API requests.
- Uses Bearer auth if token present
"""
headers = {}
token = _github_token()
if token:
headers["Authorization"] = f"Bearer {token}"
return headers
# Constants # Constants
AI_CHOICES = { AI_CHOICES = {
"copilot": "GitHub Copilot", "copilot": "GitHub Copilot",
@@ -427,7 +440,12 @@ def download_template_from_github(ai_assistant: str, download_dir: Path, *, scri
api_url = f"https://api.github.com/repos/{repo_owner}/{repo_name}/releases/latest" api_url = f"https://api.github.com/repos/{repo_owner}/{repo_name}/releases/latest"
try: try:
response = client.get(api_url, timeout=30, follow_redirects=True) response = client.get(
api_url,
timeout=30,
follow_redirects=True,
headers=_github_auth_headers() or None,
)
status = response.status_code status = response.status_code
if status != 200: if status != 200:
msg = f"GitHub API returned {status} for {api_url}" msg = f"GitHub API returned {status} for {api_url}"
@@ -473,7 +491,14 @@ def download_template_from_github(ai_assistant: str, download_dir: Path, *, scri
console.print(f"[cyan]Downloading template...[/cyan]") console.print(f"[cyan]Downloading template...[/cyan]")
try: try:
with client.stream("GET", download_url, timeout=60, follow_redirects=True) as response: # Include auth header for initial GitHub request; it won't leak across cross-origin redirects
with client.stream(
"GET",
download_url,
timeout=60,
follow_redirects=True,
headers=_github_auth_headers() or None,
) as response:
if response.status_code != 200: if response.status_code != 200:
body_sample = response.text[:400] body_sample = response.text[:400]
raise RuntimeError(f"Download failed with {response.status_code}\nHeaders: {response.headers}\nBody (truncated): {body_sample}") raise RuntimeError(f"Download failed with {response.status_code}\nHeaders: {response.headers}\nBody (truncated): {body_sample}")