Merge pull request #5 from lusm554/main

AJAX_TOKEN parser
This commit is contained in:
Andrey 2021-10-29 17:07:53 +04:00 committed by GitHub
commit 6ca89bf959
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
7 changed files with 198 additions and 110 deletions

5
.gitignore vendored Normal file
View file

@ -0,0 +1,5 @@
# Python
__pycache__
#Vim
*.swp

2
NOTICE
View file

@ -1,4 +1,4 @@
Copyright 2021 Chechkenev Andrey Copyright 2021 Chechkenev Andrey, lusm554
Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.

View file

@ -1,6 +1,7 @@
# Python Aternos API # Python Aternos API
An unofficial Aternos API written in Python. An unofficial Aternos API written in Python.
It uses requests, cloudscraper and lxml to parse data from [aternos.org](https://aternos.org/). It uses requests, cloudscraper and lxml to parse data from [aternos.org](https://aternos.org/).
> Note for vim: if u have problem like this `IndentationError: unindent does not match any outer indentation level`, try out `retab`.
## Using ## Using
First you need to install the module: First you need to install the module:
@ -55,7 +56,7 @@ You can find full documentation on the [Project Wiki](https://github.com/DarkCat
## License ## License
[License Notice](NOTICE): [License Notice](NOTICE):
``` ```
Copyright 2021 Chechkenev Andrey Copyright 2021 Chechkenev Andrey, lusm554
Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.

11
connect_test.py Normal file
View file

@ -0,0 +1,11 @@
from python_aternos import Client as AternosClient
aternos = AternosClient('', password='')
srvs = aternos.servers
print(srvs)
s = srvs[0]
s.start()

44
js2py_test.py Executable file
View file

@ -0,0 +1,44 @@
#!/usr/bin/env python3
import base64
import js2py
# Emulate 'atob' function
#print(base64.standard_b64decode('MmlYaDVXNXVFWXE1ZldKSWF6UTY='))
# Test cases
tests = [
"""(() => {window[("A" + "J" + "AX_T" + "OKE" + "N")]=("2iXh5W5u" + "EYq" + "5fWJIa" + "zQ6");})();""",
""" (() => {window[["N","TOKE","AJAX_"].reverse().join('')]=["IazQ6","fWJ","h5W5uEYq5","2iX"].reverse().join('');})();""",
"""(() => {window["AJAX_TOKEN"] = atob("SGVsbG8sIHdvcmxk")})();""",
"""(() => {window[atob('QUpBWF9UT0tFTg==')]=atob('MmlYaDVXNXVFWXE1ZldKSWF6UTY=');})();""",
"""(() => {window["AJAX_TOKEN"] = "1234" })();""",
"""(() => {window[atob('QUpBWF9UT0tFTg==')]="2iXh5W5uEYq5fWJIazQ6";})();""",
]
# Array function to ECMAScript 5.1
def code(f):
return "(function() { " + f[f.index("{")+1 : f.index("}")] + "})();"
# Emulation atob V8
def atob(arg):
return base64.standard_b64decode(str(arg)).decode("utf-8")
presettings = """
let window = {};
"""
ctx = js2py.EvalJs({ 'atob': atob })
'''
ctx.execute(presettings + code(tests[3]))
print(ctx.window)
'''
for f in tests:
try:
c = code(f)
ctx.execute(presettings + c)
print(ctx.window['AJAX_TOKEN'])
except Exception as e:
print(c, '\n', e)

View file

@ -8,141 +8,167 @@ from typing import Optional, Union
from . import aterrors from . import aterrors
# TEST
import js2py
import base64
# Set obj for js
presettings = """
let window = {};
"""
# Convert array function to CMAScript 5 function
def toECMAScript5Function(f):
return "(function() { " + f[f.index("{")+1 : f.index("}")] + "})();"
# Emulation of atob - https://developer.mozilla.org/en-US/docs/Web/API/atob
def atob(s):
return base64.standard_b64decode(str(s)).decode("utf-8")
REQGET = 0 REQGET = 0
REQPOST = 1 REQPOST = 1
REQUA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Goanna/4.8 Firefox/68.0 PaleMoon/29.4.0.2' REQUA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Goanna/4.8 Firefox/68.0 PaleMoon/29.4.0.2'
class AternosConnect: class AternosConnect:
def __init__(self) -> None: def __init__(self) -> None:
pass pass
def parse_token(self, response:Optional[Union[str,bytes]]=None) -> str: def parse_token(self, response:Optional[Union[str,bytes]]=None) -> str:
if response == None: if response == None:
loginpage = self.request_cloudflare( loginpage = self.request_cloudflare(
f'https://aternos.org/go/', REQGET f'https://aternos.org/go/', REQGET
).content ).content
pagetree = lxml.html.fromstring(loginpage) pagetree = lxml.html.fromstring(loginpage)
else: else:
pagetree = lxml.html.fromstring(response) pagetree = lxml.html.fromstring(response)
try: try:
pagehead = pagetree.head # fetch text
self.token = re.search( pagehead = pagetree.head
r'const\s+AJAX_TOKEN\s*=\s*["\'](\w+)["\']', text = pagehead.text_content()
pagehead.text_content()
)[1]
except (IndexError, TypeError):
raise aterrors.AternosCredentialsError(
'Unable to parse TOKEN from the page'
)
return self.token #search
js_funcs = re.findall(r"\(\(\)(.*?)\)\(\);", text)
token_js_func = js_funcs[1] if len(js_funcs) > 1 else js_funcs[0]
def generate_sec(self) -> str: # run js
ctx = js2py.EvalJs({ 'atob': atob })
jsf = toECMAScript5Function(token_js_func)
ctx.execute(presettings + jsf)
randkey = self.generate_aternos_rand() self.token = ctx.window['AJAX_TOKEN']
randval = self.generate_aternos_rand() except (IndexError, TypeError):
self.sec = f'{randkey}:{randval}' raise aterrors.AternosCredentialsError(
self.session.cookies.set( 'Unable to parse TOKEN from the page'
f'ATERNOS_SEC_{randkey}', randval, )
domain='aternos.org'
)
return self.sec return self.token
def generate_aternos_rand(self, randlen:int=16) -> str: def generate_sec(self) -> str:
rand_arr = [] randkey = self.generate_aternos_rand()
for i in range(randlen+1): randval = self.generate_aternos_rand()
rand_arr.append('') self.sec = f'{randkey}:{randval}'
self.session.cookies.set(
f'ATERNOS_SEC_{randkey}', randval,
domain='aternos.org'
)
rand_alphanum = \ return self.sec
self.convert_num(random.random(),36) + \
'00000000000000000'
return (rand_alphanum[2:18].join(rand_arr)[:randlen])
def convert_num(self, num:Union[int,float], base:int) -> str: def generate_aternos_rand(self, randlen:int=16) -> str:
result = '' rand_arr = []
while num > 0: for i in range(randlen+1):
result = str(num % base) + result rand_arr.append('')
num //= base
return result
def request_cloudflare( rand_alphanum = \
self, url:str, method:int, self.convert_num(random.random(),36) + \
retries:int=10, '00000000000000000'
params:Optional[dict]=None, return (rand_alphanum[2:18].join(rand_arr)[:randlen])
data:Optional[dict]=None,
headers:Optional[dict]=None,
reqcookies:Optional[dict]=None,
sendtoken:bool=False) -> Response:
cftitle = '<title>Please Wait... | Cloudflare</title>' def convert_num(self, num:Union[int,float], base:int) -> str:
if sendtoken: result = ''
if params == None: while num > 0:
params = {} result = str(num % base) + result
params['SEC'] = self.sec num //= base
params['TOKEN'] = self.token return result
if headers == None: def request_cloudflare(
headers = {} self, url:str, method:int,
headers['User-Agent'] = REQUA retries:int=10,
params:Optional[dict]=None,
data:Optional[dict]=None,
headers:Optional[dict]=None,
reqcookies:Optional[dict]=None,
sendtoken:bool=False) -> Response:
try: cftitle = '<title>Please Wait... | Cloudflare</title>'
cookies = self.session.cookies
except AttributeError:
cookies = None
self.session = CloudScraper() if sendtoken:
if cookies != None: if params == None:
self.session.cookies = cookies params = {}
params['SEC'] = self.sec
params['TOKEN'] = self.token
if method == REQPOST: if headers == None:
req = self.session.post( headers = {}
url, headers['User-Agent'] = REQUA
data=data,
headers=headers,
cookies=reqcookies
)
else:
req = self.session.get(
url,
params=params,
headers=headers,
cookies=reqcookies
)
countdown = retries try:
while cftitle in req.text \ cookies = self.session.cookies
and (countdown > 0): except AttributeError:
cookies = None
self.session = CloudScraper() self.session = CloudScraper()
if cookies != None: if cookies != None:
self.session.cookies = cookies self.session.cookies = cookies
if reqcookies != None:
for cookiekey in reqcookies:
self.session.cookies.set(cookiekey, reqcookies[cookiekey])
time.sleep(1) if method == REQPOST:
if method == REQPOST: req = self.session.post(
req = self.session.post( url,
url, data=data,
data=data, headers=headers,
headers=headers, cookies=reqcookies
cookies=reqcookies )
) else:
else: req = self.session.get(
req = self.session.get( url,
url, params=params,
params=params, headers=headers,
headers=headers, cookies=reqcookies
cookies=reqcookies )
)
countdown -= 1
return req countdown = retries
while cftitle in req.text \
and (countdown > 0):
self.session = CloudScraper()
if cookies != None:
self.session.cookies = cookies
if reqcookies != None:
for cookiekey in reqcookies:
self.session.cookies.set(cookiekey, reqcookies[cookiekey])
time.sleep(1)
if method == REQPOST:
req = self.session.post(
url,
data=data,
headers=headers,
cookies=reqcookies
)
else:
req = self.session.get(
url,
params=params,
headers=headers,
cookies=reqcookies
)
countdown -= 1
return req

View file

@ -1,3 +1,4 @@
lxml==4.6.2 lxml==4.6.2
requests==2.25.1 requests==2.25.1
cloudscraper==1.2.58 cloudscraper==1.2.58
Js2Py==0.71