o
    i                     @  s   d Z ddlmZ ddlmZ ddlZddlmZmZ ddl	m
Z
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 ddlmZ ddlmZmZ eeZG dd de
Z G dd deZ!dS )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field_validator)BaseSettingsSettingsConfigDict)JSONResponse)Route)RemoteAuthProviderTokenVerifier)JWTVerifier)ENV_FILEparse_scopes)
get_logger)NotSetNotSetTc                   @  s\   e Zd ZU ededdZded< ded< dZded	< d
Zded< e	ddde
dd Zd
S )SupabaseProviderSettingsFASTMCP_SERVER_AUTH_SUPABASE_ignore)
env_prefixenv_fileextrar   project_urlbase_urlES256z"Literal['HS256', 'RS256', 'ES256']	algorithmNzlist[str] | Nonerequired_scopesbefore)modec                 C  s   t |S Nr   )clsv r#   l/var/www/html/karishye-ai-python/venv/lib/python3.10/site-packages/fastmcp/server/auth/providers/supabase.py_parse_scopes(   s   z&SupabaseProviderSettings._parse_scopes)__name__
__module____qualname__r   r   model_config__annotations__r   r   r   classmethodr%   r#   r#   r#   r$   r      s   
 
r   c                      sB   e Zd ZdZeeeeddd fddZ	dd fddZ  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 (HS256, 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/v1/.well-known/jwks.json
       - JWTs are issued by {project_url}/auth/v1
       - 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)
        ```
    N)r   r   r   r   token_verifierr   AnyHttpUrl | str | NotSetTr   r   ,Literal['HS256', 'RS256', 'ES256'] | NotSetTr   list[str] | NotSetT | Noner-   TokenVerifier | Nonec                  s   t dd ||||d D }t|jd| _tt|jd| _|du r;t| j d| j d|j	|j
d}t j|t| j dg| jd	 dS )
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
            algorithm: JWT signing algorithm (HS256, 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.
            token_verifier: Optional token verifier. If None, creates JWT verifier for Supabase
        c                 S  s   i | ]\}}|t ur||qS r#   )r   ).0kr"   r#   r#   r$   
<dictcomp>q   s
    z-SupabaseProvider.__init__.<locals>.<dictcomp>)r   r   r   r   /Nz/auth/v1/.well-known/jwks.jsonz/auth/v1)jwks_uriissuerr   r   )r-   authorization_serversr   )r   model_validateitemsstrr   rstripr   r   r   r   r   super__init__)selfr   r   r   r   r-   settings	__class__r#   r$   r>   [   s0   


zSupabaseProvider.__init__mcp_path
str | Nonereturnlist[Route]c                   s2   t  |} fdd}|td|dgd |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              
     s   z:t  4 I dH $}| j dI dH }|  | }t|W  d  I dH  W S 1 I dH s4w   Y  W dS  tyY } ztdd| dddW  Y d}~S d}~ww )zQForward Supabase OAuth authorization server metadata with FastMCP customizations.Nz//auth/v1/.well-known/oauth-authorization-serverserver_errorz#Failed to fetch Supabase metadata: )errorerror_descriptioni  )status_code)httpxAsyncClientgetr   raise_for_statusjsonr   	Exception)requestclientresponsemetadataer?   r#   r$   #oauth_authorization_server_metadata   s&   

4zHSupabaseProvider.get_routes.<locals>.oauth_authorization_server_metadataz'/.well-known/oauth-authorization-serverGET)endpointmethods)r=   
get_routesappendr	   )r?   rC   routesrW   rA   rV   r$   r[      s   zSupabaseProvider.get_routes)
r   r.   r   r.   r   r/   r   r0   r-   r1   r    )rC   rD   rE   rF   )r&   r'   r(   __doc__r   r>   r[   __classcell__r#   r#   rA   r$   r,   .   s    /7r,   )"r^   
__future__r   typingr   rK   pydanticr   r   pydantic_settingsr   r   starlette.responsesr   starlette.routingr	   fastmcp.server.authr
   r   !fastmcp.server.auth.providers.jwtr   fastmcp.settingsr   fastmcp.utilities.authr   fastmcp.utilities.loggingr   fastmcp.utilities.typesr   r   r&   loggerr   r,   r#   r#   r#   r$   <module>   s"    