
    -:jO                        U d Z ddlZddlZddlZddlZddl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mZmZ d	d
lmZ d	dlmZ d	dlmZmZ dZdZdededdfdZda e
       Zda edz  e!d<    ejD                  e#      Z$dedz  fdZ%dedz  fdZ&dedz  fdZ'dedz  fdZ( G d de      Z) e
       Z*da+e)dz  e!d<   dZ,dedz  fdZ- G d de      Z. e
       Z/da0e.dz  e!d <   d!Z1dZ2da3dedz  fd"Z4d#edefd$Z5d%eddfd&Z6d'e7eef   de8dz  fd(Z9de7eef   fd)Z:de7ee7eef   f   fd*Z;d+e7ee7eef   f   ddfd,Z<d-ededz  fd.Z=ddd/d#ed-ed0edz  d1e8dz  ddf
d2Z>d#edz  dedz  fd3Z?y)4zVContains a helper to get the token from machine (env variable, secret or config file).    N)Path)Lock)	TypedDict   )	constants)DeviceCodeErrorOAuthErrorCode	OIDCError   )WeakFileLock)refresh_access_token)is_colab_enterpriseis_google_colabi  i  pathcontentreturnc                    | j                   j                  ddt               t        j                  t        |       t        j                  t        j                  z  t        j                  z  t              }t        j                  |d      5 }|j                  |       ddd       	 | j                  t               | j                   j                  t               y# 1 sw Y   ?xY w# t        t        f$ r Y yw xY w)ziWrite content to file, restricting both the file and its parent directory to owner-only on POSIX systems.T)parentsexist_okmodewN)parentmkdir_SECRET_DIR_MODEosopenstrO_WRONLYO_CREATO_TRUNC_SECRET_FILE_MODEfdopenwritechmodOSErrorNotImplementedError)r   r   fdfs       ]/var/www/html/tokenscope/api/venv/lib/python3.12/site-packages/huggingface_hub/utils/_auth.py_write_secretr*   %   s    KKdT8HI	TBKK"**4rzzACT	UB	2s	 q	

$%*+	 
 () s   C(4C) C&)C;:C;F_GOOGLE_COLAB_SECRETc                  ^    t               xs" t               xs t               xs
 t               S )a]  
    Get token if user is logged in.

    Note: in most cases, you should use [`huggingface_hub.utils.build_hf_headers`] instead. This method is only useful
          if you want to retrieve the token for other purposes than sending an HTTP request.

    If `HF_OIDC_RESOURCE` is set (Trusted Publishers, typically in CI), a short-lived token obtained via OIDC token
    exchange takes precedence. Otherwise the token is retrieved from the `HF_TOKEN` environment variable, then from the
    token file in the Hugging Face home folder. Returns None if user is not logged in. To log in, use [`login`] or
    `hf auth login`.

    OAuth tokens obtained with the browser-based login come with a refresh token: when such a token is close to
    expiry, it is transparently refreshed and persisted before being returned.

    Note: if `HF_OIDC_RESOURCE` is set but the OIDC token exchange fails, this raises instead of returning `None`,
    opting into OIDC is explicit, so a failure surfaces as a clear error rather than a silent fallback.

    Returns:
        `str` or `None`: The token, `None` if it doesn't exist.
    )_get_token_from_oidc_get_token_from_environment_get_token_from_file_refreshed_get_token_from_google_colab     r)   	get_tokenr3   :   s2    , 	 	*&(	*)+	* ()	r2   c                  (   t               r
t               ryt        5  t        rt        cddd       S 	 ddlm}  ddlm} 	 | j                  d      }t        |      ad
at        cddd       S # t        $ r Y ddd       yw xY w# | j                  $ r t        j                  d       daY P| j                  $ r t         j#                  d       daY w|$ r.}t        j                  dt%        |       d	       daY d}~d}~ww xY w# 1 sw Y   yxY w)zGet token from Google Colab secrets vault using `google.colab.userdata.get(...)`.

    Token is read from the vault only once per session and then stored in a global variable to avoid re-requesting
    access to the vault.
    Nr   )userdata)ErrorHF_TOKENz
Access to the secret `HF_TOKEN` has not been granted on this notebook.
You will not be requested again.
Please restart the session if you want to be prompted again.zThe secret `HF_TOKEN` does not exist in your Colab secrets. Run `huggingface_hub.login()` to authenticate (recommended but still optional to access public models or datasets).z@
Error while fetching `HF_TOKEN` secret value from your vault: 'z'.
You are not authenticated with the Hugging Face Hub in this notebook.
If the error persists, please let us know by opening an issue on GitHub (https://github.com/huggingface/huggingface_hub/issues/new).T)r   r   _GOOGLE_COLAB_SECRET_LOCK_IS_GOOGLE_COLAB_CHECKEDr+   google.colabr5   google.colab.errorsr6   ImportErrorget_clean_tokenNotebookAccessErrorwarningswarnSecretNotFoundErrorloggerinfor   )r5   
ColabErrortokenes       r)   r0   r0   W   s-     3 5 
# -$ $'-$ -$	-?	(LL,E#/#6 : $( #[-$ -$  	-$ -$	 ++ 	( MMQ
 $( ++ 	( KKf $(  	(MMSTWXYTZS[ \O O $( 	(E-$ -$sj   DA- BD-	B6D BD&D*D,%DDD$D ;D DDDc                      t        t        j                  j                  d      xs t        j                  j                  d            S )Nr7   HUGGING_FACE_HUB_TOKEN)r>   r   environr=   r1   r2   r)   r.   r.      s-    

z2^bjjnnE]6^__r2   c                      	 t        t        t        j                        j	                               S # t
        $ r Y y w xY w)N)r>   r   r   HF_TOKEN_PATH	read_textFileNotFoundErrorr1   r2   r)   _get_token_from_filerO      s8    D!8!89CCEFF s   /2 	>>c                   ,    e Zd ZU eed<   eed<   eed<   y)_OidcTokenCacheresourcerF   
expires_atN__name__
__module____qualname__r   __annotations__floatr1   r2   r)   rQ   rQ      s    MJr2   rQ   _OIDC_TOKEN_CACHEi,  c                     t         j                  j                  d      } | syddlm}m} t        5  t        j                         }t        *t        d   | k(  r|t        d   k  rt        d   cddd       S t         j                  j                  d      xs d}| |       t        d	       || |
      }|d   }t        |j                  dd            }|dnt        }| ||t        ||z
  d      z   da	|cddd       S # 1 sw Y   yxY w)a  Get a short-lived OIDC token in CI (Trusted Publishers).

    Enabled by setting `HF_OIDC_RESOURCE`, which scopes the token to a repo or user.
    The ID token is read from `HF_OIDC_ID_TOKEN` if available, or minted from a supported CI provider (e.g. GitHub Actions).

    Returns `None` when OIDC is not enabled.
    If enabled, any failure is raised explicitly rather than falling back silently.

    See `huggingface_hub._oidc` and https://huggingface.co/docs/hub/trusted-publishers.
    HF_OIDC_RESOURCENr   )detect_provider
oidc_loginrR   rS   rF   HF_OIDC_ID_TOKENzHF_OIDC_RESOURCE is set but no OIDC id token is available: not running in a supported CI provider (github) and HF_OIDC_ID_TOKEN is not set. Set HF_OIDC_ID_TOKEN to the id token minted by your CI provider, or unset HF_OIDC_RESOURCE.)rR   subject_tokenaccess_token
expires_ini  r   )rR   rF   rS   )r   rJ   r=   _oidcr]   r^   _OIDC_TOKEN_LOCKtime	monotonicrZ   r
   int_OIDC_REFRESH_MARGINmax)	rR   r]   r^   nowr`   resultrF   rb   margins	            r)   r-   r-      s    zz~~01H3 
 nn)!*-9'55$W-  

'9:Bd _%6%>O  X]K~&L$78
 $/5I J$7 ;;

 =  s   ;D6BDDc                   ,    e Zd ZU eed<   eed<   eed<   y)_OAuthRefreshCache
file_tokenresolved_token
recheck_atNrT   r1   r2   r)   rn   rn      s    Or2   rn   _OAUTH_REFRESH_CACHEiQ c                  2    t               } | yt        |       S )zSGet the token from `HF_TOKEN_PATH`, transparently refreshing it if close to expiry.N)rO   _refresh_oauth_token_if_neededrF   s    r)   r/   r/      s     "E})%00r2   rF   c           	          t         5  t        j                         }t        }||d    k(  r||d   k  r|d   cddd       S t         fdt	               j                         D        di f      \  }}|j                  d      }t        |      }|||4t               }|| k7  r|cddd       S   |t        z   da cddd       S |t        z
  |kD  r  |t        z
  da cddd       S 	 t        t        j                  dz   d	
      5  t	               j                  |i       }|j                  d       k7  r!|j                  d      xs  }t        |      }	nt        |      }
|
d   }d|
v rt        |      t        |
d         z   nd}	t!        |||
j                  d      xs ||	       t                k(  r#t#        t%        t        j&                        |       t(        j+                  d| d       ddd       |t?        |t        z   	r	|	t        z
  nd      da|cddd       S # 1 sw Y   6xY w# t,        $ r}t/        |t0              rB|j2                  t4        j6                  k(  r%t(        j9                  d| d       t;        d      }nt=        d| d       |t        z   }  |da cY d}~cddd       S d}~ww xY w# 1 sw Y   yxY w)a  Refresh an OAuth access token if it is close to expiry. Best-effort: never raises.

    OAuth tokens obtained with the browser-based login are stored with a `refresh_token` and an
    `expires_at` timestamp (see `_save_token`). When the active token is one of them and about to
    expire, exchange the refresh token for a new access token and persist it. Any other token is
    returned unchanged.
    Nro   rq   rp   c              3   V   K   | ]   \  }}|j                  d       k(  s||f " yw)hf_tokenN)r=   ).0namefieldsrF   s      r)   	<genexpr>z1_refresh_oauth_token_if_needed.<locals>.<genexpr>	  s.     vfV\V`V`akVlpuVudF^vs   )	)refresh_token)ro   rp   rq   z.lock   )timeoutrx   ra   rb   )rF   
token_namer}   rS   zAccess token `z` has been refreshed.zYour Hugging Face access token has expired and could not be refreshed (session expired or revoked). Run `hf auth login` to re-authenticate. ()infz2Could not refresh your Hugging Face access token: z. Will retry later.r   ) _OAUTH_REFRESH_LOCKre   rr   next_read_stored_tokens_fullitemsr=   _parse_expires_atrO   _OAUTH_RECHECK_INTERVAL_OAUTH_REFRESH_MARGINr   r   HF_STORED_TOKENS_PATHr   rg   _save_tokenr*   r   rL   rC   rD   	Exception
isinstancer   
error_coder	   INVALID_GRANTwarningrY   _warn_refresh_failure_onceri   )rF   rj   cacher   r{   r}   rS   current_file_token	new_tokennew_expires_atresponserG   rq   s   `            r)   rt   rt      s-    
 Wiik$|!4!=#lH[B[)*	W W "v0H0J0P0P0Rv2J

F 

?3&v.
!6*:L "6!7!-2D2M)#W W( $"'!$;;$ 
 1W W4 --3#"'(+@@$ 
 AW WD)	 i==GQST T1377
BG::j)U2 &

: 6 ?%I%6v%>N3MBH ( 8IO[_gOgSXH\4J0K%KmqN'#-&.ll?&C&T}#1 ,-6%d9+B+B&CYOKK.<Q RS+TR $' --:H!66a	 
 oW WJT T,  	!_-!,,.B^B^2^ ^^_]``ac #5\
 +-_`a_bbu+vw #::
275`j#k LWW Wv	wW Wsh   1K	A$K	1K		K	.H8C+H,7H8?#K	,H5	1H88	KA1K2K3K	KK		Kmessagec                 @    t         st        j                  |        da y y )NT)_OAUTH_REFRESH_WARNEDrC   r   )r   s    r)   r   r   \  s     w $ !r2   r{   c                 J    	 t        | d         S # t        t        f$ r Y yw xY w)zVParse the `expires_at` field of a stored-tokens section, `None` if missing or corrupt.rS   N)rg   KeyError
ValueError)r{   s    r)   r   r   c  s.    6,'((j! s    ""c            	          t               j                         D  ci c]  \  } }| |j                  dd       c}} S c c}} w )aA  
    Returns the parsed INI file containing the access tokens.
    The file is located at `HF_STORED_TOKENS_PATH`, defaulting to `~/.cache/huggingface/stored_tokens`.
    If the file does not exist, an empty dictionary is returned.

    Returns: `dict[str, str]`
        Key is the token name and value is the token.
    rx    )r   r   r=   )r   r{   s     r)   get_stored_tokensr   k  s;     NfMgMmMmMop7Iz6J

:r22ppps   =c            	         t        t        j                        } | j                         si S t	        j
                  d      }	 |j                  |        |j                         D ci c]  }|t        |j                  |             c}S c c}w # t        j                  $ r$}t        j                  d|        i cY d}~S d}~ww xY w)zRead all sections of the stored tokens INI file, with all their fields.

    Beside `hf_token`, sections for OAuth tokens also carry `refresh_token` and `expires_at`
    (unix timestamp), used by [`get_token`] to transparently refresh them.
    Ninterpolationz"Error parsing stored tokens file: )r   r   r   existsconfigparserConfigParserreadsectionsdictr   r6   rC   error)tokens_pathconfigr   rG   s       r)   r   r   w  s     y667K	&&T:FK MS__M^_z
Dj!9::___ 9!=>	s0   #B &"BB B C#C<CCstored_tokensc                    t        j                  d      }t        | j                               D ]A  }|j	                  |       | |   j                         D ]  \  }}|j                  |||        C t        j                         }|j                  |       t        t        t        j                        |j                                y)zBWrite all sections and their fields to the stored tokens INI file.Nr   )r   r   sortedkeysadd_sectionr   setioStringIOr#   r*   r   r   r   getvalue)r   r   r   keyvaluebufs         r)   _save_stored_tokens_fullr     s    &&T:F]//12 /
:&'
399; 	/JCJJz3.	//
 ++-C
LL$y667Hr2   r   c                 <    t               }| |vryt        ||          S )z
    Get the token by name.

    Args:
        token_name (`str`):
            The name of the token to get.

    Returns:
        `str` or `None`: The token, `None` if it doesn't exist.

    N)r   r>   )r   r   s     r)   _get_token_by_namer     s'     &'M&j122r2   )r}   rS   r}   rS   c                    t               }d| i}|||d<   |t        |      |d<   |||<   t        |       t        j	                  d| dt
        j                          y)a  
    Save the given token.

    If the stored tokens file does not exist, it will be created.
    Args:
        token (`str`):
            The token to save.
        token_name (`str`):
            The name of the token.
        refresh_token (`str`, *optional*):
            OAuth refresh token used to renew the access token when it expires.
        expires_at (`int`, *optional*):
            Unix timestamp at which the access token expires.
    rx   Nr}   rS   zThe token `z` has been saved to )r   r   r   rC   rD   r   r   )rF   r   r}   rS   r   r{   s         r)   r   r     sm    " -.M% F "/":| &M*]+
KK+j\)=i>]>]=^_`r2   c                 p    | y| j                  dd      j                  dd      j                         xs dS )zuClean token by removing trailing and leading spaces and newlines.

    If token is an empty string, return None.
    Nr   
)replacestripru   s    r)   r>   r>     s8    
 }==r"**44::<DDr2   )@__doc__r   r   loggingr   re   r@   pathlibr   	threadingr   typingr   r   r   errorsr   r	   r
   _fixesr   _oauth_devicer   _runtimer   r   r!   r   r   r*   r9   r8   r+   rX   	getLoggerrU   rC   r3   r0   r.   rO   rQ   rd   rZ   rh   r-   rn   r   rr   r   r   r   r/   rt   r   r   rg   r   r   r   r   r   r   r>   r1   r2   r)   <module>r      s{   ]  	  	       ? ?   / :    s t  !  F #' cDj '			8	$3: :<$cDj <$~`S4Z `
cDj i  6 ,0 ?T) 0 0cDj 0f  f 26 (4/ 6!   1d
 1`# `# `F% % %d38n t 	q4S> 	q$sDcN':"; &
IDd38n1D,E 
I$ 
I33 33: 3& AE_caaa36:aRUX\R\a	a:Ed
 EsTz Er2   