
    kKjg9                        d Z ddlmZ ddlZddlmZ ddlZddlmZ ddl	m
Z
 ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ  ee      Z G d de      Z G d de      Zy)aT  GitHub OAuth provider for FastMCP.

This module provides a complete GitHub OAuth integration that's ready to use
with just a client ID and client secret. It handles all the complexity of
GitHub's OAuth flow, token validation, and user management.

Example:
    ```python
    from fastmcp import FastMCP
    from fastmcp.server.auth.providers.github import GitHubProvider

    # Simple GitHub OAuth protection
    auth = GitHubProvider(
        client_id="your-github-client-id",
        client_secret="your-github-client-secret"
    )

    mcp = FastMCP("My Protected Server", auth=auth)
    ```
    )annotationsN)Literal)AsyncKeyValue)
AnyHttpUrl)TokenVerifier)AccessToken)
OAuthProxy)parse_scopes)
get_logger)
TokenCachec                  L     e Zd ZdZdddddd	 	 	 	 	 	 	 	 	 d fdZddZ xZS )	GitHubTokenVerifierav  Token verifier for GitHub OAuth tokens.

    GitHub OAuth tokens are opaque (not JWTs), so we verify them
    by calling GitHub's API to check if they're valid and get user info.

    Caching is disabled by default.  Set ``cache_ttl_seconds`` to a positive
    integer to cache successful verification results and avoid repeated
    GitHub API calls for the same token.
    N
   required_scopestimeout_secondscache_ttl_secondsmax_cache_sizehttp_clientc               f    t         |   |       || _        || _        t	        ||      | _        y)a  Initialize the GitHub token verifier.

        Args:
            required_scopes: Required OAuth scopes (e.g., ['user:email'])
            timeout_seconds: HTTP request timeout
            cache_ttl_seconds: How long to cache verification results in seconds.
                Caching is disabled by default (None).  Set to a positive integer
                to enable (e.g., 300 for 5 minutes).
            max_cache_size: Maximum number of tokens to cache.  Default: 10 000.
            http_client: Optional httpx.AsyncClient for connection pooling. When provided,
                the client is reused across calls and the caller is responsible for its
                lifecycle. When None (default), a fresh client is created per call.
        )r   )ttl_secondsmax_sizeN)super__init__r   _http_clientr   _cache)selfr   r   r   r   r   	__class__s         u/Users/ahmed/devFolder/Ultron/claude-voice/.venv/lib/python3.12/site-packages/fastmcp/server/auth/providers/github.pyr   zGitHubTokenVerifier.__init__4   s7    , 	9.' )#
    c                  K   | j                   j                  |      \  }}|rt        j                  d       |S 	 | j                  t        j                  | j                        nt        j                  | j                        4 d{   }|j                  dd| ddd	       d{   }|j                  d
k7  r@t        j                  d|j                  |j                  dd
        	 ddd      d{    y|j                         }|j                  dd| ddd	       d{   }|j                  d
k(  }|j                  j                  dd      }	|	j                  d      D 
cg c]"  }
|
j                         r|
j                         $ }}
|sdg}| j                   rlt#        |      }t#        | j                         }|j%                  |      s;t        j                  dt'        |      t'        |             	 ddd      d{    yt)        |t+        |j                  dd            |dt+        |d         |j                  d      |j                  d      |j                  d      |j                  d      |d      }|r| j                   j#                  ||       |cddd      d{    S 7 57 7 7 c c}
w 7 7 # 1 d{  7  sw Y   yxY w# t        j,                  $ r }t        j                  d|       Y d}~yd}~wt.        $ r }t        j                  d|       Y d}~yd}~ww xY ww)z0Verify GitHub OAuth token by calling GitHub API.zGitHub token cache hitN)timeoutzhttps://api.github.com/userzBearer zapplication/vnd.github.v3+jsonzFastMCP-GitHub-OAuth)AuthorizationAcceptz
User-Agent)headers   z)GitHub token verification failed: %d - %sz!https://api.github.com/user/reposzx-oauth-scopes ,userz6GitHub token missing required scopes. Has %d, needs %didunknownloginnameemail
avatar_url)subr,   r-   r.   r/   github_user_data)token	client_idscopes
expires_atclaimsz!Failed to verify GitHub token: %sz#GitHub token verification error: %s)r   getloggerdebugr   
contextlibnullcontexthttpxAsyncClientr   status_codetextjsonr%   splitstripr   setissubsetlenr   strRequestError	Exception)r   r2   	is_cachedcached_resultclientresponse	user_datascopes_responsescopes_verifiedoauth_scopes_headerscopetoken_scopestoken_scopes_setrequired_scopes_setresultes                   r   verify_tokenz GitHubTokenVerifier.verify_tokenR   s:    #';;??5#9 	=LL12  V	 $$0 &&t'8'89&&t/C/CDE E !'1+25'):"B&< ", "  ''3.LLC ,, ds+
  )E E E, %MMO	 )/

7+25'):"B&< )3 ) # #2"="="D&5&=&=&A&ABRTV&W# "5!:!:3!? !?{{} KKM!?    $$*8L '''*<'8$*-d.B.B*C'.778HIT 01 34
  $uE E Ez %!)--i"@A'#"9T?3!*w!7 )f 5!*w!7&/mmL&A,5 #KKOOE62[E E E
E4# ME E E E E^ !! 	LL<a@ 	LL>B	s  8MAK) 
J?K) K,K-AK/K) :K;K) ?M -K-K.AK0'KA.KK) KK) MBK-K) 9K:K) >M?K) KK) KKK) K) K&KK&"K) %M&K) )M<LMM#L>9M>MM)
r   list[str] | Noner   intr   
int | Noner   rZ   r   httpx.AsyncClient | None)r2   rF   returnzAccessToken | None)__name__
__module____qualname____doc__r   rW   __classcell__r   s   @r   r   r   )   sV     -1!(,%)04
 *
 	

 &
 #
 .
<]r    r   c                       e Zd ZdZddddddddddddddddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d fdZ xZS )	GitHubProvidera  Complete GitHub OAuth provider for FastMCP.

    This provider makes it trivial to add GitHub OAuth protection to any
    FastMCP server. Just provide your GitHub OAuth app credentials and
    a base URL, and you're ready to go.

    Features:
    - Transparent OAuth proxy to GitHub
    - Automatic token validation via GitHub API
    - User information extraction
    - Minimal configuration required

    Example:
        ```python
        from fastmcp import FastMCP
        from fastmcp.server.auth.providers.github import GitHubProvider

        auth = GitHubProvider(
            client_id="Ov23li...",
            client_secret="abc123...",
            base_url="https://my-server.com"
        )

        mcp = FastMCP("My App", auth=auth)
        ```
    Nr   Tr   )resource_base_url
issuer_urlredirect_pathr   r   r   r   allowed_client_redirect_urisclient_storagejwt_signing_keyrequire_authorization_consentconsent_csp_policyforward_resource%fallback_refresh_token_expiry_seconds#fastmcp_access_token_expiry_secondstoken_expiry_threshold_secondsr   enable_cimdc                   |t        |      ndg}t        |||	|
|      }t        |   dd|||||||xs |||||||||||       t        j                  d||       y)aO  Initialize GitHub OAuth provider.

        Args:
            client_id: GitHub OAuth app client ID (e.g., "Ov23li...")
            client_secret: GitHub OAuth app client secret
            base_url: Public URL where OAuth endpoints will be accessible (includes any mount path)
            resource_base_url: Optional public base URL for the protected resource metadata
                and token audience. Defaults to ``base_url``.
            issuer_url: Issuer URL for OAuth metadata (defaults to base_url). Use root-level URL
                to avoid 404s during discovery when mounting under a path.
            redirect_path: Redirect path configured in GitHub OAuth app (defaults to "/auth/callback")
            required_scopes: Required GitHub scopes (defaults to ["user"])
            timeout_seconds: HTTP request timeout for GitHub API calls (defaults to 10)
            cache_ttl_seconds: How long to cache token verification results in seconds.
                Caching is disabled by default (None).  Set to a positive integer to
                enable (e.g., 300 for 5 minutes).
            max_cache_size: Maximum number of tokens to cache.  Default: 10 000.
            allowed_client_redirect_uris: List of allowed redirect URI patterns for MCP clients.
                If None (default), all URIs are allowed. If empty list, no URIs are allowed.
            client_storage: Storage backend for OAuth state (client registrations, encrypted tokens).
                If None, an encrypted file store will be created in the data directory
                (derived from `platformdirs`).
            jwt_signing_key: Secret for signing FastMCP JWT tokens (any string or bytes). If bytes are provided,
                they will be used as is. If a string is provided, it will be derived into a 32-byte key. If not
                provided, the upstream client secret will be used to derive a 32-byte key using PBKDF2.
            require_authorization_consent: Whether to require user consent before authorizing clients (default True).
                When True, users see a consent screen before being redirected to GitHub.
                When False, authorization proceeds directly without user confirmation.
                When "external", the built-in consent screen is skipped but no warning is
                logged, indicating that consent is handled externally (e.g. by the upstream IdP).
                SECURITY WARNING: Only set to False for local development or testing environments.
            http_client: Optional httpx.AsyncClient for connection pooling in token verification.
                When provided, the client is reused across verify_token calls and the caller
                is responsible for its lifecycle. When None (default), a fresh client is created per call.
            enable_cimd: Enable CIMD (Client ID Metadata Document) support for URL-based
                client IDs (default True). Set to False to disable.
            fallback_refresh_token_expiry_seconds: Lifetime for the FastMCP-issued
                refresh token when the upstream provider omits `refresh_expires_in`
                (e.g. Cognito, GitHub, many OIDC IdPs). Defaults to 1 year. The upstream
                refresh remains the source of truth. See `OAuthProxy` for details.
            fastmcp_access_token_expiry_seconds: Lifetime for the FastMCP-issued access
                token, decoupling it from the upstream provider's `expires_in`. Defaults
                to None (mirror the upstream lifetime). Set this for bridges whose
                upstream issues short-lived access tokens that some MCP clients can't
                refresh gracefully (e.g. `mcp-remote`). See `OAuthProxy` for details.
            token_expiry_threshold_seconds: Number of seconds before actual expiry to
                treat a token as expired, refreshing early to avoid races. Defaults to 0.
        Nr)   r   z(https://github.com/login/oauth/authorizez+https://github.com/login/oauth/access_token)upstream_authorization_endpointupstream_token_endpointupstream_client_idupstream_client_secrettoken_verifierbase_urlre   rg   rf   rh   ri   rj   rk   rl   rm   rn   ro   rp   rq   z?Initialized GitHub OAuth provider for client %s with scopes: %s)r
   r   r   r   r8   r9   )r   r3   client_secretrx   re   rf   rg   r   r   r   r   rh   ri   rj   rk   rl   rm   rn   ro   rp   r   rq   required_scopes_finalrw   r   s                           r   r   zGitHubProvider.__init__   s    V .=-HL)vh 	
 -1+/)#
 	,V$Q(#0)/'!-X)E)+*G1-2W0S+I#' 	 	
, 	M!	
r    )*r3   rF   ry   rF   rx   zAnyHttpUrl | strre   AnyHttpUrl | str | Nonerf   r{   rg   
str | Noner   rX   r   rY   r   rZ   r   rZ   rh   rX   ri   zAsyncKeyValue | Nonerj   zstr | bytes | Nonerk   z&bool | Literal['remember', 'external']rl   r|   rm   boolrn   rZ   ro   rZ   rp   rY   r   r[   rq   r}   )r]   r^   r_   r`   r   ra   rb   s   @r   rd   rd      s5   B 6:.2$(,0!(,%)9=/3.2PT)-!%<@:>./04 /r
 r
 	r

 #r
 3r
 ,r
 "r
 *r
 r
 &r
 #r
 '7r
 -r
 ,r
  (N!r
" '#r
$ %r
& 0:'r
( .8)r
* ),+r
, .-r
. /r
 r
r    rd   )r`   
__future__r   r:   typingr   r<   key_value.aio.protocolsr   pydanticr   fastmcp.server.authr   fastmcp.server.auth.authr   fastmcp.server.auth.oauth_proxyr	   fastmcp.utilities.authr
   fastmcp.utilities.loggingr   fastmcp.utilities.token_cacher   r]   r8   r   rd    r    r   <module>r      sW   * #    1  - 0 6 / 0 4	H	F- FRN
Z N
r    