Skip to content

github_auth

Class info

Classes

Name Children Inherits
CopilotAuthBackend
llmling_models.auth.github_auth
GitHub Copilot device-code auth backend.
    CopilotAuthResult
    llmling_models.auth.github_auth
    Result of Copilot authentication.
      CopilotTokenStore
      llmling_models.auth.github_auth
      File-based token storage for Copilot OAuth.

        🛈 DocStrings

        GitHub Copilot authentication helper.

        Supports both github.com and GitHub Enterprise via device code flow. After login, exchanges the GitHub access token for a Copilot API token.

        Based on the pi-mono implementation by badlogic.

        CopilotAuthBackend

        Bases: ProviderAuthBackend

        GitHub Copilot device-code auth backend.

        Source code in src/llmling_models/auth/github_auth.py
        class CopilotAuthBackend(ProviderAuthBackend):
            """GitHub Copilot device-code auth backend."""
        
            def __init__(self) -> None:
                self._pending_device_codes: dict[str, str] = {}
        
            @property
            def provider_id(self) -> str:
                return "copilot"
        
            def methods(self) -> list[ProviderAuthMethod]:
                return [ProviderAuthMethod(type="oauth", label="Connect GitHub Copilot")]
        
            async def authorize(self, method: int = 0) -> ProviderAuthAuthorization:
                async with httpx2.AsyncClient(timeout=30.0) as client:
                    resp = await client.post(
                        "https://github.com/login/device/code",
                        headers=COPILOT_HEADERS,
                        json={"client_id": COPILOT_CLIENT_ID, "scope": "read:user"},
                    )
                    resp.raise_for_status()
                    data: dict[str, Any] = resp.json()
        
                device_code = data["device_code"]
                user_code = data["user_code"]
                verification_uri = data["verification_uri"]
                self._pending_device_codes[device_code] = device_code
        
                return ProviderAuthAuthorization(
                    url=verification_uri,
                    instructions=f"Enter code: {user_code}",
                    method="auto",
                )
        
            async def callback(
                self,
                *,
                code: str | None = None,
                device_code: str | None = None,
                verifier: str | None = None,
            ) -> bool:
                if not device_code:
                    msg = "Missing device_code for Copilot OAuth"
                    raise ValueError(msg)
                async with httpx2.AsyncClient(timeout=30.0) as client:
                    resp = await client.post(
                        "https://github.com/login/oauth/access_token",
                        headers=COPILOT_HEADERS,
                        data={
                            "client_id": COPILOT_CLIENT_ID,
                            "device_code": device_code,
                            "grant_type": "urn:ietf:params:oauth:grant-type:device_code",
                        },
                    )
                    data: dict[str, Any] = resp.json()
        
                if "error" in data:
                    detail = data.get("error_description", data["error"])
                    raise ValueError(detail)
        
                github_token = data.get("access_token")
                if not github_token:
                    raise ValueError("No token received")
        
                self._pending_device_codes.pop(device_code, None)
        
                # Exchange GitHub token for Copilot API token and store
                copilot_data = refresh_copilot_token(github_token)
                store = CopilotTokenStore()
                store.save({
                    "github_token": github_token,
                    "copilot_token": copilot_data["copilot_token"],
                    "base_url": copilot_data["base_url"],
                    "expires_at": copilot_data["expires_at"],
                    "enterprise_domain": None,
                })
                return True
        

        CopilotAuthResult

        Bases: NamedTuple

        Result of Copilot authentication.

        Source code in src/llmling_models/auth/github_auth.py
        class CopilotAuthResult(NamedTuple):
            """Result of Copilot authentication."""
        
            token: str
            token_type: str
            scope: str
            refresh_token: str | None = None
        

        CopilotTokenStore

        File-based token storage for Copilot OAuth.

        Source code in src/llmling_models/auth/github_auth.py
        class CopilotTokenStore:
            """File-based token storage for Copilot OAuth."""
        
            def __init__(self, path: Path = DEFAULT_TOKEN_PATH) -> None:
                self.path = path
                self.path.parent.mkdir(parents=True, exist_ok=True)
        
            def load(self) -> dict[str, str | float | None] | None:
                """Load stored credentials."""
                if not self.path.exists():
                    return None
                try:
                    return anyenv.load_json(self.path.read_text(), return_type=dict)
                except (anyenv.JsonLoadError, KeyError) as e:
                    logger.warning("Failed to load copilot token from %s: %s", self.path, e)
                    return None
        
            def save(self, data: dict[str, str | float | None]) -> None:
                """Save credentials."""
                write_private_json(self.path, data)
        
            def clear(self) -> None:
                """Remove stored credentials."""
                if self.path.exists():
                    self.path.unlink()
        

        clear

        clear() -> None
        

        Remove stored credentials.

        Source code in src/llmling_models/auth/github_auth.py
        def clear(self) -> None:
            """Remove stored credentials."""
            if self.path.exists():
                self.path.unlink()
        

        load

        load() -> dict[str, str | float | None] | None
        

        Load stored credentials.

        Source code in src/llmling_models/auth/github_auth.py
        def load(self) -> dict[str, str | float | None] | None:
            """Load stored credentials."""
            if not self.path.exists():
                return None
            try:
                return anyenv.load_json(self.path.read_text(), return_type=dict)
            except (anyenv.JsonLoadError, KeyError) as e:
                logger.warning("Failed to load copilot token from %s: %s", self.path, e)
                return None
        

        save

        save(data: dict[str, str | float | None]) -> None
        

        Save credentials.

        Source code in src/llmling_models/auth/github_auth.py
        def save(self, data: dict[str, str | float | None]) -> None:
            """Save credentials."""
            write_private_json(self.path, data)
        

        authenticate_copilot

        authenticate_copilot(
            verbose: bool = True, enterprise_domain: str | None = None
        ) -> dict[str, str | float | None]
        

        Authenticate with GitHub Copilot via device code flow.

        Parameters:

        Name Type Description Default
        verbose bool

        Whether to print authentication status messages

        True
        enterprise_domain str | None

        GitHub Enterprise domain (None for github.com)

        None

        Returns:

        Type Description
        dict[str, str | float | None]

        Dict with keys: github_token, copilot_token, base_url, expires_at,

        dict[str, str | float | None]

        enterprise_domain

        Source code in src/llmling_models/auth/github_auth.py
        def authenticate_copilot(
            verbose: bool = True,
            enterprise_domain: str | None = None,
        ) -> dict[str, str | float | None]:
            """Authenticate with GitHub Copilot via device code flow.
        
            Args:
                verbose: Whether to print authentication status messages
                enterprise_domain: GitHub Enterprise domain (None for github.com)
        
            Returns:
                Dict with keys: github_token, copilot_token, base_url, expires_at,
                enterprise_domain
            """
            domain = enterprise_domain or "github.com"
        
            with httpx2.Client(timeout=30.0) as client:
                # Step 1: Start device flow
                if verbose:
                    print("Requesting GitHub device code...")
                device_data = _start_device_flow(client, domain)
        
                user_code = device_data["user_code"]
                verification_uri = device_data["verification_uri"]
        
                if verbose:
                    print()
                    print("To authenticate with GitHub Copilot, please:")
                    print(f"1. Visit:  {verification_uri}")
                    print(f"2. Enter code:  {user_code}")
                    print("\nWaiting for authentication...")
        
                # Step 2: Poll for GitHub access token
                github_token = _poll_for_github_token(
                    client,
                    domain,
                    str(device_data["device_code"]),
                    int(device_data.get("interval", 5)),
                    int(device_data.get("expires_in", 900)),
                )
        
                if verbose:
                    print("\nGitHub authentication successful!")
                    print("Exchanging for Copilot API token...")
        
                # Step 3: Exchange for Copilot token
                copilot_data = _get_copilot_token(client, github_token, domain)
                copilot_token = str(copilot_data["token"])
                expires_at = copilot_data["expires_at"]
        
                base_url = get_copilot_base_url(copilot_token, enterprise_domain)
        
                if verbose:
                    print(f"Copilot API base URL: {base_url}")
                    print("Authentication complete!")
        
            return {
                "github_token": github_token,
                "copilot_token": copilot_token,
                "base_url": base_url,
                "expires_at": float(expires_at),
                "enterprise_domain": enterprise_domain,
            }
        

        copilot_auth_main

        copilot_auth_main() -> None
        

        Command-line entry point for Copilot authentication.

        Source code in src/llmling_models/auth/github_auth.py
        def copilot_auth_main() -> None:
            """Command-line entry point for Copilot authentication."""
            parser = argparse.ArgumentParser(
                description="Authenticate with GitHub Copilot and get API token."
            )
            parser.add_argument(
                "--silent",
                action="store_true",
                help="Suppress status messages",
            )
            parser.add_argument(
                "--enterprise",
                default=None,
                help="GitHub Enterprise domain (e.g. company.ghe.com)",
            )
            parser.add_argument(
                "--token-path",
                type=Path,
                default=DEFAULT_TOKEN_PATH,
                help=f"Path to store token (default: {DEFAULT_TOKEN_PATH})",
            )
            parser.add_argument(
                "--logout",
                action="store_true",
                help="Remove stored token and log out",
            )
            parser.add_argument(
                "--status",
                action="store_true",
                help="Show current authentication status",
            )
        
            args = parser.parse_args()
            store = CopilotTokenStore(path=args.token_path)
        
            if args.logout:
                store.clear()
                print("Logged out. Token removed.")
                return
        
            if args.status:
                data = store.load()
                if data is None:
                    print("Not authenticated.")
                    sys.exit(1)
                expires_at = data.get("expires_at", 0)
                if isinstance(expires_at, (int, float)) and time.time() < expires_at:
                    remaining = expires_at - time.time()
                    hours = int(remaining // 3600)
                    minutes = int((remaining % 3600) // 60)
                    print(f"Authenticated. Copilot token expires in {hours}h {minutes}m.")
                else:
                    print("Copilot token expired (will refresh automatically on use).")
                print(f"Base URL: {data.get('base_url', 'unknown')}")
                enterprise = data.get("enterprise_domain")
                if enterprise:
                    print(f"Enterprise: {enterprise}")
                print(f"Token path: {args.token_path}")
                return
        
            # Normalize enterprise domain
            enterprise_domain = None
            if args.enterprise:
                enterprise_domain = _normalize_domain(args.enterprise)
                if not enterprise_domain:
                    print(f"Invalid enterprise domain: {args.enterprise}", file=sys.stderr)
                    sys.exit(1)
        
            try:
                result = authenticate_copilot(
                    verbose=not args.silent,
                    enterprise_domain=enterprise_domain,
                )
                store.save(result)
                print(f"\nToken saved to: {args.token_path}")
                print("You can now use GitHub Copilot models.")
        
            except Exception:
                logger.exception("Authentication failed")
                sys.exit(1)
        

        get_copilot_base_url

        get_copilot_base_url(token: str | None = None, enterprise_domain: str | None = None) -> str
        

        Get the Copilot API base URL.

        Prefers extracting from the token's proxy-ep field, falls back to constructing from enterprise domain or default.

        Source code in src/llmling_models/auth/github_auth.py
        def get_copilot_base_url(
            token: str | None = None,
            enterprise_domain: str | None = None,
        ) -> str:
            """Get the Copilot API base URL.
        
            Prefers extracting from the token's proxy-ep field, falls back to
            constructing from enterprise domain or default.
            """
            if token:
                url = _get_base_url_from_token(token)
                if url:
                    return url
            if enterprise_domain:
                return f"https://copilot-api.{enterprise_domain}"
            return "https://api.individual.githubcopilot.com"
        

        get_or_refresh_copilot_token

        get_or_refresh_copilot_token(
            store: CopilotTokenStore | None = None,
        ) -> dict[str, str | float | None]
        

        Get a valid Copilot token, refreshing if necessary.

        The GitHub OAuth token doesn't expire, but the Copilot API token does. This refreshes the Copilot token using the stored GitHub token.

        Source code in src/llmling_models/auth/github_auth.py
        def get_or_refresh_copilot_token(
            store: CopilotTokenStore | None = None,
        ) -> dict[str, str | float | None]:
            """Get a valid Copilot token, refreshing if necessary.
        
            The GitHub OAuth token doesn't expire, but the Copilot API token does.
            This refreshes the Copilot token using the stored GitHub token.
            """
            if store is None:
                store = CopilotTokenStore()
        
            data = store.load()
            if data is None:
                msg = "No Copilot credentials found. Run 'llmling-models copilot-auth' to authenticate."
                raise RuntimeError(msg)
        
            # Check if Copilot token is expired
            expires_at = data.get("expires_at", 0)
            if isinstance(expires_at, (int, float)) and time.time() < expires_at - 300:
                return data
        
            # Refresh using stored GitHub token
            github_token = data.get("github_token")
            if not github_token:
                msg = "Stored credentials missing GitHub token. Re-authenticate."
                raise RuntimeError(msg)
        
            logger.info("Copilot token expired, refreshing...")
            enterprise = data.get("enterprise_domain")
            refreshed = refresh_copilot_token(
                str(github_token),
                str(enterprise) if enterprise else None,
            )
        
            # Merge refreshed data back
            data["copilot_token"] = refreshed["copilot_token"]
            data["base_url"] = refreshed["base_url"]
            data["expires_at"] = refreshed["expires_at"]
            store.save(data)
        
            return data
        

        refresh_copilot_token

        refresh_copilot_token(
            github_token: str, enterprise_domain: str | None = None
        ) -> dict[str, str | float | None]
        

        Refresh the Copilot API token using the stored GitHub token.

        Parameters:

        Name Type Description Default
        github_token str

        The GitHub OAuth access token

        required
        enterprise_domain str | None

        GitHub Enterprise domain (None for github.com)

        None

        Returns:

        Type Description
        dict[str, str | float | None]

        Dict with copilot_token, base_url, expires_at

        Source code in src/llmling_models/auth/github_auth.py
        def refresh_copilot_token(
            github_token: str,
            enterprise_domain: str | None = None,
        ) -> dict[str, str | float | None]:
            """Refresh the Copilot API token using the stored GitHub token.
        
            Args:
                github_token: The GitHub OAuth access token
                enterprise_domain: GitHub Enterprise domain (None for github.com)
        
            Returns:
                Dict with copilot_token, base_url, expires_at
            """
            domain = enterprise_domain or "github.com"
        
            with httpx2.Client(timeout=30.0) as client:
                copilot_data = _get_copilot_token(client, github_token, domain)
        
            copilot_token = str(copilot_data["token"])
            expires_at = copilot_data["expires_at"]
            base_url = get_copilot_base_url(copilot_token, enterprise_domain)
        
            return {
                "copilot_token": copilot_token,
                "base_url": base_url,
                "expires_at": float(expires_at),
            }