Initialize local project and fix ranch growth synchronization
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
# Local protocol prototype
|
||||
|
||||
This is an independently written, incomplete local service based on static
|
||||
inspection of the supplied client. It is not the publisher's server source,
|
||||
not a playable private server, and not yet demonstrated with the original APK.
|
||||
|
||||
## Run
|
||||
|
||||
Python 3.13 is installed on this machine. Dependencies are already vendored in
|
||||
`vendor`; no installation is needed for this workspace.
|
||||
|
||||
```powershell
|
||||
python .\backend\server.py --host 127.0.0.1 --port 9099
|
||||
```
|
||||
|
||||
Health check: `http://127.0.0.1:9099/health`.
|
||||
The database defaults to `backend/local.db`. Do not expose this prototype to
|
||||
the public internet: there is no production authentication, rate limiting,
|
||||
TLS, audit trail, anti-replay mechanism, or trusted payment implementation.
|
||||
|
||||
For a fresh environment:
|
||||
|
||||
```powershell
|
||||
python -m pip install -r .\backend\requirements.txt
|
||||
python -B -m unittest discover -s .\backend -v
|
||||
```
|
||||
|
||||
## Implemented locally
|
||||
|
||||
- AES-128-ECB, PKCS#7 padding and Base64 request/response codec.
|
||||
- Local development account registration and login. The local login route
|
||||
compares the supplied value directly with its stored hash; it does not
|
||||
reproduce platform SDK token verification or the original password scheme.
|
||||
- One local server, server selection and token validation.
|
||||
- One role per local account, role creation and SQLite persistence.
|
||||
- Initial role-detail shape, empty optional secondary detail, time, notices,
|
||||
empty game configuration, heartbeat and guide acknowledgement.
|
||||
|
||||
## Deliberately not implemented
|
||||
|
||||
Platform login/payment, static resource manifests, gameplay rules, monsters,
|
||||
items, battles, incubation, tasks, gacha, mail, shop, exploration and every
|
||||
other unlisted feature. Unknown endpoints return `resCode: 997`. Empty role
|
||||
arrays and `{}` configuration are scaffolding, not verified original data.
|
||||
Client table and resource files are prerequisites for a real connection test.
|
||||
|
||||
The original APK is unchanged. Redirecting a test build requires modifying
|
||||
the recovered center/game server configuration and restoring the resource
|
||||
manifest. This project has not performed or validated those steps.
|
||||
@@ -0,0 +1,192 @@
|
||||
"""Compatibility codec recovered from the supplied client's Crypter class."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
|
||||
try:
|
||||
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
|
||||
except ImportError:
|
||||
import sys
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).with_name("vendor")))
|
||||
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
|
||||
|
||||
|
||||
def encode(text: str, base64_key: str) -> str:
|
||||
key = base64.b64decode(base64_key, validate=True)
|
||||
data = text.encode("utf-8")
|
||||
padding = 16 - len(data) % 16
|
||||
data += bytes([padding]) * padding
|
||||
encryptor = Cipher(algorithms.AES(key), modes.ECB()).encryptor()
|
||||
return base64.b64encode(encryptor.update(data) + encryptor.finalize()).decode("ascii")
|
||||
|
||||
|
||||
def decode(payload: str, base64_key: str) -> str:
|
||||
key = base64.b64decode(base64_key, validate=True)
|
||||
data = base64.b64decode(payload, validate=True)
|
||||
if not data or len(data) % 16:
|
||||
raise ValueError("Invalid AES payload length")
|
||||
decryptor = Cipher(algorithms.AES(key), modes.ECB()).decryptor()
|
||||
plaintext = decryptor.update(data) + decryptor.finalize()
|
||||
padding = plaintext[-1]
|
||||
if not 1 <= padding <= 16 or plaintext[-padding:] != bytes([padding]) * padding:
|
||||
raise ValueError("Invalid PKCS#7 padding")
|
||||
return plaintext[:-padding].decode("utf-8")
|
||||
|
||||
|
||||
"""Reference implementation retained only for testing the recovered algorithm."""
|
||||
|
||||
SBOX = (
|
||||
0x63,0x7C,0x77,0x7B,0xF2,0x6B,0x6F,0xC5,0x30,0x01,0x67,0x2B,0xFE,0xD7,0xAB,0x76,
|
||||
0xCA,0x82,0xC9,0x7D,0xFA,0x59,0x47,0xF0,0xAD,0xD4,0xA2,0xAF,0x9C,0xA4,0x72,0xC0,
|
||||
0xB7,0xFD,0x93,0x26,0x36,0x3F,0xF7,0xCC,0x34,0xA5,0xE5,0xF1,0x71,0xD8,0x31,0x15,
|
||||
0x04,0xC7,0x23,0xC3,0x18,0x96,0x05,0x9A,0x07,0x12,0x80,0xE2,0xEB,0x27,0xB2,0x75,
|
||||
0x09,0x83,0x2C,0x1A,0x1B,0x6E,0x5A,0xA0,0x52,0x3B,0xD6,0xB3,0x29,0xE3,0x2F,0x84,
|
||||
0x53,0xD1,0x00,0xED,0x20,0xFC,0xB1,0x5B,0x6A,0xCB,0xBE,0x39,0x4A,0x4C,0x58,0xCF,
|
||||
0xD0,0xEF,0xAA,0xFB,0x43,0x4D,0x33,0x85,0x45,0xF9,0x02,0x7F,0x50,0x3C,0x9F,0xA8,
|
||||
0x51,0xA3,0x40,0x8F,0x92,0x9D,0x38,0xF5,0xBC,0xB6,0xDA,0x21,0x10,0xFF,0xF3,0xD2,
|
||||
0xCD,0x0C,0x13,0xEC,0x5F,0x97,0x44,0x17,0xC4,0xA7,0x7E,0x3D,0x64,0x5D,0x19,0x73,
|
||||
0x60,0x81,0x4F,0xDC,0x22,0x2A,0x90,0x88,0x46,0xEE,0xB8,0x14,0xDE,0x5E,0x0B,0xDB,
|
||||
0xE0,0x32,0x3A,0x0A,0x49,0x06,0x24,0x5C,0xC2,0xD3,0xAC,0x62,0x91,0x95,0xE4,0x79,
|
||||
0xE7,0xC8,0x37,0x6D,0x8D,0xD5,0x4E,0xA9,0x6C,0x56,0xF4,0xEA,0x65,0x7A,0xAE,0x08,
|
||||
0xBA,0x78,0x25,0x2E,0x1C,0xA6,0xB4,0xC6,0xE8,0xDD,0x74,0x1F,0x4B,0xBD,0x8B,0x8A,
|
||||
0x70,0x3E,0xB5,0x66,0x48,0x03,0xF6,0x0E,0x61,0x35,0x57,0xB9,0x86,0xC1,0x1D,0x9E,
|
||||
0xE1,0xF8,0x98,0x11,0x69,0xD9,0x8E,0x94,0x9B,0x1E,0x87,0xE9,0xCE,0x55,0x28,0xDF,
|
||||
0x8C,0xA1,0x89,0x0D,0xBF,0xE6,0x42,0x68,0x41,0x99,0x2D,0x0F,0xB0,0x54,0xBB,0x16,
|
||||
)
|
||||
INV_SBOX = [0] * 256
|
||||
for _i, _v in enumerate(SBOX):
|
||||
INV_SBOX[_v] = _i
|
||||
INV_SBOX = tuple(INV_SBOX)
|
||||
|
||||
|
||||
def _rot(value: int, shift: int) -> int:
|
||||
return ((value << shift) | (value >> (32 - shift))) & 0xFFFFFFFF
|
||||
|
||||
|
||||
def _xtime(value: int) -> int:
|
||||
return ((value << 1) ^ (0x1B if value & 0x80 else 0)) & 0xFF
|
||||
|
||||
|
||||
def _mul(a: int, b: int) -> int:
|
||||
result = 0
|
||||
while b:
|
||||
if b & 1:
|
||||
result ^= a
|
||||
a = _xtime(a)
|
||||
b >>= 1
|
||||
return result
|
||||
|
||||
|
||||
def _expand_key(key: bytes) -> tuple[list[list[int]], int]:
|
||||
if len(key) not in (16, 24, 32):
|
||||
raise ValueError("AES key must be 16, 24 or 32 bytes")
|
||||
nk, rounds = len(key) // 4, len(key) // 4 + 6
|
||||
words = [list(key[i:i + 4]) for i in range(0, len(key), 4)]
|
||||
rcon = 1
|
||||
for i in range(nk, 4 * (rounds + 1)):
|
||||
temp = words[i - 1].copy()
|
||||
if i % nk == 0:
|
||||
temp = temp[1:] + temp[:1]
|
||||
temp = [SBOX[b] for b in temp]
|
||||
temp[0] ^= rcon
|
||||
rcon = _xtime(rcon)
|
||||
elif nk > 6 and i % nk == 4:
|
||||
temp = [SBOX[b] for b in temp]
|
||||
words.append([a ^ b for a, b in zip(words[i - nk], temp)])
|
||||
keys = [sum(words[4 * r:4 * r + 4], []) for r in range(rounds + 1)]
|
||||
return keys, rounds
|
||||
|
||||
|
||||
def _add_key(state: list[int], key: list[int]) -> None:
|
||||
for i in range(16):
|
||||
state[i] ^= key[i]
|
||||
|
||||
|
||||
def _shift(state: list[int], inverse: bool = False) -> None:
|
||||
for row in range(1, 4):
|
||||
indices = [4 * col + row for col in range(4)]
|
||||
values = [state[i] for i in indices]
|
||||
shift = row if inverse else -row
|
||||
values = values[-shift:] + values[:-shift]
|
||||
for i, value in zip(indices, values):
|
||||
state[i] = value
|
||||
|
||||
|
||||
def _mix(state: list[int], inverse: bool = False) -> None:
|
||||
coefficients = (14, 11, 13, 9) if inverse else (2, 3, 1, 1)
|
||||
for col in range(4):
|
||||
i = 4 * col
|
||||
original = state[i:i + 4]
|
||||
state[i:i + 4] = [
|
||||
_mul(original[j], coefficients[0])
|
||||
^ _mul(original[(j + 1) % 4], coefficients[1])
|
||||
^ _mul(original[(j + 2) % 4], coefficients[2])
|
||||
^ _mul(original[(j + 3) % 4], coefficients[3])
|
||||
for j in range(4)
|
||||
]
|
||||
|
||||
|
||||
def _crypt_block(block: bytes, keys: list[list[int]], rounds: int, inverse: bool) -> bytes:
|
||||
state = list(block)
|
||||
_add_key(state, keys[rounds if inverse else 0])
|
||||
for round_no in range(rounds - 1, 0, -1) if inverse else range(1, rounds):
|
||||
state = [(INV_SBOX if inverse else SBOX)[b] for b in state]
|
||||
_shift(state, inverse)
|
||||
_mix(state, inverse)
|
||||
_add_key(state, keys[round_no])
|
||||
state = [(INV_SBOX if inverse else SBOX)[b] for b in state]
|
||||
_shift(state, inverse)
|
||||
_add_key(state, keys[0 if inverse else rounds])
|
||||
return bytes(state)
|
||||
|
||||
|
||||
def encode(text: str, base64_key: str) -> str:
|
||||
key = base64.b64decode(base64_key, validate=True)
|
||||
data = text.encode("utf-8")
|
||||
padding = 16 - len(data) % 16
|
||||
data += bytes([padding]) * padding
|
||||
encryptor = Cipher(algorithms.AES(key), modes.ECB()).encryptor()
|
||||
return base64.b64encode(encryptor.update(data) + encryptor.finalize()).decode("ascii")
|
||||
|
||||
|
||||
def decode(payload: str, base64_key: str) -> str:
|
||||
key = base64.b64decode(base64_key, validate=True)
|
||||
data = base64.b64decode(payload, validate=True)
|
||||
if not data or len(data) % 16:
|
||||
raise ValueError("Invalid AES payload length")
|
||||
decryptor = Cipher(algorithms.AES(key), modes.ECB()).decryptor()
|
||||
plaintext = decryptor.update(data) + decryptor.finalize()
|
||||
padding = plaintext[-1]
|
||||
if not 1 <= padding <= 16 or plaintext[-padding:] != bytes([padding]) * padding:
|
||||
raise ValueError("Invalid PKCS#7 padding")
|
||||
return plaintext[:-padding].decode("utf-8")
|
||||
|
||||
|
||||
def _reference_encode(text: str, base64_key: str) -> str:
|
||||
key = base64.b64decode(base64_key, validate=True)
|
||||
keys, rounds = _expand_key(key)
|
||||
data = text.encode("utf-8")
|
||||
data += bytes([16 - len(data) % 16]) * (16 - len(data) % 16)
|
||||
encrypted = b"".join(
|
||||
_crypt_block(data[i:i + 16], keys, rounds, False)
|
||||
for i in range(0, len(data), 16)
|
||||
)
|
||||
return base64.b64encode(encrypted).decode("ascii")
|
||||
|
||||
|
||||
def _reference_decode(payload: str, base64_key: str) -> str:
|
||||
key = base64.b64decode(base64_key, validate=True)
|
||||
keys, rounds = _expand_key(key)
|
||||
data = base64.b64decode(payload, validate=True)
|
||||
if not data or len(data) % 16:
|
||||
raise ValueError("Invalid AES payload length")
|
||||
plaintext = b"".join(
|
||||
_crypt_block(data[i:i + 16], keys, rounds, True)
|
||||
for i in range(0, len(data), 16)
|
||||
)
|
||||
padding = plaintext[-1]
|
||||
if not 1 <= padding <= 16 or plaintext[-padding:] != bytes([padding]) * padding:
|
||||
raise ValueError("Invalid PKCS#7 padding")
|
||||
return plaintext[:-padding].decode("utf-8")
|
||||
@@ -0,0 +1 @@
|
||||
cryptography==50.0.2
|
||||
@@ -0,0 +1,111 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
|
||||
from crypto_compat import decode, encode
|
||||
from store import Store
|
||||
|
||||
|
||||
# Matches the supplied DYD client. Resource game_setting.xyz1 can override it.
|
||||
DEFAULT_KEY = "O/UT+WpvDymb26pF485QOA=="
|
||||
|
||||
|
||||
class GameHandler(BaseHTTPRequestHandler):
|
||||
server_version = "MyrLocalPrototype/0.1"
|
||||
|
||||
def do_GET(self) -> None:
|
||||
if self.path == "/health":
|
||||
self.write_json({"status": "ok", "prototype": True})
|
||||
else:
|
||||
self.write_json({"error": "not found"}, 404)
|
||||
|
||||
def do_POST(self) -> None:
|
||||
try:
|
||||
body = self.rfile.read(int(self.headers.get("Content-Length", "0"))).decode("utf-8")
|
||||
request = json.loads(decode(body, self.server.crypto_key)) if self.server.crypto else json.loads(body)
|
||||
with self.server.store.lock:
|
||||
result = self.dispatch(self.path.lstrip("/"), request)
|
||||
status = 200
|
||||
except (ValueError, UnicodeError, json.JSONDecodeError) as error:
|
||||
result, status = {"resCode": 400, "resMsg": str(error)}, 400
|
||||
payload = json.dumps(result, ensure_ascii=False, separators=(",", ":"))
|
||||
encoded = encode(payload, self.server.crypto_key) if self.server.crypto else payload
|
||||
data = encoded.encode("ascii")
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "text/plain; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
def dispatch(self, path: str, request: dict) -> dict:
|
||||
store: Store = self.server.store
|
||||
if path == "userInfoService/userRegister":
|
||||
return store.register(str(request.get("userName", "")), str(request.get("passWord", "")))
|
||||
if path == "userServerService/loginUser":
|
||||
password = request.get("password", "")
|
||||
return store.login(str(request.get("sdkUid", "")), str(password))
|
||||
user = store.user(str(request.get("token", "")))
|
||||
if not user:
|
||||
return {"resCode": 408, "resMsg": "local login required"}
|
||||
if path == "userServerService/enterGame":
|
||||
return {"resCode": 0, "resMsg": "ok"} if request.get("serverId") == 1 else {"resCode": 404, "resMsg": "unknown server"}
|
||||
if path == "userServerService/createMaster":
|
||||
return store.create_master(user["id"], str(request.get("roleName", "")), int(request.get("avatar", 1)))
|
||||
if path == "userServerService/firstOpenGame":
|
||||
return {"resCode": 0, "resMsg": "ok"}
|
||||
if path == "masterService/masterQuery":
|
||||
return {"resCode": 0, "resMsg": "ok", "masterInfo": store.master_info(user["id"])}
|
||||
if path == "masterService/masterQueryDetail":
|
||||
return store.detail(user["id"])
|
||||
if path == "masterService/queryMasterSecondDetail":
|
||||
return {"resCode": 997, "resMsg": "optional second detail is not implemented"}
|
||||
if path == "getSysCurTime/execute":
|
||||
return {"resCode": 0, "resMsg": "ok", "time": int(time.time() * 1000)}
|
||||
if path == "gameService/queryGameNotice":
|
||||
return {"resCode": 0, "resMsg": "ok", "gameNotice": "[]"}
|
||||
if path == "gameService/queryGameConfig":
|
||||
return {"resCode": 0, "resMsg": "ok", "config": "{}"}
|
||||
if path in ("heartBeatService/keepAlive", "guideService/guideUpdate"):
|
||||
return {"resCode": 0, "resMsg": "ok"}
|
||||
return {"resCode": 997, "resMsg": f"local prototype has not implemented: {path}"}
|
||||
|
||||
def write_json(self, value: dict, status: int = 200) -> None:
|
||||
data = json.dumps(value).encode()
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
def log_message(self, fmt: str, *args: object) -> None:
|
||||
print(f"{self.address_string()} {fmt % args}")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description="Local protocol prototype; not the original game server")
|
||||
parser.add_argument("--host", default="127.0.0.1")
|
||||
parser.add_argument("--port", type=int, default=9099)
|
||||
parser.add_argument("--database", default=str(Path(__file__).with_name("local.db")))
|
||||
parser.add_argument("--plaintext", action="store_true", help="development only: disable compatible AES codec")
|
||||
args = parser.parse_args()
|
||||
server = ThreadingHTTPServer((args.host, args.port), GameHandler)
|
||||
server.store = Store(args.database)
|
||||
server.crypto = not args.plaintext
|
||||
server.crypto_key = os.environ.get("MYR_NET_KEY", DEFAULT_KEY)
|
||||
print(f"Local prototype listening on http://{args.host}:{args.port}/ (AES={server.crypto})")
|
||||
try:
|
||||
server.serve_forever()
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
finally:
|
||||
server.server_close()
|
||||
server.store.db.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,125 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import secrets
|
||||
import sqlite3
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def now_ms() -> int:
|
||||
return int(time.time() * 1000)
|
||||
|
||||
|
||||
class Store:
|
||||
def __init__(self, database: str | Path):
|
||||
self.lock = threading.RLock()
|
||||
self.db = sqlite3.connect(database, check_same_thread=False)
|
||||
self.db.row_factory = sqlite3.Row
|
||||
self.db.execute("PRAGMA foreign_keys = ON")
|
||||
self.db.executescript("""
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT UNIQUE NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
token TEXT UNIQUE NOT NULL,
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS masters (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER UNIQUE NOT NULL REFERENCES users(id),
|
||||
role_name TEXT UNIQUE NOT NULL,
|
||||
avatar INTEGER NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
snapshot TEXT NOT NULL
|
||||
);
|
||||
""")
|
||||
|
||||
@staticmethod
|
||||
def password_hash(value: str) -> str:
|
||||
return hashlib.sha256(("local-prototype:" + value).encode()).hexdigest()
|
||||
|
||||
def register(self, name: str, password: str) -> dict:
|
||||
if not 1 <= len(name) <= 64 or not password:
|
||||
return {"resCode": 1, "resMsg": "invalid local account"}
|
||||
try:
|
||||
cursor = self.db.execute(
|
||||
"INSERT INTO users(name,password_hash,token,created_at) VALUES(?,?,?,?)",
|
||||
(name, self.password_hash(password), secrets.token_urlsafe(32), now_ms()),
|
||||
)
|
||||
except sqlite3.IntegrityError:
|
||||
return {"resCode": 1, "resMsg": "account already exists"}
|
||||
self.db.commit()
|
||||
return {"resCode": 0, "resMsg": "ok", "playerInfo": self.player_info(cursor.lastrowid)}
|
||||
|
||||
def login(self, name: str, password: str) -> dict:
|
||||
row = self.db.execute("SELECT * FROM users WHERE name=?", (name,)).fetchone()
|
||||
if not row or not secrets.compare_digest(row["password_hash"], self.password_hash(password)):
|
||||
return {"resCode": 1, "resMsg": "invalid account or password"}
|
||||
return {
|
||||
"resCode": 0, "resMsg": "ok", "playerInfo": self.player_info(row["id"]),
|
||||
"servers": [{"id": 1, "channel": "LOCAL", "platform": "ANDROID",
|
||||
"gameServerAddress": "http://127.0.0.1:9099/",
|
||||
"payServerAddress": "http://127.0.0.1:9099/",
|
||||
"serverName": "Local prototype", "serverStatus": 1}],
|
||||
"masterInfos": self.master_infos(row["id"]),
|
||||
}
|
||||
|
||||
def user(self, token: str) -> sqlite3.Row | None:
|
||||
return self.db.execute("SELECT * FROM users WHERE token=?", (token,)).fetchone()
|
||||
|
||||
def player_info(self, user_id: int) -> dict:
|
||||
row = self.db.execute("SELECT * FROM users WHERE id=?", (user_id,)).fetchone()
|
||||
return {"token": row["token"], "userIdCard": None, "userName": None}
|
||||
|
||||
def master_infos(self, user_id: int) -> list[dict]:
|
||||
rows = self.db.execute("SELECT * FROM masters WHERE user_id=?", (user_id,)).fetchall()
|
||||
return [{"id": r["id"], "serverId": 1, "masterName": r["role_name"],
|
||||
"createTime": r["created_at"], "updateTime": r["created_at"], "status": True}
|
||||
for r in rows]
|
||||
|
||||
def master(self, user_id: int) -> sqlite3.Row | None:
|
||||
return self.db.execute("SELECT * FROM masters WHERE user_id=?", (user_id,)).fetchone()
|
||||
|
||||
def master_info(self, user_id: int) -> dict | None:
|
||||
row = self.master(user_id)
|
||||
if not row:
|
||||
return None
|
||||
snapshot = json.loads(row["snapshot"])
|
||||
return {"masterId": row["id"], "createTime": row["created_at"],
|
||||
"roleName": row["role_name"], "avatar": row["avatar"],
|
||||
"level": snapshot["master"]["level"]}
|
||||
|
||||
def create_master(self, user_id: int, role_name: str, avatar: int) -> dict:
|
||||
if not 1 <= len(role_name.strip()) <= 24:
|
||||
return {"resCode": 1, "resMsg": "invalid role name"}
|
||||
created = now_ms()
|
||||
snapshot = {
|
||||
"master": {"id": 0, "createTime": created, "level": 1, "roleName": role_name,
|
||||
"farmName": role_name + "'s farm", "avatar": avatar, "exp": 0,
|
||||
"money": 1000, "ti": 100, "ke": 0, "timeTi": created},
|
||||
"history": {}, "data2": {}, "payInfo": {"payPoint": 0, "payGiftTypes": ""},
|
||||
"activityHistory": {"vipInfo": {"vipTime": 0}, "vipCheckTime": 0},
|
||||
"masterEventTimer": 0, "masterCurrentEvent": None, "stacks": [],
|
||||
"alchemyStacks": [], "monsters": [], "monsterAttributes": [], "items": [],
|
||||
"exploreTeams": [], "currentTasks": [], "rooms": [], "teams": [],
|
||||
}
|
||||
try:
|
||||
cursor = self.db.execute(
|
||||
"INSERT INTO masters(user_id,role_name,avatar,created_at,snapshot) VALUES(?,?,?,?,?)",
|
||||
(user_id, role_name.strip(), avatar, created, json.dumps(snapshot)),
|
||||
)
|
||||
except sqlite3.IntegrityError:
|
||||
return {"resCode": 1, "resMsg": "role already exists or name is taken"}
|
||||
self.db.commit()
|
||||
return {"resCode": 0, "resMsg": "ok", "masterInfo": self.master_info(user_id)}
|
||||
|
||||
def detail(self, user_id: int) -> dict:
|
||||
row = self.master(user_id)
|
||||
if not row:
|
||||
return {"resCode": 404, "resMsg": "create a role first"}
|
||||
result = json.loads(row["snapshot"])
|
||||
result["master"]["id"] = row["id"]
|
||||
return {"resCode": 0, "resMsg": "ok", **result}
|
||||
@@ -0,0 +1,74 @@
|
||||
import http.client
|
||||
import json
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
from http.server import ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
|
||||
from crypto_compat import decode, encode
|
||||
from server import DEFAULT_KEY, GameHandler
|
||||
from store import Store
|
||||
|
||||
|
||||
class CodecTest(unittest.TestCase):
|
||||
def test_nist_aes_vector(self):
|
||||
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
|
||||
cipher = Cipher(algorithms.AES(bytes.fromhex("000102030405060708090a0b0c0d0e0f")), modes.ECB())
|
||||
encrypted = cipher.encryptor().update(bytes.fromhex("00112233445566778899aabbccddeeff"))
|
||||
self.assertEqual(encrypted.hex(), "69c4e0d86a7b0430d8cdb78070b4c55a")
|
||||
|
||||
def test_unicode_roundtrip(self):
|
||||
text = json.dumps({"message": "本地测试", "number": 1}, ensure_ascii=False)
|
||||
self.assertEqual(decode(encode(text, DEFAULT_KEY), DEFAULT_KEY), text)
|
||||
|
||||
|
||||
class ProtocolTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
# Keep temporary state in the workspace on restricted Windows hosts.
|
||||
cls.test_dir = Path(__file__).with_name("test-data")
|
||||
cls.test_dir.mkdir(exist_ok=True)
|
||||
cls.database = cls.test_dir / "test.db"
|
||||
cls.server = ThreadingHTTPServer(("127.0.0.1", 0), GameHandler)
|
||||
cls.server.store = Store(cls.database)
|
||||
cls.server.crypto = True
|
||||
cls.server.crypto_key = DEFAULT_KEY
|
||||
cls.thread = threading.Thread(target=cls.server.serve_forever, daemon=True)
|
||||
cls.thread.start()
|
||||
cls.port = cls.server.server_address[1]
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.server.shutdown()
|
||||
cls.server.server_close()
|
||||
cls.thread.join()
|
||||
cls.server.store.db.close()
|
||||
cls.database.unlink(missing_ok=True)
|
||||
|
||||
def post(self, path, body):
|
||||
connection = http.client.HTTPConnection("127.0.0.1", self.port)
|
||||
connection.request("POST", "/" + path, encode(json.dumps(body), DEFAULT_KEY),
|
||||
{"Content-Type": "application/x-www-form-urlencoded"})
|
||||
response = connection.getresponse()
|
||||
result = json.loads(decode(response.read().decode(), DEFAULT_KEY))
|
||||
connection.close()
|
||||
return result
|
||||
|
||||
def test_account_role_and_snapshot(self):
|
||||
self.assertEqual(self.post("userInfoService/userRegister", {"userName": "tester", "passWord": "hash"})["resCode"], 0)
|
||||
login = self.post("userServerService/loginUser", {"sdkUid": "tester", "password": "hash"})
|
||||
self.assertEqual(login["resCode"], 0)
|
||||
self.assertEqual(login["masterInfos"], [])
|
||||
token = login["playerInfo"]["token"]
|
||||
self.assertEqual(self.post("userServerService/enterGame", {"token": token, "serverId": 1})["resCode"], 0)
|
||||
created = self.post("userServerService/createMaster", {"token": token, "serverId": 1, "roleName": "Tester", "avatar": 1})
|
||||
self.assertEqual(created["resCode"], 0)
|
||||
detail = self.post("masterService/masterQueryDetail", {"token": token, "reqid": 1, "reqsid": 1})
|
||||
self.assertEqual(detail["master"]["roleName"], "Tester")
|
||||
self.assertEqual(detail["master"]["id"], created["masterInfo"]["masterId"])
|
||||
self.assertEqual(self.post("getSysCurTime/execute", {})["resCode"], 408)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user