def get_image_data_from_page(self, html): js = re.search(r">window.*(\(function\(p.*?)</script>", html).group(1) b64_str = re.search(r"[0-9],'([A-Za-z0-9+/=]+?)'", js).group(1) s = lzstring.LZString.decompressFromBase64(b64_str) new_js = re.sub(r"'[A-Za-z0-9+/=]*'\[.*\]\('\\x7c'\)", "'" + s + "'.split('|')", js) res = dukpy.evaljs(new_js) return json.loads(re.search(r"(\{.*\})", res).group(1))
def test_eval_files_multi(self): testfile = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'test.js') with open(testfile) as f: with open(testfile) as f2: s = dukpy.evaljs([f, f2]) assert s == 11, s
def evaluate_expression( expression: str, exp_type: ExpressionType, expression_lib: list, runtime: dict, inputs: dict, cwl_self: dict): if exp_type == ExpressionType.PlainString: return expression if inputs: if exp_type == ExpressionType.ParameterReference: full_expression = parameter_reference_template(expression) else: full_expression = js_template(expression) try: res = dukpy.evaljs(expression_lib + [full_expression], runtime=runtime, inputs=inputs, cwl_self=cwl_self) if res is None and exp_type == ExpressionType.JSExpression: res = "Got a 'null' result. Do you have a `return` for your JS expression?" else: res = str(res) except dukpy.JSRuntimeError as e: res = str(e).splitlines()[0] logger.error(res) else: res = "Job inputs have not been filled out" return res
def load_tests(test_loader, test_suite, pattern): # Special function invoked by unittest.loader.TestLoader to perform special # test suite initialization. # Load the JavaScript files and get the test list using dukpy. # TODO: Limit tests according to the given pattern. if dukpy is None: # Add special test case indicating the dukpy is not installed. class SkipTestCase(unittest.TestCase): def runTest(self): self.skipTest("dukpy not installed") def __str__(self): return "Skip tests because dukpy not installed" test_suite.addTest(SkipTestCase()) return test_suite scripts = [] for filename in LIB_FILES: with open(filename) as fp: scripts.append(fp.read()) scripts.append(PREAMBLE) for filename in CODE_FILES: with open(filename) as fp: scripts.append(fp.read()) with open(TEST_FILE) as fp: scripts.append(fp.read()) scripts = tuple(scripts) test_names = dukpy.evaljs(scripts + (ENUMERATE_TESTS, )) for test_name in test_names: test_suite.addTest(ScriptTestCase(scripts, test_name)) return test_suite
def evals_es5(py_text, body_only=False, ret_code=False, enable_stage3=False, **kwargs): es5_text, _ = transpile_pys(py_text, body_only=body_only, enable_stage3=enable_stage3) res = dukpy.evaljs(es5_text, **kwargs) if ret_code: res = (res, es5_text) return res
def get_core_info(html): jsSlic = re.search(r">window.*(\(function\(p.*?)</script>", html).group(1) coreStr = re.search(r"[0-9],'([A-Za-z0-9+/=]+?)'", jsSlic).group(1) decStr = lzstring.LZString.decompressFromBase64(coreStr) jsNew = re.sub(r"'[A-Za-z0-9+/=]*'\[.*\]\('\\x7c'\)", "'" + decStr + "'.split('|')", jsSlic) sol = dukpy.evaljs(jsNew) return json.loads(re.search(r"(\{.*\})", sol).group(1))
def test_jsx_mixed(self): code = ''' var React = require('react/react'), ReactDOM = require('react/react-dom-server'); ReactDOM.renderToStaticMarkup(<h1>Hello, world!</h1>, null); ''' jsx = dukpy.jsx_compile(code) res = dukpy.evaljs(jsx) assert res == '<h1>Hello, world!</h1>', res
def eval_object_es5(py_obj, append=None, body_only=False, ret_code=False, enable_stage3=False, **kwargs): es5_text, _ = transpile_object(py_obj, body_only, enable_stage3=enable_stage3) if append: es5_text += '\n' + append res = dukpy.evaljs(es5_text, **kwargs) if ret_code: res = (res, es5_text) return res
def eval_object(py_obj, append=None, body_only=False, ret_code=False, **kwargs): js_text, _ = translate_object(py_obj, body_only) if append: js_text += append res = dukpy.evaljs(js_text, **kwargs) if ret_code: res = (res, js_text) return res
def getCoreInfo(url): with open("./config.json", 'r') as f: conf = json.load(f) baseSite = requests.get(url, headers={"User-Agent": conf["User-Agent"]}) formatedSite = bs4.BeautifulSoup(baseSite.content, features="lxml") infoJS = re.search(r">eval\((.*)\)\n<", str(formatedSite)).group(1) sol = [ re.search(r"\'(.*?)\'", z).group(1) for z in dukpy.evaljs("(" + infoJS + ")").split(",") ] return sol
def babel_compile(source, **kwargs): """Compiles the given ``source`` from ES6 to ES5 usin Babeljs""" presets = kwargs.get('presets') if not presets: kwargs['presets'] = ["es2015"] with open(BABEL_COMPILER, 'r') as babel_js: return dukpy.evaljs( (babel_js.read(), 'var bres, res;' 'bres = Babel.transform(dukpy.es6code, dukpy.babel_options);', 'res = {map: bres.map, code: bres.code};'), es6code=source, babel_options=kwargs)
def evaljs(js_text, load_es6_polyfill=False, **kwargs): """Evaluate JS code, like ``dukpy.evaljs()``, optionally loading the es6 polyfill before the actual code. """ if isinstance(js_text, (str, bytes, bytearray)): js_text = [js_text] else: list(js_text) if load_es6_polyfill: with open(BABEL_POLYFILL, 'r') as babel_poly: js_text = ['global = this; this.console = {log: print};\n' ] + [babel_poly.read()] + js_text return dukpy.evaljs(js_text, **kwargs)
def evaljs(js_text, load_es6_polyfill=False, **kwargs): """Evaluate JS code, like ``dukpy.evaljs()``, optionally loading the es6 polyfill before the actual code. """ if isinstance(js_text, (str, bytes, bytearray)): js_text = [js_text] else: list(js_text) if load_es6_polyfill: with open(BABEL_POLYFILL, 'r', encoding='utf-8') as babel_poly: js_text = (['global = this; this.console = {log: print};\n'] + [babel_poly.read()] + js_text) return dukpy.evaljs(js_text, **kwargs)
def test_pairs_without_jsmin(self): json_content = generate_js() self.assertTrue(evaljs(f"{json_content} Choices.pairs !== undefined")) years_in_school = [{"value": value, "label": str(label)} for value, label in YEAR_IN_SCHOOL_CHOICES] media_choices = [ {"value": value, "label": str(label)} for value, label in MEDIA_CHOICES[0][1] + MEDIA_CHOICES[1][1] + (MEDIA_CHOICES[2],) ] medal_types = [{"value": value, "label": str(label)} for value, label in MEDAL_TYPES] self.assertEqual(self.get_pairs(json_content, "modela_year_in_school"), years_in_school) self.assertEqual(self.get_pairs(json_content, "modelb_year_in_school"), years_in_school[:-1]) self.assertEqual(self.get_pairs(json_content, "modelb_media"), media_choices) self.assertEqual(self.get_pairs(json_content, "modelc_medals"), medal_types)
async def execute(code): prefix = "var window={\"parseInt\": true, \"location\": {\"host\": \"iyiyiyiyi\"}, \"navigator\": { \"userAgent\": \"Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20150101 Firefox/20.0 (Chrome)\"}}" if dukpy_available: return dukpy.evaljs("{};{}".format(prefix, code)) proc = await asyncio.create_subprocess_exec( "node", "-e", "{};process.stdout.write(String({}))".format(prefix, code), stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT) stdout, stderr = await proc.communicate() return stdout.decode()
def babel_compile(source, **kwargs): """Compiles the given ``source`` from ES6 to ES5 usin Babeljs""" presets = kwargs.get('presets') if not presets: kwargs['presets'] = ["es2015"] with open(BABEL_COMPILER, 'r') as babel_js: return dukpy.evaljs( (babel_js.read(), 'var bres, res;' 'bres = Babel.transform(dukpy.es6code, dukpy.babel_options);', 'res = {map: bres.map, code: bres.code};'), es6code=source, babel_options=kwargs )
def test_logging(self): log = logging.getLogger('dukpy.interpreter') with mock.patch.object(log, 'info', return_value=None) as fakelog: dukpy.evaljs('console.log("HI")') assert fakelog.call_count == 1 with mock.patch.object(log, 'info', return_value=None) as fakelog: dukpy.evaljs('console.info("HI")') assert fakelog.call_count == 1 with mock.patch.object(log, 'error', return_value=None) as fakelog: dukpy.evaljs('console.error("HI")') assert fakelog.call_count == 1 with mock.patch.object(log, 'warn', return_value=None) as fakelog: dukpy.evaljs('console.warn("HI")') assert fakelog.call_count == 1
def test_display_without_jsmin(self): json_content = generate_js() self.assertTrue(evaljs(f"{json_content} Choices.display !== undefined")) self.assertEqual(self.get_display(json_content, "modela_year_in_school", "FR"), "Freshman") self.assertEqual(self.get_display(json_content, "modela_year_in_school", "SO"), "Sophomore") self.assertEqual(self.get_display(json_content, "modela_year_in_school", "JR"), "Junior") self.assertEqual(self.get_display(json_content, "modela_year_in_school", "SR"), "Senior") self.assertEqual(self.get_display(json_content, "modela_year_in_school", "GR"), "Graduate") self.assertEqual(self.get_display(json_content, "modelb_year_in_school", "GR"), None) self.assertEqual(self.get_display(json_content, "modelb_media", "vinyl"), "Vinyl") self.assertEqual(self.get_display(json_content, "modelb_media", "cd"), "CD") self.assertEqual(self.get_display(json_content, "modelb_media", "vhs"), "VHS Tape") self.assertEqual(self.get_display(json_content, "modelb_media", "dvd"), "DVD") self.assertEqual(self.get_display(json_content, "modelb_media", "unknown"), "Unknown") self.assertEqual(self.get_display(json_content, "modelc_medals", "GOLD"), "Gold") self.assertEqual(self.get_display(json_content, "modelc_medals", "SILVER"), "Silver") self.assertEqual(self.get_display(json_content, "modelc_medals", "BRONZE"), "Bronze")
def getCoreInfo(url): with open("./config.json", "r") as f: conf = json.load(f) getSite = bs4.BeautifulSoup(requests.get(url, headers={ "User-Agent": conf["User-Agent"] }).content, features="lxml") jsSlic = re.search(r">window.*(\(function\(p.*?)</script>", str(getSite)).group(1) coreStr = re.search(r"[0-9],'([A-Za-z0-9+/=]+?)'", jsSlic).group(1) decStr = lzstring.LZString.decompressFromBase64(coreStr) jsNew = re.sub(r"'[A-Za-z0-9+/=]*'\[.*\]\('\\x7c'\)", "'" + decStr + "'.split('|')", jsSlic) sol = dukpy.evaljs(jsNew) return json.loads(re.search(r"(\{.*\})", sol).group(1))
def test_display_with_locale(self): json_content = generate_js("es") self.assertTrue(evaljs(f"{json_content} Choices.display !== undefined")) self.assertEqual(self.get_display(json_content, "modela_year_in_school", "FR"), "Estudiante de primer año") self.assertEqual(self.get_display(json_content, "modela_year_in_school", "SO"), "Estudiante de segundo año") self.assertEqual(self.get_display(json_content, "modela_year_in_school", "JR"), "Estudiante de tercer año") self.assertEqual(self.get_display(json_content, "modela_year_in_school", "SR"), "Estudiante de último año") self.assertEqual(self.get_display(json_content, "modela_year_in_school", "GR"), "Graduado") self.assertEqual(self.get_display(json_content, "modelb_year_in_school", "GR"), None) self.assertEqual(self.get_display(json_content, "modelb_media", "vinyl"), "Vinil") self.assertEqual(self.get_display(json_content, "modelb_media", "cd"), "CD") self.assertEqual(self.get_display(json_content, "modelb_media", "vhs"), "Cinta VHS") self.assertEqual(self.get_display(json_content, "modelb_media", "dvd"), "DVD") self.assertEqual(self.get_display(json_content, "modelb_media", "unknown"), "Desconocido") self.assertEqual(self.get_display(json_content, "modelc_medals", "GOLD"), "Oro") self.assertEqual(self.get_display(json_content, "modelc_medals", "SILVER"), "Plata") self.assertEqual(self.get_display(json_content, "modelc_medals", "BRONZE"), "Bronce")
def get_ports_status(address, gambit): url = "http://%s/iss/specific/PoEPortSetting.js?Gambit=%s" % (address, gambit) response = requests.get(url) poe_port_setting = dukpy.evaljs(response.text + "; PoE_Port_Setting") result = [] for port_result in poe_port_setting: if len(port_result) == 10: (port, state, time_range, priority, delay_power_detect, legacy_pd, power_limit, power, voltage, current) = port_result result += [{ "port": port, "state": state, "time_range": time_range, "priority": priority, "delay_power_detect": delay_power_detect, "legacy_pd": legacy_pd, "power_limit": power_limit, "power": power, "voltage": voltage, "current": current }] elif len(port_result) == 12: (port, state, time_range, priority, delay_power_detect, legacy_pd, power_limit, power, voltage, current, classification, status) = port_result result += [{ "port": port, "state": state, "time_range": time_range, "priority": priority, "delay_power_detect": delay_power_detect, "legacy_pd": legacy_pd, "power_limit": power_limit, "power": power, "voltage": voltage, "current": current, "classification": classification, "status": status }] return result
def test_react_binding(self): code = ''' var React = require('react/react'), ReactDOM = require('react/react-dom-server'); var HelloWorld = React.createClass({ render: function() { return ( <div className="helloworld"> Hello {this.props.data.name} </div> ); } }); ReactDOM.renderToStaticMarkup(<HelloWorld data={dukpy.data}/>, null); ''' jsx = dukpy.jsx_compile(code) res = dukpy.evaljs(jsx, data={'id': 1, 'name': "Alessandro"}) assert res == '<div class="helloworld">Hello Alessandro</div>', res
def test_jsx6(self): code = ''' import React from 'react/react'; var ReactDOM = require('react/react-dom-server'); class HelloWorld extends React.Component { render() { return ( <div className="helloworld"> Hello {this.props.data.name} </div> ); } } ReactDOM.renderToStaticMarkup(<HelloWorld data={dukpy.data}/>, null); ''' jsx = dukpy.jsx_compile(code) res = dukpy.evaljs(jsx, data={'id': 1, 'name': "Alessandro"}) assert res == '<div class="helloworld">Hello Alessandro</div>', res
def test_sum(self): n = dukpy.evaljs("dukpy['value'] + 3", value=7) assert n == 10
def test_object_return(self): ans = dukpy.evaljs(["var o = {'value': 5}", "o['value'] += 3", "o"]) assert ans == {'value': 8}
lptitle=content[3] url=url[:-1] username=username[:-1] pswd=pswd[:-1] lptitle=lptitle[:-1] print("Trying to login !\nPlease Wait...") while requests.get(url).status_code!=200: print("Login Portal Still not Available") sleep(5) r=requests.get(url); if r.status_code == 200: x=r.text if(x[(int(x.find("<title>"))+7):int(x.find("</title>"))]==lptitle): if content[4]: tst=int(x.find("<title>"))+7 tend=x.find("</title>") cid=x[(int(x.find("document.sendin.password.value = hexMD5('"))+41):(int(x.find(' + document.login.password.value + '))-1)] ch=x[(int(x.find(' + document.login.password.value + '))+36):(int(x.find("document.sendin.submit();")-7))] print("ChapID : "+str(cid)) print("ChapChallenge: "+str(ch)) pas=(cid+str(pswd)+ch) pas=pas.encode().decode('unicode-escape') cc='''function c(i,r){var n=(i&65535)+(r&65535);var u=(i>>16)+(r>>16)+(n>>16);return u<<16|n&65535}function o(i,r){return i<<r|i>>>32-r}function v(i,r,n,u,t,a){return c(o(c(c(r,i),c(u,a)),t),n)}function d(i,r,n,u,t,a,o){return v(r&n|~r&u,i,r,t,a,o)}function y(i,r,n,u,t,a,o){return v(r&u|n&~u,i,r,t,a,o)}function b(i,r,n,u,t,a,o){return v(r^n^u,i,r,t,a,o)}function k(i,r,n,u,t,a,o){return v(n^(r|~u),i,r,t,a,o)}function r(r){var n=1732584193;var u=-271733879;var t=-1732584194;var a=271733878;for(i=0;i<r.length;i+=16){var o=n;var v=u;var f=t;var e=a;n=d(n,u,t,a,r[i+0],7,-680876936);a=d(a,n,u,t,r[i+1],12,-389564586);t=d(t,a,n,u,r[i+2],17,606105819);u=d(u,t,a,n,r[i+3],22,-1044525330);n=d(n,u,t,a,r[i+4],7,-176418897);a=d(a,n,u,t,r[i+5],12,1200080426);t=d(t,a,n,u,r[i+6],17,-1473231341);u=d(u,t,a,n,r[i+7],22,-45705983);n=d(n,u,t,a,r[i+8],7,1770035416);a=d(a,n,u,t,r[i+9],12,-1958414417);t=d(t,a,n,u,r[i+10],17,-42063);u=d(u,t,a,n,r[i+11],22,-1990404162);n=d(n,u,t,a,r[i+12],7,1804603682);a=d(a,n,u,t,r[i+13],12,-40341101);t=d(t,a,n,u,r[i+14],17,-1502002290);u=d(u,t,a,n,r[i+15],22,1236535329);n=y(n,u,t,a,r[i+1],5,-165796510);a=y(a,n,u,t,r[i+6],9,-1069501632);t=y(t,a,n,u,r[i+11],14,643717713);u=y(u,t,a,n,r[i+0],20,-373897302);n=y(n,u,t,a,r[i+5],5,-701558691);a=y(a,n,u,t,r[i+10],9,38016083);t=y(t,a,n,u,r[i+15],14,-660478335);u=y(u,t,a,n,r[i+4],20,-405537848);n=y(n,u,t,a,r[i+9],5,568446438);a=y(a,n,u,t,r[i+14],9,-1019803690);t=y(t,a,n,u,r[i+3],14,-187363961);u=y(u,t,a,n,r[i+8],20,1163531501);n=y(n,u,t,a,r[i+13],5,-1444681467);a=y(a,n,u,t,r[i+2],9,-51403784);t=y(t,a,n,u,r[i+7],14,1735328473);u=y(u,t,a,n,r[i+12],20,-1926607734);n=b(n,u,t,a,r[i+5],4,-378558);a=b(a,n,u,t,r[i+8],11,-2022574463);t=b(t,a,n,u,r[i+11],16,1839030562);u=b(u,t,a,n,r[i+14],23,-35309556);n=b(n,u,t,a,r[i+1],4,-1530992060);a=b(a,n,u,t,r[i+4],11,1272893353);t=b(t,a,n,u,r[i+7],16,-155497632);u=b(u,t,a,n,r[i+10],23,-1094730640);n=b(n,u,t,a,r[i+13],4,681279174);a=b(a,n,u,t,r[i+0],11,-358537222);t=b(t,a,n,u,r[i+3],16,-722521979);u=b(u,t,a,n,r[i+6],23,76029189);n=b(n,u,t,a,r[i+9],4,-640364487);a=b(a,n,u,t,r[i+12],11,-421815835);t=b(t,a,n,u,r[i+15],16,530742520);u=b(u,t,a,n,r[i+2],23,-995338651);n=k(n,u,t,a,r[i+0],6,-198630844);a=k(a,n,u,t,r[i+7],10,1126891415);t=k(t,a,n,u,r[i+14],15,-1416354905);u=k(u,t,a,n,r[i+5],21,-57434055);n=k(n,u,t,a,r[i+12],6,1700485571);a=k(a,n,u,t,r[i+3],10,-1894986606);t=k(t,a,n,u,r[i+10],15,-1051523);u=k(u,t,a,n,r[i+1],21,-2054922799);n=k(n,u,t,a,r[i+8],6,1873313359);a=k(a,n,u,t,r[i+15],10,-30611744);t=k(t,a,n,u,r[i+6],15,-1560198380);u=k(u,t,a,n,r[i+13],21,1309151649);n=k(n,u,t,a,r[i+4],6,-145523070);a=k(a,n,u,t,r[i+11],10,-1120210379);t=k(t,a,n,u,r[i+2],15,718787259);u=k(u,t,a,n,r[i+9],21,-343485551);n=c(n,o);u=c(u,v);t=c(t,f);a=c(a,e)}return[n,u,t,a]}function n(i){var r="0123456789abcdef";var n="";for(var u=0;u<i.length*4;u++){n+=r.charAt(i[u>>2]>>u%4*8+4&15)+r.charAt(i[u>>2]>>u%4*8&15)}return n}function u(i){var r=(i.length+8>>6)+1;var n=new Array(r*16);for(var u=0;u<r*16;u++)n[u]=0;console.log(n);for(var u=0;u<i.length;u++)n[u>>2]|=(i.charCodeAt(u)&255)<<u%4*8;n[u>>2]|=128<<u%4*8;n[r*16-2]=i.length*8;return n}function t(i){return n(r(u(i)))}t(dukpy["value"]);''' pas=dukpy.evaljs(cc,value=pas) print("Password Hash : "+str(pas)) else:pas=pswd zz={"username":username,"password":pas,"dst":"","popup":"true"} rr=requests.post(url,zz); xx=rr.text print("After Login Page Title : "+str(xx[(int(xx.find("<title>"))+7):int(xx.find("</title>"))])) exit(1)
def test_eval_files(self): testfile = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'test.js') with open(testfile) as f: s = dukpy.evaljs(f) assert s == 8, s
def runTest(self): # If the JavaScript function throws an error, # it is wrapped in a dukpy.JSRuntimeError exception, # which then causes this test case to fail. dukpy.evaljs(scripts + ("tests.%s()\n" % test_name, ))
def test_unicode_jssrc(self): s = dukpy.evaljs("dukpy.c + '華'", c="華") assert s == '華華'
def test_unicode(self): s = dukpy.evaljs("dukpy.c + 'A'", c="華") assert s == '華A'
def evals(py_text, body_only=False, ret_code=False, **kwargs): js_text, _ = translates(py_text, body_only=body_only) res = dukpy.evaljs(js_text, **kwargs) if ret_code: res = (res, js_text) return res
def get_pairs(self, json_content, field): return evaljs(f"{json_content} Choices.pairs('{field}')")