
    ^j/                        d Z ddlZddlmZ ddlmZmZ ddlZddlm	Z	 ddl
mZmZ dd	lmZmZ d
ZdZ G d de      Z G d ded      ZdefdZdddedeg df   dz  defdZdedefdZdej0                  defdZy)aA  Device Code OAuth (RFC 8628) for browser-based login, plus access token refresh.

The flow: the client requests a device code, displays a URL and a short user code, the user
authorizes in a browser, and the client polls ``POST {ENDPOINT}/oauth/token`` until a token is
issued. Access tokens may come with a refresh token, used to renew them transparently (see
``utils/_auth.py::get_token``).

This module is self-contained protocol logic: no printing, no persistence. Interactive flows
live in ``_login.py`` (human/library) and ``cli/auth.py`` (machine-readable event stream).
    N)Callable)	TypedDictcast   )	constants)DeviceCodeErrorOAuthErrorCode   )get_sessionhf_raise_for_statusz,urn:ietf:params:oauth:grant-type:device_coderefresh_tokenc                   J    e Zd ZU eed<   eed<   eed<   eed<   eed<   eed<   y)DeviceCodeInfodevice_code	user_codeverification_uriverification_uri_completeinterval
expires_inN__name__
__module____qualname__str__annotations__int     n/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/huggingface_hub/utils/_oauth_device.pyr   r   (   s#    N""MOr   r   c                   6    e Zd ZU eed<   eed<   eed<   eed<   y)OAuthTokenResponseaccess_tokenr   r   
token_typeNr   r   r   r   r!   r!   1   s    OOr   r!   F)totalreturnc                     	 t               j                  t        j                   ddt        j                  it        j
                        } t        |        | j                         }|j                  dd       |j                  d	d
       |j                  d      s|d   |d<   t        t        |      S # t        j                  $ r%}t        dt        j                   d|       |d}~ww xY w)a'  Request a device code from the Hub's OAuth device authorization endpoint.

    The returned dict is normalized: `interval`, `expires_in` and `verification_uri_complete`
    are always set (server values, or sensible defaults).

    Raises:
        [`DeviceCodeError`]: If the request fails.
    z/oauth/device	client_iddatatimeoutz#Failed to request device code from z/oauth/device: Nr      r   i  r   r   )r   postr   ENDPOINTDEVICE_CODE_OAUTH_CLIENT_IDHF_HUB_DOWNLOAD_TIMEOUTr   httpx	HTTPErrorr   json
setdefaultgetr   r   )responseeinfos      r   request_device_coder8   8   s    s=%%!!"-0yDDE55 & 

 	H% ==?D 	OOJ"OOL#&88/0,01C,D()%% ?? s CIDVDVCWWfghfijkqrrss   AB5 5C- C((C-)
on_pendingdevice_infor9   c          	         | d   }t        j                         | d   z   }t        j                         |k  rd}	 t               j                  t        j
                   dt        | d   t        j                  dt        j                        }|j                  dk  r|j                         }|d	|v rt        t        |      S |j!                  d
      x nxt"        j$                  k(  r | |        nxt"        j&                  k(  r |dz  }nxt"        j(                  k(  r t+        dt"        j(                        xt"        j,                  k(  r t+        dt"        j,                        }t+        d| d|j!                  dd       |      t        j.                  |       t        j                         |k  rt+        dt"        j(                        # t        j                  t        f$ r Y Iw xY w)aw  Poll the token endpoint until the user authorizes the device.

    Args:
        device_info (`DeviceCodeInfo`):
            The device authorization response from [`request_device_code`].
        on_pending (`Callable`, *optional*):
            Called after each "authorization pending" response (e.g. to print a progress dot).

    Returns:
        `OAuthTokenResponse`: the full token response: `access_token`, and optionally
        `refresh_token` and `expires_in`.

    Raises:
        [`DeviceCodeError`]: If authorization is denied, the device code expires, or the server
            returns an unexpected OAuth error.
    r   r   N/oauth/tokenr   )
grant_typer   r'   r(     r"   errorr+   z&Device code expired. Please try again.
error_codez+Authorization was denied. Please try again.zOAuth error:  - error_description z0Device code expired (timeout). Please try again.)time	monotonicr   r,   r   r-   _DEVICE_CODE_GRANT_TYPEr.   r/   status_coder2   r0   r1   
ValueErrorr   r!   r4   r	   AUTHORIZATION_PENDING	SLOW_DOWNEXPIRED_TOKENr   ACCESS_DENIEDsleep)r:   r9   r   deadliner)   r5   r?   s          r   poll_device_tokenrP   T   s   & :&H~~+l";;H
..
X
% 	"}))%%&l3"9#.}#=!*!F!F
 "99 * H ##c)}} %.55((7#9^99!-"-^--MH1^11)@^MiMi  2^11)ER`RnRn  )'wc$((;NPR2S1TUbg  	

8[ ..
X
%^ LYgYuYu
vv= , 		s   A3G G87G8c           	         	 t               j                  t        j                   dt        | t        j
                  dt        j                        }t        |      }d|v rt        t        |      S |j                  d      }t        d|xs |j                   d|j                  d	d
       |      # t        j                  $ r}t        d|       |d}~ww xY w)a  Exchange a refresh token for a new access token.

    Returns:
        `OAuthTokenResponse`: the full token response: `access_token`, and optionally a rotated
        `refresh_token` and `expires_in`.

    Raises:
        [`DeviceCodeError`]: If the server rejects the refresh (`error_code="invalid_grant"` when
            the refresh token is expired or revoked) or returns an unexpected response.
    r<   )r=   r   r'   r(   z Failed to refresh access token: Nr"   r?   rB   rC   rD   r@   )r   r,   r   r-   _REFRESH_TOKEN_GRANT_TYPEr.   r/   r0   r1   r   _parse_token_responser   r!   r4   rH   )r   r5   r6   r)   r?   s        r   refresh_access_tokenrT      s    M=%%!!",/7!.&BB 55 & 

 !*D&--HHWE

*5+HH4H4H*ITXXVikmMnLop  ?? M @DE1LMs   AB4 4CCCr5   c                     	 | j                         S # t        $ r?}t        dt        j                   d| j
                   d| j                  d d        |d }~ww xY w)NzFailed to parse response from z/oauth/token (status z): r>   )r2   rI   r   r   r-   rH   text)r5   r6   s     r   rS   rS      sm    }} ,Y-?-?,@ A++,Cds0C/DF
 	s    	A:AA)__doc__rE   collections.abcr   typingr   r   r0   rD   r   errorsr   r	   _httpr   r   rG   rR   r   r!   r8   rP   r   rT   ResponsedictrS   r   r   r   <module>r^      s   	  $ "   4 3 I + Y % &^ &: MQDwDw08T0BT0IDwDwN   0B  FENN t r   