
    kKj<                        d Z ddlm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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y)a  Supabase authentication provider for FastMCP.

This module provides SupabaseProvider - a complete authentication solution that integrates
with Supabase Auth's JWT verification, supporting Dynamic Client Registration (DCR)
for seamless MCP client authentication.
    )annotations)LiteralN)
AnyHttpUrl)JSONResponse)Route)RemoteAuthProviderTokenVerifier)JWTVerifier)parse_scopes)
get_loggerc                  n     e Zd ZdZdddddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d fdZ	 d		 	 	 d
 fdZ xZS )SupabaseProvidera  Supabase metadata provider for DCR (Dynamic Client Registration).

    This provider implements Supabase Auth integration using metadata forwarding.
    This approach allows Supabase to handle the OAuth flow directly while FastMCP acts
    as a resource server, verifying JWTs issued by Supabase Auth.

    IMPORTANT SETUP REQUIREMENTS:

    1. Supabase Project Setup:
       - Create a Supabase project at https://supabase.com
       - Note your project URL (e.g., "https://abc123.supabase.co")
       - Configure your JWT algorithm in Supabase Auth settings (RS256 or ES256)
       - Asymmetric keys (RS256/ES256) are recommended for production

    2. JWT Verification:
       - FastMCP verifies JWTs using the JWKS endpoint at {project_url}{auth_route}/.well-known/jwks.json
       - JWTs are issued by {project_url}{auth_route}
       - Default auth_route is "/auth/v1" (can be customized for self-hosted setups)
       - Tokens are cached for up to 10 minutes by Supabase's edge servers
       - Algorithm must match your Supabase Auth configuration

    3. Authorization:
       - Supabase uses Row Level Security (RLS) policies for database authorization
       - OAuth-level scopes are an upcoming feature in Supabase Auth
       - Both approaches will be supported once scope handling is available

    For detailed setup instructions, see:
    https://supabase.com/docs/guides/auth/jwts

    Example:
        ```python
        from fastmcp.server.auth.providers.supabase import SupabaseProvider

        # Create Supabase metadata provider (JWT verifier created automatically)
        supabase_auth = SupabaseProvider(
            project_url="https://abc123.supabase.co",
            base_url="https://your-fastmcp-server.com",
            algorithm="ES256",  # Match your Supabase Auth configuration
        )

        # Use with FastMCP
        mcp = FastMCP("My App", auth=supabase_auth)
        ```
    z/auth/v1ES256N)
auth_route	algorithmrequired_scopesscopes_supportedresource_nameresource_documentationtoken_verifierc       	           t        |      j                  d      | _        t        t        |      j                  d            | _        |j                  d      | _        |t        |      nd}
|	Xt        j                  d       t        | j                   d| j                   d| j                   d| j                   |d|
      }	t        | 1  |	t        | j                   d| j                         g| j                  |||       y)a  Initialize Supabase metadata provider.

        Args:
            project_url: Your Supabase project URL (e.g., "https://abc123.supabase.co")
            base_url: Public URL of this FastMCP server
            auth_route: Supabase Auth route. Defaults to "/auth/v1". Can be customized
                for self-hosted Supabase Auth setups using custom routes.
            algorithm: JWT signing algorithm (RS256 or ES256). Must match your
                Supabase Auth configuration. Defaults to ES256.
            required_scopes: Optional list of scopes to require for all requests.
                Note: Supabase currently uses RLS policies for authorization. OAuth-level
                scopes are an upcoming feature.
            scopes_supported: Optional list of scopes to advertise in OAuth metadata.
                If None, uses required_scopes. Use this when the scopes clients should
                request differ from the scopes enforced on tokens.
            resource_name: Optional name for the protected resource metadata.
            resource_documentation: Optional documentation URL for the protected resource.
            token_verifier: Optional token verifier. If None, creates JWT verifier for Supabase
        /NzSupabaseProvider cannot validate token audience for the specific resource because Supabase Auth does not support RFC 8707 resource indicators. This may leave the server vulnerable to cross-server token replay.z/.well-known/jwks.jsonauthenticated)jwks_uriissuerr   audiencer   )r   authorization_serversbase_urlr   r   r   )strrstripproject_urlr   r   stripr   r   loggerwarningr
   super__init__)selfr!   r   r   r   r   r   r   r   r   parsed_scopes	__class__s              w/Users/ahmed/devFolder/Ultron/claude-voice/.venv/lib/python3.12/site-packages/fastmcp/server/auth/providers/supabase.pyr&   zSupabaseProvider.__init__G   s   @ {+2237"3x=#7#7#<=$**3/ .=-HL)d 	
 !NNU
 ) ,,-Qt.??UV**+1T__,=>#( -N 	)#-1A1A0B!DOOCT.U#V"W]]-'#9 	 	
    c                n     t            |      } fd}|j                  t        d|dg             |S )a  Get OAuth routes including Supabase authorization server metadata forwarding.

        This returns the standard protected resource routes plus an authorization server
        metadata endpoint that forwards Supabase's OAuth metadata to clients.

        Args:
            mcp_path: The path where the MCP endpoint is mounted (e.g., "/mcp")
                This is used to advertise the resource URL in metadata.
        c                  K   	 t        j                         4 d{   }|j                  j                   dj                   d       d{   }|j                          |j                         }t        |      cddd      d{    S 7 s7 B7 	# 1 d{  7  sw Y   yxY w# t        $ r}t        dd| dd      cY d}~S d}~ww xY ww)	zQForward Supabase OAuth authorization server metadata with FastMCP customizations.Nr   '/.well-known/oauth-authorization-serverserver_errorz#Failed to fetch Supabase metadata: )errorerror_descriptioni  )status_code)	httpxAsyncClientgetr!   r   raise_for_statusjsonr   	Exception)requestclientresponsemetadataer'   s        r*   #oauth_authorization_server_metadatazHSupabaseProvider.get_routes.<locals>.oauth_authorization_server_metadata   s      ,,..&%+ZZ++,Adoo->>ef&  H --/'}}H'1 /..  /...  #!//RSTRU-V !$ s   CB, BB, /BB.B?B, BB, CB, BB, B)B B)%B, (C)B, ,	C5CCCCCr.   GET)endpointmethods)r%   
get_routesappendr   )r'   mcp_pathroutesr>   r)   s   `   r*   rB   zSupabaseProvider.get_routes   sA     #H-	( 	9<	
 r+   )r!   AnyHttpUrl | strr   rF   r   r   r   zLiteral['RS256', 'ES256']r   list[str] | Noner   rG   r   
str | Noner   zAnyHttpUrl | Noner   zTokenVerifier | None)N)rD   rH   returnzlist[Route])__name__
__module____qualname____doc__r&   rB   __classcell__)r)   s   @r*   r   r      s    +d %/6,0-1$(48/3@
 &@
 #	@

 @
 -@
 *@
 +@
 "@
 !2@
 -@
H  $,, 
, ,r+   r   )rM   
__future__r   typingr   r3   pydanticr   starlette.responsesr   starlette.routingr   fastmcp.server.authr   r	   !fastmcp.server.auth.providers.jwtr
   fastmcp.utilities.authr   fastmcp.utilities.loggingr   rJ   r#   r    r+   r*   <module>rY      sC    #    , # A 9 / 0	H	\) \r+   