
    ¦i+j                        U 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mZmZmZmZmZ d dlmZmZ d dlmZ d dlmZmZ d	efd
Zi d ed          d ed          d ed          d ed          d ed          d ed          d ed          d ed          d ed          d ed          d ed           d! ed"          d# ed$          d% ed&          d' ed(          d) ed*          d+ ed,           ed-           ed.          d/Zeeef         ed0<    G d1 d2          Zi dd3dd3dd3dd3d4d3dd3dd3dd3dd3d!d3d#d3d%d3d'd3d)d3d+d3d5d3d6d3d7d3iZdS )8    N)Callable)deepcopy)Path)DictListUnionAnyTupleOptional)	async_apisync_api)CaseInsensitiveDict)AsyncWrappingContextManagerSyncWrappingContextManagerreturnc                 d    t          t                    j        dz  | z                                  S )Njs)r   __file__parent	read_text)names    U/root/projects/butler/venv/lib/python3.11/site-packages/playwright_stealth/stealth.py	from_filer      s'    NN!D(4/::<<<    generate_magic_arrayszgenerate.magic.arrays.jsutilszutils.js
chrome_appzevasions/chrome.app.js
chrome_csizevasions/chrome.csi.jschrome_hairlinezevasions/chrome.hairline.jschrome_load_timeszevasions/chrome.load.times.jschrome_runtimezevasions/chrome.runtime.jsiframe_content_windowz evasions/iframe.contentWindow.jsmedia_codecszevasions/media.codecs.jsnavigator_hardware_concurrencyz)evasions/navigator.hardwareConcurrency.jsnavigator_languageszevasions/navigator.languages.jsnavigator_permissionsz!evasions/navigator.permissions.jsnavigator_platformzevasions/navigator.platform.jsnavigator_pluginszevasions/navigator.plugins.jsnavigator_user_agentzevasions/navigator.userAgent.jsnavigator_vendorzevasions/navigator.vendor.jsnavigator_webdriverzevasions/navigator.webdriver.jszevasions/error.prototype.jszevasions/webgl.vendor.js)error_prototypewebgl_vendorSCRIPTSc            7       &   e Zd ZdZdZdZdZddddddddddddddddddddd	d	d	d	d	ddd
dededededededededededededededededededee	e	f         de	de
e	         d e	d!e
e	         d"e	d#e	d$ed%ef6d&Zed'e	fd(            Zed'e	fd)            Zed*             Zed'e	fd+            Zd,ed'efd-Zd.ej        d'efd/Zd.ej        d'efd0Zd1eej        ej        f         d'd	fd2Zd1eej        ej        f         d'd	fd3Zd.eej        ej        f         d'd	fd4Z d5e!d6e"e	ef         d7ed'e"e	ef         fd8Z#d5e!d7efd9Z$d:e!d;e!d'e!fd<Z%d;e!d=ed'e!fd>Z&d?e!d6e"e	ef         d'e"e	ef         fd@Z'd?e!d6e"e	ef         d'e"e	ef         fdAZ(dBeej)        ej)        f         d'd	fdCZ*e+dDe	d'e
e	         fdE            Z,e+dFe
e-e	                  d'e-e	         fdG            Z.e+dFe-e	         dHe	d'e-e	         fdI            Z/e+d6e"e	ef         d'd	fdJ            Z0d	S )KStealtha  
    Playwright stealth configuration that applies stealth strategies to Playwright.
    The stealth strategies are contained in ./js package and are basic javascript scripts that are executed
    on every page.goto() called.
    Note:
        All init scripts are combined by playwright into one script and then executed this means
        the scripts should not have conflicting constants/variables etc. !
        This also means scripts can be extended by overriding enabled_scripts generator:
        ```
        @property
        def enabled_scripts():
            yield 'console.log("first script")'
            yield from super().enabled_scripts()
            yield 'console.log("last script")'
        ```
    _stealth_user_agent_stealth_sec_ch_ua_playwright_stealth_appliedTFzen-USenWin32N)r   r   r    r!   hairliner"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   	sec_ch_uar-   navigator_languages_overridenavigator_platform_overridenavigator_user_agent_overridenavigator_vendor_overridesec_ch_ua_overridewebgl_renderer_overridewebgl_vendor_overrideinit_scripts_onlyscript_loggingr   r   r    r!   r7   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r8   r-   r9   r:   r;   r<   r=   r>   r?   r@   rA   c                $   || _         || _        || _        || _        || _        || _        || _        || _        |	| _        |
| _	        || _
        || _        || _        || _        || _        || _        || _        || _        |                     t'                                 |pd| _        || _        || _        |pd | _        |'| j         |                     | j                  | _        n|| _        |pd| _        |pd| _        || _        || _        d S )Nr4   zIntel Iris OpenGL Enginez
Intel Inc.)r   r   r    r!   r7   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r8   r-   &_check_for_disabled_options_overriddenlocalsr9   r:   r;   r<   _get_greased_chrome_sec_ua_chr=   r>   r?   r@   rA   )selfr   r   r    r!   r7   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r8   r-   r9   r:   r;   r<   r=   r>   r?   r@   rA   s                               r   __init__zStealth.__init__E   s9   @ !+ *'8$2&+@"".3Q+)< +@"(:'8*>!&6)< %4(". 	33FHH====Y=l]l):U(<Y*.G.O4&%$*L*X&*&H&HIk&l&lD##5GD#,C,aGa$*?*O<"'8,r   r   c                 p    d                     | j                  }t          |          dk    rdS d|z   dz   S )z
        Generates an immediately invoked function expression for all enabled scripts
        Returns: string of enabled scripts in IIFE
        
r    z	(() => {
z
})();)joinenabled_scriptslen)rF   scripts_blocks     r   script_payloadzStealth.script_payload   s@     		$"677}""2m+i77r   c           	          | j         | j        | j        | j        | j        | j        | j        | j        d}dt          j	        |           dS )N)r$   r9   r'   r)   r*   webgl_rendererr-   rA   zconst opts = ;)
r$   r9   r:   r;   r<   r>   r?   rA   jsondumps)rF   optss     r   options_payloadzStealth.options_payload   s]     /3.Q,0,M"&"B$($F $ >": 6"1	
 	
 3tz$//2222r   c              #      K   d                     | j                  }t          |          dk    rdS | j        V  t          d         V  t          d         V  |V  d S )NrI   r   rJ   r   r   )rK   _evasion_scriptsrM   rV   r.   )rF   evasion_script_blocks     r   rL   zStealth.enabled_scripts   sx      #yy)>??#$$))2""""g-....""""""r   c              #     K   | j         rt          d         V  | j        rt          d         V  | j        rt          d         V  | j        rt          d         V  | j        rt          d         V  | j        rt          d         V  | j        rt          d         V  | j        rt          d         V  | j	        rt          d	         V  | j
        rt          d
         V  | j        rt          d         V  | j        rt          d         V  | j        rt          d         V  | j        rt          d         V  | j        rt          d         V  | j        rt          d         V  d S d S )Nr   r   r   r    r!   r"   r#   r%   r&   r'   r(   r)   r*   r+   r,   r-   )r   r.   r   r7   r    r!   r"   r#   r%   r&   r'   r(   r)   r*   r+   r,   r-   )rF   s    r   rX   zStealth._evasion_scripts   s     ? 	(,''''? 	(,''''= 	-+,,,,! 	/-.... 	,*++++% 	312222 	*.))))# 	1/0000% 	312222" 	0.////! 	/-....$ 	201111  	.,----# 	1/0000 	-+,,,, 	*.))))))	* 	*r   objc                 \    t          || j                  rt          j        d           dS dS )NzYStealth has already been applied to this page or context. Skipping duplicate application.TF)hasattr_STEALTH_APPLIED_KEYwarningswarn)rF   r[   s     r   warn_if_stealth_appliedzStealth.warn_if_stealth_applied   s:    3122 	Mk   4ur   ctxc                 "    t          | |          S )a)  
        Instruments the playwright context manager.
        Any browser connected to or any page created with any method from
        the patched context should have stealth evasions applied automatically.

        async with Stealth().use_async(async_playwright()) as p:
            ...
        )r   rF   rb   s     r   	use_asynczStealth.use_async   s     +4555r   c                 "    t          | |          S )a!  
        Instruments the playwright context manager.
        Any browser connected to or any page created with any method from
        the patched context should have stealth evasions applied automatically.

        with Stealth().use_sync(sync_playwright()) as p:
            ...
        )r   rd   s     r   use_synczStealth.use_sync   s     *$444r   page_or_contextc                    K   t          | j                  dk    rM|                     |          s:|                    | j                   d {V  t	          || j        d           d S d S d S Nr   TrM   rO   ra   add_init_scriptsetattrr^   rF   rh   s     r   apply_stealth_asynczStealth.apply_stealth_async   s      t"##a''0L0L_0]0]'!11$2EFFFFFFFFFOT%>EEEEE ('''r   c                     t          | j                  dk    rG|                     |          s4|                    | j                   t	          || j        d           d S d S d S rj   rk   rn   s     r   apply_stealth_synczStealth.apply_stealth_sync   sk    t"##a''0L0L_0]0]'++D,?@@@OT%>EEEEE ('''r   c                 B   t           j        j        }|j        |j        |j        fD ]x}|j        dk    }t          j        |t          j	                  D ]J\  }}|j
                            d          |k    r'|                     ||          }t          |||           KydS )z
        Given a Playwright context object, hooks all the browser type object methods that return a Browser object.
        Can be used with sync and async methods contexts
        chromium)	predicater   N)r   Browser__name__rs   firefoxwebkitr   inspect
getmembersismethod__annotations__get,_generate_hooked_method_that_returns_browserrm   )rF   rb   browser_class_namebrowser_typechromium_moder   hooked_methods          r   hook_playwright_contextzStealth.hook_playwright_context   s    
 &-6 \3;
C 	? 	?L(-;M'.'9,RYRb'c'c'c ? ?#m 044X>>BTTT$($U$UVcer$s$sML$>>>	?	? 	?r   methodpacked_kwargsr   c                    t          j        |          j        }|                    d          }t	          |          }||r| j        sz|                    d|j                  }| j        r|                     |pg           }| j	        r5dd
                    | j                   }|                     |pg |          }||d<   |S )Nargsz--accept-lang=,)ry   	signature
parametersr}   r   r@   defaultr+   _patch_blink_features_cli_argsr%   rK   r9   _patch_cli_arg)	rF   r   r   r   r   args_parameter
new_kwargsnew_cli_argslanguages_cli_flags	            r   _kwargs_with_patched_cli_argz$Stealth._kwargs_with_patched_cli_arg  s     %f--8	"v.. m,,
% 2T%; 2)~~fn6LMM+ [#'#F#F|GYWY#Z#ZL+ _)g#((4Cd:e:e)g)g&#'#6#6|7IrK]#^#^L%1
6"r   c                      dt           j        f fd}dt          j        f fd}t          j                  r|S |S )Nr   c            	      |   K    | i                      |           d {V }                    |           |S Nr   _reassign_new_page_new_contextr   kwargsbrowserr   r   rF   s      r   async_hooked_methodzQStealth._generate_hooked_method_that_returns_browser.<locals>.async_hooked_method  sn      "F33FFMRR       G //888Nr   c            	      l     | i                      |          }                    |           |S r   r   r   s      r   sync_hooked_methodzPStealth._generate_hooked_method_that_returns_browser.<locals>.sync_hooked_method#  sL    f33FFMRR G //888Nr   )r   ru   r   ry   iscoroutinefunction)rF   r   r   r   r   s   ```  r   r~   z4Stealth._generate_hooked_method_that_returns_browser  s    	):K 	 	 	 	 	 	 	 		83C 	 	 	 	 	 	 	 	 &v.. 	'&&!!r   new_context_methodnew_page_methodc                 T      fd} fd}t          j                  r|S |S )Nc                     K    | i                      |           d {V  d {V }                    |           d {V  |S r   +_kwargs_new_page_context_with_patches_asyncro   r   r   contextr   r   rF   s      r   hooked_new_context_asynczFStealth._generate_hooked_new_context.<locals>.hooked_new_context_async0  s      ..II/[abbbbbbbb       G **7333333333Nr   c                  j     | i                      |          }                    |           |S r   *_kwargs_new_page_context_with_patches_syncrq   r   s      r   hooked_browser_method_synczHStealth._generate_hooked_new_context.<locals>.hooked_browser_method_sync8  sL    ((BB?TZ[[ G ##G,,,Nr   ry   r   )rF   r   r   r   r   s   ```  r   _generate_hooked_new_contextz$Stealth._generate_hooked_new_context/  sm    	 	 	 	 	 	 		 	 	 	 	 	 	 &'9:: 	,++))r   patch_kwargsc                 T      fd} fd}t          j                  r|S |S )a  
        Returns a hooked method (async or sync) for new_page.
        *args and **kwargs even though these methods may not take any number of arguments,
        we want to preserve accurate stack traces when caller passes args improperly.

        If patch_kwargs is true, we patch kwargs the caller passes to enhance evasions. This only applies
        to Browser.new_page, so we pass false when passing in a BrowserContext.new_page method
        c                     K   r                     |           d {V n|} | i | d {V }                    |           d {V  |S r   r   r   r   pager   r   rF   s      r   hooked_new_page_asyncz@Stealth._generate_hooked_new_page.<locals>.hooked_new_page_asyncN  s        dFFX^_________ 
 )$9&99999999D**4000000000Kr   c                  v    r                     |          n|} | i |}                    |           |S r   r   r   s      r   hooked_new_page_syncz?Stealth._generate_hooked_new_page.<locals>.hooked_new_page_syncX  sV    \ht??QWXXXnt  #?D3F33D##D)))Kr   r   )rF   r   r   r   r   s   ```  r   _generate_hooked_new_pagez!Stealth._generate_hooked_new_pageD  sl    	 	 	 	 	 	 		 	 	 	 	 	 	 &77 	)((##r   unpatched_new_pagec                 6   K   j         }t          |t          j                  r|j        n|j        j        dk    }dt          t          t          f         f fd}t          |          } j
        r8|                    d          # j        }||r |             d{V \  }}||d<   |                    di           }	 j        rLt          |	                              d          * j        }
|
|r |             d{V \  }}
|

|
|	d<   |	|d<   |S )a  
        This returns kwargs with arguments added based on enabled evasions, while respecting any kwargs the caller
        has passed in. If enabled and overrides aren't set for either navigator_user_agent or sec_ch_ua,
        and we're dealing with a Chromium browser, we create a temporary page to get up-to-date UA information.

        This function is suitable for patching kwargs for new_context and new_page, though in either case, an unpatched
        new_page method must be provided.
        Args:
            unpatched_new_page: new_page
            packed_kwargs: kwargs the caller has passed in
        Returns:
            patched kwargs
        rs   r   c                    K   t          j        d           } t          j        d           }| |              d {V }|                    d           d {V                     dd          } |                    d           d {V                      |           }t          j        |           t          j        |            | |fS Nznavigator.userAgentHeadlessChromeChromez-playwright_stealth internal temp utility page)reason)getattr"_USER_AGENT_OVERRIDE_PIGGYBACK_KEY!_SEC_CH_UA_OVERRIDE_PIGGYBACK_KEYevaluatereplacecloserE   rm   stealth_user_agentr8   	temp_pagebrowser_instancerF   r   s      r   "get_user_agent_and_sec_ch_ua_asyncz_Stealth._kwargs_new_page_context_with_patches_async.<locals>.get_user_agent_and_sec_ch_ua_async{  s     !()94;bdh!i!i 0$2XZ^__I!)Y->"4"4"6"6666666	,5,>,>?T,U,U&U&U&U&U&U&U%^%^$h& &"  oo-\o]]]]]]]]] >>?QRR	($*PR[\\\$;&  
 &y00r   
user_agentNextra_http_headers	sec-ch-ua)__self__
isinstancer   BrowserContextr   r   r   r
   strr   r)   r}   r;   r8   r   r=   )rF   r   r   browser_or_contextis_chromiumr   r   resolved_user_agent_override_r   resolved_sec_ch_ua_overrider   s   ``         @r   r   z3Stealth._kwargs_new_page_context_with_patches_asyncd  s       08()*BCC 	2191&38JF	1%S/ 	1 	1 	1 	1 	1 	1 	1 	1& m,,
$ 	D):):<)H)H)P+/+M(+338Z8Z8\8\2\2\2\2\2\2\/,a'CJ|$*../CRHH> 	F12DEEII+VV^*.*A'*2{27Y7Y7[7[1[1[1[1[1[1[..*62M";/3E
/0r   c                     j         }t          |t          j                  r|j        n|j        j        dk    }dt          t          t          f         f fd}t          |          } j
        r2|                    d           j        }||r |            \  }}||d<   |                    di           }	 j        rFt          |	                              d          $ j        }
|
|r |            \  }}
|

|
|	d<   |	|d<   |S )z>see self._kwargs_new_page_context_with_patches_async for docs.rs   r   c                     t          j        d           } t          j        d           }| |             }|                    d                              dd          }                     |           }|                    d           t          j        |           t          j        |            | |fS r   )r   r   r   r   r   rE   r   rm   r   s      r   !get_user_agent_and_sec_ch_ua_syncz]Stealth._kwargs_new_page_context_with_patches_sync.<locals>.get_user_agent_and_sec_ch_ua_sync  s    !()94;bdh!i!i 0$2XZ^__I!)Y->..00	%.%7%78M%N%N%V%VWgiq%r%r" >>?QRR	'VWWW($*PR[\\\$;&  
 &y00r   r   Nr   r   )r   r   r   r   r   r   r   r
   r   r   r)   r}   r;   r8   r   r=   )rF   r   r   r   r   r   r   r   r   r   r   r   s   ``         @r   r   z2Stealth._kwargs_new_page_context_with_patches_sync  sh    08((*ABB 	2191&38JF	15c? 	1 	1 	1 	1 	1 	1 	1 	1" m,,
$ 	D):):<)H)H)P+/+M(+332S2S2U2U/,a'CJ|$*../CRHH> 	F12DEEII+VV^*.*A'*2{21R1R1T1T..*62M";/3E
/0r   r   c                    t          |t          j        t          j        f          rH|                     |j        |j                  |_        |                     |j        d          |_        d S t          d|           )NT)r   z.unexpected type from function (bug): returned )	r   r   ru   r   r   new_contextnew_pager   	TypeError)rF   r   s     r   r   z&Stealth._reassign_new_page_new_context  s{    g	 183CDEE 	X"&"C"CGDWY`Yi"j"jG#==g>N]a=bbGVWVVWWWr   r   c                    g d}d}dt          j        |           dt          j        |           d}t          j        d| t          j                  }t          |                                          dk    rdS |                    d	          }d
|fd|f|t          j        |          fg}t          j        |           d	                    d |D                       S )aD  
        From the major version in user_agent, generate a Sec-CH-UA header value. An example of the data in this
        header can be generated from navigator.userAgentData.brands (requires secure context). We could query that
        ourselves, but since it requires a secure context, there's no performant way to do that, so instead we
        re-implement the greasing algorithm from Chrome.

        See Also:
             https://wicg.github.io/ua-client-hints/#grease
             https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Sec-CH-UA
             https://source.chromium.org/chromium/chromium/src/+/main:components/embedder_support/user_agent_utils.cc
        Args:
            user_agent: Chrome UA

        Returns:
            greased Sec-CH-UA header value, None if the Chrome version cannot be parsed
        )   c      z ():-./;=?_NotABrandzChrome/(\d+)[\d.]+r   N   Chromiumr   z, c              3   .   K   | ]\  }}d | d| d V  dS )"z";v="N ).0brandversions      r   	<genexpr>z8Stealth._get_greased_chrome_sec_ua_ch.<locals>.<genexpr>  s:      QQw3U33333QQQQQQr   )
randomchoiceresearch
IGNORECASErM   groupsgroupshufflerK   )r   greased_versionsgreasy_charsgreasy_brandr   major_versionbrandss          r   rE   z%Stealth._get_greased_chrome_sec_ua_ch  s    $ ';;$]V]<88]]6=;V;V]]])1:r}MMw~~  A%%4a(('}%6=)9::;

 	vyyQQ&QQQQQQr   existing_argsc                    g }d}d}| pg D ]b}|                                 }|                    |          r"||vr|d| z  }|                    |           M|                    |           c|                    | |            |S )z`Patches CLI args list to disable AutomationControlled blink feature, while preserving other argsz--disable-blink-features=AutomationControlledr   )strip
startswithappend)r   new_argsdisable_blink_features_prefix"automation_controlled_feature_nameargstripped_args         r   r   z&Stealth._patch_blink_features_cli_args  s     (C%-C* &B 	d 	dC99;;L&&'DEE %5\II $L(J$L$LLL----$$$$ OO<b>`bbcccr   flagc                 h   g }t          j        d|                              d          }| D ]o}|                                }|                    |          r/t          j        d|d           |                    |            n+|                    |           p|                    |           |S )zZPatches CLI args list with any arg, warns if the user passed their own value in themselvesz(.*)=?r   zplaywright-stealth is trying to modify a flag you have set yourself already.Either disable the mitigation or don't specify this flag manually flag=zBto avoid this warning. playwright-stealth has overridden your flag)r   r   r   r   r   r_   r`   r   )r   r  r   switch_namer  r  s         r   r   zStealth._patch_cli_arg  s     i$//55a88  	" 	"C99;;L&&{33 	%ZY]Z Z Z  
 %%%$$$$ OOD!!!r   c                     t                                           D ]K}|                     |          s4|                     | d          t          j        | d| dd           Ld S )N	_overridez is False, but an override (zF_override) was provided, which is probably not what you intended to do   )
stacklevel)ALL_EVASIONS_DISABLED_KWARGSkeysr}   r_   r`   )r   keys     r   rC   z.Stealth._check_for_disabled_options_overridden  s    /4466 	 	C $$S)) m.?.?3@Q@Q@Q.R.R.^ E E E E E    	 	r   )1rv   
__module____qualname____doc__r   r   r^   boolr
   r   r   rG   propertyrO   rV   rL   rX   r	   ra   r   PlaywrightContextManagerr   re   r   r   rg   r   Pager   ro   rq   
Playwrightr   r   r   r   r~   r   r   r   r   ru   r   staticmethodrE   r   r   r   rC   r   r   r   r0   r0   /   s        " *?&(<%8
  $#&*#(!*.!%37(,*.'+&*)-%)(,$("!%<K/6;?-104+/)-&+#(;C- C- C- C- 	C-
  $C- !C- C- $(C- C- -1C- "&C- $(C- !%C-  $C- #'C-  #!C-" "&#C-$ "%C-& 'C-( )C-* +0S/+C-, *--C-. ,4C=/C-0 (+1C-2 !)3C-4 &)5C-6 $'7C-8  $9C-: !;C- C- C- C-J 8 8 8 8 X8 3 3 3 3 X3 # # X#  *#  *  *  * X *D3 4    	6Y? 	6D_ 	6 	6 	6 	6	5H= 	5B\ 	5 	5 	5 	5Fy~yOg?g9h Fmq F F F F
F%xG^8^2_ Fdh F F F F
?51ExGZ1Z+[ ?`d ? ? ? ?"37S>RV	c3h   &"8 "\` " " " "**x *Zb *go * * * **$ $QU $Zb $ $ $ $@9&.9?CCH~9	c3h9 9 9 9v+&.+?CCH~+	c3h+ + + +ZXeI<MxO_<_6` Xei X X X X R# R(3- R R R \R@ htCy6I dSVi    \& d3i s tCy    \* d38n QU    \  r   r0   Fr7   r,   r8   r-   ) ry   rS   r   r   r_   collections.abcr   copyr   pathlibr   typingr   r   r   r	   r
   r   
playwrightr   r   (playwright_stealth.case_insensitive_dictr   #playwright_stealth.context_managersr   r   r   r   r.   r|   r0   r  r   r   r   <module>r     s      				  $ $ $ $ $ $             : : : : : : : : : : : : : : : : * * * * * * * * H H H H H H       =s = = = =YY'ABBYYz"" ))455 ))455	
 yy!>?? #BCC ii <== YY'IJJ II899 %ii0[&\&\ 99%FGG YY'JKK ))$DEE #BCC II&GHH  		"@AA!" 99%FGG#$ !y!>??I899'  c3h   .w w w w w w w wt % %    e	 
   U  E  %e  5  U  %    E    5   u! " # $ E%      r   