AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary
Python ai-promptsai-skillblueskyclaudeclaude-codeclawhubdeep-researchhackernewsinstagramopenclawpolymarketrecencyredditresearchsocial-mediatiktoktrendstwitterweb-searchyoutube
fix: use device auth without forwarding gh tokens (#470)
Shaan Majid29bb5487727c
diff --git a/skills/last30days/scripts/lib/setup_wizard.py b/skills/last30days/scripts/lib/setup_wizard.pyindex 8f8047a3..03218adb 100644--- a/skills/last30days/scripts/lib/setup_wizard.py+++ b/skills/last30days/scripts/lib/setup_wizard.py@@ -252,44 +252,6 @@ def run_openclaw_setup(config: Dict[str, Any]) -> Dict[str, Any]:}-# ----------------------------------------------------------------------------# PAT auth flow (GitHub token via ScrapeCreators)-# -----------------------------------------------------------------------------_PAT_BASE = "https://api.scrapecreators.com/v1/github/pat"---def auth_with_pat(github_token: str) -> Optional[Dict[str, Any]]:- """Authenticate with ScrapeCreators using a GitHub PAT.-- POSTs the token to the PAT auth endpoint. ScrapeCreators verifies it- against GitHub's API, creates/finds the account, and returns an API key.-- Returns:- Dict with api_key, github_username, etc. on success, None on failure.- """- try:- req = Request(f"{_PAT_BASE}/auth", data=b"", method="POST")- req.add_header("Authorization", f"Bearer {github_token}")- with urlopen(req, timeout=15) as resp:- data = json.loads(resp.read())- except HTTPError as exc:- if exc.code == 422:- logger.warning("PAT auth: insufficient scope — user needs user:email")- else:- logger.warning("PAT auth failed: %s", exc)- return None- except (URLError, OSError) as exc:- logger.warning("PAT auth request failed: %s", exc)- return None-- if not data.get("api_key"):- logger.warning("PAT auth returned no api_key: %s", data)- return None-- return data--# ---------------------------------------------------------------------------# Device auth flow (GitHub OAuth via ScrapeCreators)# ---------------------------------------------------------------------------@@ -499,52 +461,16 @@ def run_full_device_auth(timeout: int = 300) -> Dict[str, Any]:# ----------------------------------------------------------------------------# Unified GitHub auth: PAT first, device flow fallback+# Unified GitHub auth# ---------------------------------------------------------------------------def run_github_auth(timeout: int = 300) -> Dict[str, Any]:- """Try PAT auth via gh CLI, fall back to device flow.+ """Run the --github setup path via device auth only.- 1. Check for `gh` CLI- 2. If found, run `gh auth token` to get a PAT- 3. POST PAT to ScrapeCreators — if it works, done- 4. If PAT fails for any reason, fall through to device flow+ Kept as the semantic entry point for GitHub-backed setup; this path must+ not read or forward local GitHub CLI tokens.Returns JSON-serializable dict with status, method, and api_key."""- import sys-- # Step 1: Try PAT via gh CLI- gh_path = shutil.which("gh")- if gh_path:- try:- result = subprocess.run(- ["gh", "auth", "token"],- capture_output=True, text=True, timeout=10,- )- if result.returncode == 0 and result.stdout.strip():- token = result.stdout.strip()- print("Found gh CLI — trying PAT auth...", file=sys.stderr)- pat_result = auth_with_pat(token)- if pat_result and pat_result.get("api_key"):- return {- "status": "success",- "method": "pat",- "api_key": pat_result["api_key"],- "github_username": pat_result.get("github_username", ""),- }- # PAT failed — might be insufficient scope- print(- "PAT auth didn't work (scope or endpoint issue). "- "Falling back to GitHub device flow...",- file=sys.stderr,- )- except Exception as exc:- logger.debug("gh auth token failed: %s", exc)-- # Step 2: Fall back to device flow- if not gh_path:- print("gh CLI not found — using GitHub device flow...", file=sys.stderr)-return run_full_device_auth(timeout=timeout)diff --git a/tests/test_setup_openclaw.py b/tests/test_setup_openclaw.pyindex f0c0b840..c165a4ad 100644--- a/tests/test_setup_openclaw.py+++ b/tests/test_setup_openclaw.py@@ -383,74 +383,6 @@ class TestRunFullDeviceAuth:mock_browser.assert_not_called()-class TestAuthWithPat:- """Tests for auth_with_pat()."""-- @patch("lib.setup_wizard.urlopen")- def test_success(self, mock_urlopen):- """Valid PAT -> returns dict with api_key."""- resp = MagicMock()- resp.read.return_value = json.dumps({- "api_key": "sc_live_test123",- "github_username": "testuser",- "credits_remaining": 100,- }).encode()- resp.__enter__ = lambda s: s- resp.__exit__ = MagicMock(return_value=False)- mock_urlopen.return_value = resp-- result = setup_wizard.auth_with_pat("gho_validtoken")-- assert result is not None- assert result["api_key"] == "sc_live_test123"- assert result["github_username"] == "testuser"-- @patch("lib.setup_wizard.urlopen")- def test_invalid_token_returns_none(self, mock_urlopen):- """HTTP 401 (invalid token) -> returns None."""- from urllib.error import HTTPError- mock_urlopen.side_effect = HTTPError(- url="https://api.scrapecreators.com/v1/github/pat/auth",- code=401, msg="Unauthorized", hdrs={}, fp=None,- )-- result = setup_wizard.auth_with_pat("gho_badtoken")- assert result is None-- @patch("lib.setup_wizard.urlopen")- def test_insufficient_scope_returns_none(self, mock_urlopen):- """HTTP 422 (insufficient scope) -> returns None."""- from urllib.error import HTTPError- mock_urlopen.side_effect = HTTPError(- url="https://api.scrapecreators.com/v1/github/pat/auth",- code=422, msg="Unprocessable", hdrs={}, fp=None,- )-- result = setup_wizard.auth_with_pat("gho_noscope")- assert result is None-- @patch("lib.setup_wizard.urlopen")- def test_network_error_returns_none(self, mock_urlopen):- """URLError -> returns None."""- from urllib.error import URLError- mock_urlopen.side_effect = URLError("Connection refused")-- result = setup_wizard.auth_with_pat("gho_anytoken")- assert result is None-- @patch("lib.setup_wizard.urlopen")- def test_no_api_key_in_response(self, mock_urlopen):- """Response without api_key -> returns None."""- resp = MagicMock()- resp.read.return_value = json.dumps({"error": "something"}).encode()- resp.__enter__ = lambda s: s- resp.__exit__ = MagicMock(return_value=False)- mock_urlopen.return_value = resp-- result = setup_wizard.auth_with_pat("gho_validtoken")- assert result is None--class TestClipboardDeviceAuth:"""Tests for clipboard-first behavior in run_full_device_auth()."""@@ -500,51 +432,11 @@ class TestClipboardDeviceAuth:class TestRunGithubAuth:- """Tests for run_github_auth() — PAT-first with device fallback."""-- @patch("lib.setup_wizard.auth_with_pat")- @patch("subprocess.run")- @patch("shutil.which", return_value="/usr/local/bin/gh")- def test_pat_success(self, mock_which, mock_subproc, mock_pat):- """gh found + valid token + PAT endpoint success -> pat method."""- mock_subproc.return_value = MagicMock(- returncode=0, stdout="gho_testtoken123\n",- )- mock_pat.return_value = {- "api_key": "sc_live_fromPAT",- "github_username": "testuser",- }-- result = setup_wizard.run_github_auth(timeout=10)-- assert result["status"] == "success"- assert result["method"] == "pat"- assert result["api_key"] == "sc_live_fromPAT"-- @patch("lib.setup_wizard.run_full_device_auth")- @patch("lib.setup_wizard.auth_with_pat", return_value=None)- @patch("subprocess.run")- @patch("shutil.which", return_value="/usr/local/bin/gh")- def test_pat_fails_falls_to_device(self, mock_which, mock_subproc, mock_pat, mock_device):- """gh found + PAT endpoint fails -> falls through to device flow."""- mock_subproc.return_value = MagicMock(- returncode=0, stdout="gho_badtoken\n",- )- mock_device.return_value = {- "status": "success", "method": "device",- "api_key": "sc_live_fromDevice",- }-- result = setup_wizard.run_github_auth(timeout=10)-- assert result["status"] == "success"- assert result["method"] == "device"- mock_device.assert_called_once()+ """Tests for run_github_auth() — device flow only."""@patch("lib.setup_wizard.run_full_device_auth")- @patch("shutil.which", return_value=None)- def test_no_gh_goes_to_device(self, mock_which, mock_device):- """gh not installed -> straight to device flow."""+ def test_goes_to_device_flow(self, mock_device):+ """Setup never forwards a local gh PAT to ScrapeCreators."""mock_device.return_value = {"status": "success", "method": "device","api_key": "sc_live_deviceOnly",@@ -554,21 +446,12 @@ class TestRunGithubAuth:assert result["status"] == "success"assert result["method"] == "device"+ mock_device.assert_called_once_with(timeout=10)@patch("lib.setup_wizard.run_full_device_auth")- @patch("subprocess.run")- @patch("shutil.which", return_value="/usr/local/bin/gh")- def test_gh_not_logged_in_falls_to_device(self, mock_which, mock_subproc, mock_device):- """gh exists but not logged in (exit code 1) -> device flow."""- mock_subproc.return_value = MagicMock(- returncode=1, stdout="", stderr="not logged in",- )- mock_device.return_value = {- "status": "success", "method": "device",- "api_key": "sc_live_fallback",- }-- result = setup_wizard.run_github_auth(timeout=10)-- assert result["status"] == "success"- assert result["method"] == "device"+ @patch("subprocess.run", side_effect=AssertionError("must not read gh auth token"))+ def test_does_not_shell_out_for_gh_token(self, mock_subproc, mock_device):+ mock_device.return_value = {"status": "timeout", "user_code": "ABCD-1234"}+ result = setup_wizard.run_github_auth(timeout=1)+ assert result["status"] == "timeout"+ mock_subproc.assert_not_called()