|
| 1 | +import json |
| 2 | +import logging |
| 3 | +import time |
| 4 | +import urllib.error |
| 5 | +import urllib.parse |
| 6 | +import urllib.request |
| 7 | +from typing import Callable |
| 8 | + |
| 9 | +from core.utils.utilities import app_data_path |
| 10 | + |
| 11 | +_OAUTH_APPS = { |
| 12 | + "notifications": {"client_id": "Ov23li0KAXuxNzbEl9Jy", "scope": "notifications"}, |
| 13 | + "copilot": {"client_id": "Iv23lixvCWMEuoUakkey", "scope": ""}, |
| 14 | +} |
| 15 | + |
| 16 | +_TOKEN_FILES = { |
| 17 | + "notifications": app_data_path("github_token"), |
| 18 | + "copilot": app_data_path("github_copilot_token"), |
| 19 | +} |
| 20 | + |
| 21 | + |
| 22 | +def get_saved_token(name: str = "notifications") -> str: |
| 23 | + """Read a saved OAuth token from disk. Returns empty string if not found.""" |
| 24 | + try: |
| 25 | + path = _TOKEN_FILES[name] |
| 26 | + if path.exists(): |
| 27 | + return path.read_text(encoding="utf-8").strip() |
| 28 | + except Exception as e: |
| 29 | + logging.error(f"GitHubAuth: Failed to read saved token: {e}") |
| 30 | + return "" |
| 31 | + |
| 32 | + |
| 33 | +def save_token(token: str, name: str = "notifications") -> None: |
| 34 | + """Persist an OAuth token to disk.""" |
| 35 | + try: |
| 36 | + _TOKEN_FILES[name].write_text(token, encoding="utf-8") |
| 37 | + logging.info("GitHubAuth token saved successfully.") |
| 38 | + except Exception as e: |
| 39 | + logging.error(f"GitHubAuth failed to save token: {e}") |
| 40 | + |
| 41 | + |
| 42 | +def request_device_code(name: str = "notifications") -> dict: |
| 43 | + """ |
| 44 | + Request a device code from GitHub OAuth Device Flow. |
| 45 | + Returns dict with: device_code, user_code, verification_uri, expires_in, interval. |
| 46 | + Raises on network/API error. |
| 47 | + """ |
| 48 | + app = _OAUTH_APPS[name] |
| 49 | + params = {"client_id": app["client_id"]} |
| 50 | + if app["scope"]: |
| 51 | + params["scope"] = app["scope"] |
| 52 | + data = urllib.parse.urlencode(params).encode("utf-8") |
| 53 | + req = urllib.request.Request( |
| 54 | + "https://github.com/login/device/code", |
| 55 | + data=data, |
| 56 | + headers={"Accept": "application/json"}, |
| 57 | + method="POST", |
| 58 | + ) |
| 59 | + try: |
| 60 | + with urllib.request.urlopen(req, timeout=10) as resp: |
| 61 | + raw = resp.read().decode("utf-8") |
| 62 | + return json.loads(raw) |
| 63 | + except urllib.error.HTTPError as e: |
| 64 | + body = e.read().decode("utf-8", errors="replace") |
| 65 | + logging.error(f"GitHubAuth HTTP {e.code}: {body}") |
| 66 | + raise RuntimeError(f"GitHub returned HTTP {e.code}.\nDetails: {body}") from e |
| 67 | + except urllib.error.URLError as e: |
| 68 | + logging.error(f"GitHubAuth network error: {e}") |
| 69 | + raise RuntimeError("Network error.\nCheck your internet connection.") from e |
| 70 | + |
| 71 | + |
| 72 | +def poll_for_token( |
| 73 | + device_code: str, |
| 74 | + interval: int, |
| 75 | + on_success: Callable[[str], None], |
| 76 | + on_error: Callable[[str], None], |
| 77 | + stop_flag: Callable[[], bool], |
| 78 | + save_fn: Callable[[str], None] | None = None, |
| 79 | + name: str = "notifications", |
| 80 | +) -> None: |
| 81 | + """ |
| 82 | + Poll GitHub for an access token after the user has authorized the device. |
| 83 | + Runs in a background thread. |
| 84 | +
|
| 85 | + - on_success(token) is called when the user approves. |
| 86 | + - on_error(message) is called on any unrecoverable error. |
| 87 | + - stop_flag() should return True to cancel polling early. |
| 88 | + """ |
| 89 | + poll_interval = max(interval, 5) |
| 90 | + cid = _OAUTH_APPS[name]["client_id"] |
| 91 | + post_data_base = { |
| 92 | + "client_id": cid, |
| 93 | + "device_code": device_code, |
| 94 | + "grant_type": "urn:ietf:params:oauth:grant-type:device_code", |
| 95 | + } |
| 96 | + |
| 97 | + while not stop_flag(): |
| 98 | + time.sleep(poll_interval) |
| 99 | + if stop_flag(): |
| 100 | + return |
| 101 | + try: |
| 102 | + encoded = urllib.parse.urlencode(post_data_base).encode("utf-8") |
| 103 | + req = urllib.request.Request( |
| 104 | + "https://github.com/login/oauth/access_token", |
| 105 | + data=encoded, |
| 106 | + headers={"Accept": "application/json"}, |
| 107 | + method="POST", |
| 108 | + ) |
| 109 | + with urllib.request.urlopen(req, timeout=15) as resp: |
| 110 | + result = json.loads(resp.read().decode("utf-8")) |
| 111 | + |
| 112 | + error = result.get("error") |
| 113 | + if error == "authorization_pending": |
| 114 | + continue |
| 115 | + elif error == "slow_down": |
| 116 | + poll_interval += 5 |
| 117 | + continue |
| 118 | + elif error == "expired_token": |
| 119 | + on_error("Device code expired.\nPlease try again.") |
| 120 | + return |
| 121 | + elif error == "access_denied": |
| 122 | + on_error("Authorization was denied.") |
| 123 | + return |
| 124 | + elif error: |
| 125 | + on_error(f"Authorization failed: {error}") |
| 126 | + return |
| 127 | + |
| 128 | + token = result.get("access_token", "") |
| 129 | + if token: |
| 130 | + _save = save_fn if save_fn is not None else save_token |
| 131 | + _save(token) |
| 132 | + on_success(token) |
| 133 | + return |
| 134 | + |
| 135 | + except urllib.error.URLError: |
| 136 | + on_error("Network error.\nCheck your internet connection.") |
| 137 | + return |
| 138 | + except Exception as e: |
| 139 | + logging.error(f"GitHubAuth polling error: {e}") |
| 140 | + on_error(f"Unexpected error: {e}") |
| 141 | + return |
0 commit comments