Updated API

This commit is contained in:
DarkCat09 2021-11-01 18:04:19 +04:00
parent 6ca89bf959
commit ae85a218ea
11 changed files with 289 additions and 208 deletions

View file

@ -1,7 +1,7 @@
# Python Aternos API
An unofficial Aternos API written in Python.
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`.
> Note for vim: if you have a problem like `IndentationError: unindent does not match any outer indentation level`, try out `retab`.
## Using
First you need to install the module:
@ -13,7 +13,7 @@ To use Aternos API in your Python script, import it and
login with your username and password (or MD5 hash of password).
> Note: Logging in with Google or Facebook account is not supported yet.
Then get the servers list using get_servers method.
Then get the servers list using the `servers` field.
You can start/stop your Aternos server now, calling `start()` or `stop()`.
There is an example how to use the Aternos API:
@ -53,6 +53,31 @@ if testserv != None:
```
You can find full documentation on the [Project Wiki](https://github.com/DarkCat09/python-aternos/wiki).
## Changelog
<!--
* v0.1 - the first release.
* v0.2 - fixed import problem.
* v0.3 - implemented files API, added typization.
* v0.4 - implemented configuration API, some bugfixes.
* v0.5 - the API was updated corresponding to new Aternos security methods.
Huge thanks to [lusm554](https://github.com/lusm554).
* v0.6 - implementation of Google Drive backups API is planned.
* v0.7 - full implementation of config API is planned.
* v0.8 - shared access API and permission management is planned.
* v0.9.x - a long debugging before stable release, SemVer version code.
-->
|Version|Description|
|:-----:|-----------|
|v0.1|The first release.|
|v0.2|Fixed import problem.|
|v0.3|Implemented files API, added typization.|
|v0.4|Implemented configuration API, some bugfixes.|
|v0.5|The API was updated corresponding to new Aternos security methods. Huge thanks to [lusm554](https://github.com/lusm554).|
|v0.6|Preventing detecting automated access is planned.|
|v0.7|Full implementation of config API and Google Drive backups is planned.|
|v0.8|Shared access API and permission management is planned.|
|v0.9.x|A long debugging before stable release, SemVer version code.|
## License
[License Notice](NOTICE):
```

View file

@ -1,44 +0,0 @@
#!/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

@ -10,8 +10,8 @@ class Client:
def __init__(
self, username:str,
md5:Optional[str]=None,
password:Optional[str]=None) -> None:
password:Optional[str]=None,
md5:Optional[str]=None) -> None:
if (password == None) and (md5 == None):
raise AttributeError('Password was not specified')
@ -52,7 +52,7 @@ class Client:
atconnect.REQGET
)
serverstree = lxml.html.fromstring(serverspage.content)
serverslist = serverstree.xpath('//div[@class="servers"]/div')
serverslist = serverstree.xpath('//div[contains(@class,"servers ")]/div')
servers = []
for server in serverslist:

View file

@ -7,23 +7,7 @@ from cloudscraper import CloudScraper
from typing import Optional, Union
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")
from . import atjsparse
REQGET = 0
REQPOST = 1
@ -46,20 +30,15 @@ class AternosConnect:
pagetree = lxml.html.fromstring(response)
try:
# fetch text
pagehead = pagetree.head
text = pagehead.text_content()
#search
js_funcs = re.findall(r"\(\(\)(.*?)\)\(\);", text)
token_js_func = js_funcs[1] if len(js_funcs) > 1 else js_funcs[0]
# run js
ctx = js2py.EvalJs({ 'atob': atob })
jsf = toECMAScript5Function(token_js_func)
ctx.execute(presettings + jsf)
js_code = re.findall(r'\(\(\)(.*?)\)\(\);', text)
token_func = js_code[1] if len(js_code) > 1 else js_code[0]
ctx = atjsparse.exec(token_func)
self.token = ctx.window['AJAX_TOKEN']
except (IndexError, TypeError):
raise aterrors.AternosCredentialsError(
'Unable to parse TOKEN from the page'

View file

@ -0,0 +1,37 @@
import re
import js2py
import base64
brkregex = re.compile(r'\((?!\)|[\'\"])(.+?)(?<!\(|[\'\"])\)')
def parse_brackets(f):
return brkregex.search(f)[1]
def to_ecma5_function(f):
fnstart = f.find('{')+1
fnend = f.rfind('}')
f = arrow_conv(f[fnstart:fnend])
return f
def atob(s):
return base64.standard_b64decode(str(s)).decode('utf-8')
def arrow_conv(f):
if '=>' in f:
inner = parse_brackets(f)
while brkregex.match(inner) != None:
inner = parse_brackets(inner)
func = re.sub(
r'(\w+)\s*=>\s*(.+)',
r'function(\1){return \2}', inner
)
start = f.find(inner)
end = start + len(inner)
f = f[:start] + func + f[end:]
return f
def exec(f):
ctx = js2py.EvalJs({'atob': atob})
ctx.execute(to_ecma5_function(f))
return ctx

View file

@ -159,7 +159,8 @@ class AternosServer:
def motd(self, value:str) -> None:
self.atserver_request(
'https://aternos.org/panel/ajax/options/motd.php',
atconnect.REQPOST, data={'motd': value}
atconnect.REQPOST, data={'motd': value},
sendtoken=True
)
@property

View file

@ -5,7 +5,7 @@ with open('README.md', 'rt') as readme:
setuptools.setup(
name='python-aternos',
version='0.2',
version='0.5',
author='Chechkenev Andrey (@DarkCat09)',
author_email='aacd0709@mail.ru',
description='An unofficial Aternos API',

80
tests/js2py_test.py Normal file
View file

@ -0,0 +1,80 @@
#!/usr/bin/env python3
import re
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";})();""",
# ]
# Use tests from a file
tests = []
with open('../token.txt', 'rt') as f:
lines = re.split(r'[\r\n]', f.read())
del lines[len(lines)-1] # Remove empty string
tests = lines
brkregex = re.compile(r'\((?!\)|[\'\"])(.+?)(?<!\(|[\'\"])\)')
def parse_brackets(f):
return brkregex.search(f)[1]
def to_ecma5_function(f):
# return "(function() { " + f[f.index("{")+1 : f.index("}")] + "})();"
fnstart = f.find('{')+1
fnend = f.rfind('}')
f = arrow_conv(f[fnstart:fnend])
return f
def atob(s):
return base64.standard_b64decode(str(s)).decode('utf-8')
def arrow_conv(f):
if '=>' in f:
inner = parse_brackets(f)
while brkregex.match(inner) != None:
inner = parse_brackets(inner)
func = re.sub(
r'(\w+)\s*=>\s*(.+)',
r'function(\1){return \2}', inner
)
start = f.find(inner)
end = start + len(inner)
f = f[:start] + func + f[end:]
return f
ctx = js2py.EvalJs({'atob': atob})
for f in tests:
try:
c = to_ecma5_function(f)
ctx.execute(c)
print(ctx.window['AJAX_TOKEN'])
except Exception as e:
print(c, '\n', e)
# Expected output:
# 2rKOA1IFdBcHhEM616cb
# 2rKOA1IFdBcHhEM616cb
# 2rKOA1IFdBcHhEM616cb
# 2rKOA1IFdBcHhEM616cb
# 2rKOA1IFdBcHhEM616cb
# 2rKOA1IFdBcHhEM616cb
# 2rKOA1IFdBcHhEM616cb
# 2rKOA1IFdBcHhEM616cb
# 2rKOA1IFdBcHhEM616cb
# 2iXh5W5uEYq5fWJIazQ6
# CuUcmZ27Fb8bVBNw12Vj
# YPPe8Ph7vzYaZ9PF9oQP
# (Note: The last three
# tokens are different)

View file

@ -7,3 +7,6 @@
(() => {window[["A","JAX_","TOKEN"].join('')]=atob('MnJLT0ExSUZkQmNIaEVNNjE2Y2I=');})();
(() => {window["AJAX_TOKEN"]=["2rKOA1IFdB","cHhEM61","6cb"].join('');})();
(() => {window[atob('QUpBWF9UT0tFTg==')]=("2rKOA1IFdB" + "cHhEM616c" + "b");})();
(() => {window[atob('QUpBWF9UT0tFTg==')]=atob('MmlYaDVXNXVFWXE1ZldKSWF6UTY=');})();
(() => {window[["_XAJA","NEKOT"].map(s => s.split('').reverse().join('')).join('')]=!window[("encodeURI" + "Componen" + "t")] || atob('Q3VVY21aMjdGYjhiVkJOdzEyVmo=');})();
(() => {window[["N","_TOKE","AJAX"].reverse().join('')]=!window[("en" + "co" + "deURICo" + "mpone" + "nt")] || ["zv7hP8ePPY","FP9ZaY","PQo9"].map(s => s.split('').reverse().join('')).join('');})();