o
    î6WjÁ(  ã                   @  s"  d dl mZ d dlZd dlZd dlZd dlmZ ddlmZ dZ	dZ
dZd	Zd
ZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdGdd„ZdHd!d"„Z dId$d%„Z!dGd&d'„Z"dJd+d,„Z#d-d.œdKd1d2„Z$dLd5d6„Z%dMd7d8„Z&dMd9d:„Z'dNd<d=„Z(dNd>d?„Z)dOdPdCdD„Z*dNdEdF„Z+dS )Qé    )ÚannotationsN)ÚOptionalé   )ÚAnthropicErrorz+urn:ietf:params:oauth:grant-type:jwt-bearerÚrefresh_tokenz/v1/oauth/tokeng      >@zoauth-2025-04-20zoidc-federation-2026-04-01éx   é   Údefaultzhttps://api.anthropic.comÚANTHROPIC_API_KEYÚANTHROPIC_AUTH_TOKENÚANTHROPIC_CONFIG_DIRÚANTHROPIC_PROFILEÚANTHROPIC_IDENTITY_TOKENÚANTHROPIC_IDENTITY_TOKEN_FILEÚANTHROPIC_FEDERATION_RULE_IDÚANTHROPIC_ORGANIZATION_IDÚANTHROPIC_SERVICE_ACCOUNT_IDÚANTHROPIC_WORKSPACE_IDÚANTHROPIC_SCOPEÚANTHROPIC_BASE_URLÚreturnÚstrc                  C  s   ddl m}  d| › �S )zÌ``User-Agent`` value sent on token-endpoint POSTs.

    Computed lazily so this module doesn't need to import ``_version`` at
    module load time (the credentials package is otherwise import-light).
    r   ©Ú__version__zanthropic-python/)Ú_versionr   r   © r   ús/home/esfera/Documents/content_generation/venv/lib/python3.10/site-packages/anthropic/lib/credentials/_constants.pyÚ_user_agent8   s   
r   úpathlib.Pathc                  C  sj   t j t¡} | rt | ¡S tjdkr,t j d¡}|rt |¡ntj ¡ d d }|d S tj ¡ d d S )uY  Resolve the config directory.

    ``ANTHROPIC_CONFIG_DIR`` env var â†’ platform default.

    Platform defaults:
      * Linux & macOS: ``~/.config/anthropic/`` â€” XDG-style on both platforms
        for consistency across SDKs (macOS does **not** use
        ``~/Library/Application Support/``).
      * Windows: ``%APPDATA%\Anthropic\``
    Úwin32ÚAPPDATAÚAppDataÚRoamingÚ	Anthropicz.configÚ	anthropic)	ÚosÚenvironÚgetÚENV_CONFIG_DIRÚpathlibÚPathÚsysÚplatformÚhome)ÚenvÚappdataÚbaser   r   r   Ú_config_dirC   s   

 r1   úOptional[str]c                  C  s8   zt ƒ d jdd� ¡ } W n
 ty   Y dS w | pdS )zxReturn the stripped contents of ``<config_dir>/active_config``, or ``None``
    if the pointer file is missing or empty.Úactive_configzutf-8)ÚencodingN)r1   Ú	read_textÚstripÚOSError)Únamer   r   r   Ú_read_active_config_pointerX   s   ÿr9   c                  C  sB   t j t¡} | rt| td� | S tƒ }|du rtS t|dd� |S )uò   Resolve the active profile name.

    ``ANTHROPIC_PROFILE`` env var â†’ ``<config_dir>/active_config`` pointer file
    â†’ ``"default"`` literal. The resolved name is validated against path-
    traversal patterns before being returned.
    ©ÚsourceNzactive_config pointer file)r%   r&   r'   ÚENV_PROFILEÚ_validate_profile_namer9   ÚDEFAULT_PROFILE)r.   r8   r   r   r   Ú_active_profileb   s   r?   ÚurlÚfieldÚNonec                C  s>   |   ¡  d¡}| d¡rdS | d¡rdS t|› d| ›d�ƒ‚)a;  Reject non-``https://`` token-endpoint URLs.

    Localhost is allowed for testing so ``base_url="http://localhost:8080"``
    works against a local ``oauth_server`` instance; everything else must be
    TLS-encrypted because the body of these POSTs carries the assertion JWT
    or a long-lived refresh token.
    ú/zhttps://N)zhttp://localhostzhttp://127.0.0.1zhttp://[::1]z must use https (got z^); the token-exchange endpoint carries secret material and cannot be used over cleartext HTTP.)ÚlowerÚrstripÚ
startswithr   )r@   rA   Úloweredr   r   r   Ú_require_httpst   s   

ÿrH   zprofile namer:   Úprofiler;   c                C  s¨   | s	t |› d�ƒ‚| |  ¡ krt |› d| ›d�ƒ‚|  d¡r(t |› d| ›d�ƒ‚ddtjfD ]}|rC|| v rCt |› d| ›d|›d�ƒ‚q.d	| v rRt |› d| ›d
�ƒ‚dS )aÝ  Reject profile names that could escape the config directory.

    Profile names come from user-controlled sources (``ANTHROPIC_PROFILE``,
    the ``active_config`` pointer file, ``CredentialsFile(profile=...)``) and
    are interpolated into filesystem paths. A value like ``"../../etc/shadow"``
    would otherwise let a read of ``configs/<profile>.json`` escape the config
    root entirely. Pass ``source=`` so the error message names where the bad
    value came from.
    z must not be empty.ú z$ has leading or trailing whitespace.Ú.z must not start with a dot.rC   ú\um    must not contain path separators â€” profiles are filenames under the config directory. Pick a name without ú z must not contain null bytes.N)r   r6   rF   r%   Úsep)rI   r;   rN   r   r   r   r=   ‡   s"   

ÿÿ€ÿr=   r0   Ú	candidatec              
   C  sZ   | j dd�}|j dd�}z| |¡ W |S  ty, } ztd|› d|› d�ƒ|‚d}~ww )u®  Assert ``candidate`` resolves to a descendant of ``base``, return it verbatim.

    The containment check uses ``resolve(strict=False)`` on both sides so
    symlinks and ``..`` segments are normalized for the purposes of escape
    detection. The returned path is the *original* (unresolved) candidate â€”
    callers that care about symlink following must handle it themselves
    (e.g. ``os.stat(follow_symlinks=False)``).
    F)ÚstrictzResolved path z escapes config directory rK   N)ÚresolveÚrelative_toÚ
ValueErrorr   )r0   rO   Úbase_resolvedÚcandidate_resolvedÚerrr   r   r   Ú_resolve_under¡   s   	þ€ÿrW   c                 C  ó&   t | ƒ tƒ }t||d | › d� ƒS )zCPath to ``<config_dir>/configs/<profile>.json`` (non-secret, 0644).Úconfigsú.json©r=   r1   rW   ©rI   r0   r   r   r   Ú_config_file_path³   ó   r]   c                 C  rX   )zCPath to ``<config_dir>/credentials/<profile>.json`` (secret, 0600).ÚcredentialsrZ   r[   r\   r   r   r   Ú_credentials_file_pathº   r^   r`   Úboolc                	   C  s*   zt tƒ ƒ ¡ W S  ttfy   Y dS w )a   Tighter auto-discover check for the tier-1 credential chain.

    Returns ``True`` only if the *active* profile's config file exists. The
    previous version returned ``True`` for any ``.json`` under ``configs/``,
    which meant a stray ``configs/work.json`` on disk was enough to steer
    ``default_credentials()`` into reading ``configs/default.json`` and
    failing because ``default.json`` wasn't there.
    F)r]   r?   Úis_filer7   r   r   r   r   r   Ú_has_active_profile_configÁ   s
   	ÿrc   c                   C  s
   t ƒ duS )u‘  True if the user wrote a non-empty ``active_config`` pointer file.

    This is an explicit opt-in signal equivalent to setting ``ANTHROPIC_PROFILE``:
    the user has told us which profile to load. If the target config file is
    missing or malformed, the chain should surface that error rather than
    silently falling through â€” matching how ``ANTHROPIC_PROFILE=missing``
    behaves today.
    N)r9   r   r   r   r   Ú_has_explicit_active_configÐ   s   
	rd   Úpathústr | os.PathLike[str] | Noneúpathlib.Path | Nonec                 C  s0   | dur	t  | ¡S tj t¡}|rt  |¡S dS )u<   ctor arg â†’ ``ANTHROPIC_IDENTITY_TOKEN_FILE`` â†’ ``None``.N)r)   r*   r%   r&   r'   ÚENV_IDENTITY_TOKEN_FILE)re   r.   r   r   r   Úresolve_identity_token_pathÜ   s   

ri   c                   C  s^   t j t¡st j t¡rdS tƒ rdS t j t¡r-t j t¡r-t j t¡s+t j t	¡r-dS dS )uÒ  True if the environment / filesystem contains signals that would
    normally drive the tier-1 (profile) or tier-2 (env federation) paths of
    :func:`default_credentials`.

    Used by the shadow-warning detection in the client constructor: if a
    static ``ANTHROPIC_API_KEY`` / ``ANTHROPIC_AUTH_TOKEN`` is set alongside
    any of these signals, the auto-discovery would have yielded a credential
    but got silently shadowed â€” and the user should know.
    TF)
r%   r&   r'   r<   r(   rd   ÚENV_FEDERATION_RULE_IDÚENV_ORGANIZATION_IDrh   ÚENV_IDENTITY_TOKENr   r   r   r   Ú"_has_auto_discoverable_credentialsæ   s   
rm   )r   r   )r   r   )r   r2   )r@   r   rA   r   r   rB   )rI   r   r;   r   r   rB   )r0   r   rO   r   r   r   )rI   r   r   r   )r   ra   )N)re   rf   r   rg   ),Ú
__future__r   r%   r+   r)   Útypingr   Ú_exceptionsr   ÚGRANT_TYPE_JWT_BEARERÚGRANT_TYPE_REFRESH_TOKENÚTOKEN_ENDPOINTÚTOKEN_EXCHANGE_TIMEOUTÚOAUTH_API_BETA_HEADERÚFEDERATION_BETA_HEADERÚADVISORY_REFRESH_SECONDSÚMANDATORY_REFRESH_SECONDSr>   ÚDEFAULT_BASE_URLÚENV_API_KEYÚENV_AUTH_TOKENr(   r<   rl   rh   rj   rk   ÚENV_SERVICE_ACCOUNT_IDÚENV_WORKSPACE_IDÚ	ENV_SCOPEÚENV_BASE_URLr   r1   r9   r?   rH   r=   rW   r]   r`   rc   rd   ri   rm   r   r   r   r   Ú<module>   sR    











