109 lines
3.9 KiB
Python
109 lines
3.9 KiB
Python
"""Exchange API keys for real trading, one pair (key + secret) per exchange.
|
|
|
|
Stored in web_sim_data/api_keys.bin encrypted with Windows DPAPI (CryptProtectData, current user): the file can be
|
|
read back only by this Windows user on this computer. The page never receives a secret — only a masked key.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import ctypes
|
|
import json
|
|
import threading
|
|
from ctypes import wintypes
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parent
|
|
KEYS_FILE = ROOT / "web_sim_data" / "api_keys.bin"
|
|
EXCHANGES = {"bybit": "Bybit", "binance": "Binance", "mexc": "MEXC", "htx": "HTX", "gate": "Gate"}
|
|
_lock = threading.Lock()
|
|
|
|
|
|
class _Blob(ctypes.Structure):
|
|
_fields_ = [("cbData", wintypes.DWORD), ("pbData", ctypes.POINTER(ctypes.c_char))]
|
|
|
|
|
|
def _blob(data: bytes) -> _Blob:
|
|
buf = ctypes.create_string_buffer(data, len(data))
|
|
return _Blob(len(data), ctypes.cast(buf, ctypes.POINTER(ctypes.c_char)))
|
|
|
|
|
|
def _take(blob: _Blob) -> bytes:
|
|
try:
|
|
return ctypes.string_at(blob.pbData, blob.cbData)
|
|
finally:
|
|
ctypes.windll.kernel32.LocalFree(blob.pbData)
|
|
|
|
|
|
def protect(data: bytes) -> bytes:
|
|
out = _Blob()
|
|
if not ctypes.windll.crypt32.CryptProtectData(ctypes.byref(_blob(data)), "simulator api keys", None, None, None,
|
|
0, ctypes.byref(out)):
|
|
raise OSError("не удалось зашифровать ключи (DPAPI)")
|
|
return _take(out)
|
|
|
|
|
|
def unprotect(data: bytes) -> bytes:
|
|
out = _Blob()
|
|
if not ctypes.windll.crypt32.CryptUnprotectData(ctypes.byref(_blob(data)), None, None, None, None, 0,
|
|
ctypes.byref(out)):
|
|
raise OSError("не удалось расшифровать ключи (другой пользователь Windows или другой компьютер?)")
|
|
return _take(out)
|
|
|
|
|
|
def load(path: Path | None = None) -> dict[str, dict]:
|
|
path = path or KEYS_FILE
|
|
try:
|
|
raw = path.read_bytes()
|
|
except OSError:
|
|
return {}
|
|
try:
|
|
data = json.loads(unprotect(raw).decode("utf-8"))
|
|
except (OSError, ValueError):
|
|
return {}
|
|
return data if isinstance(data, dict) else {}
|
|
|
|
|
|
def _save(data: dict, path: Path) -> None:
|
|
path.parent.mkdir(exist_ok=True)
|
|
tmp = path.with_suffix(".tmp")
|
|
tmp.write_bytes(protect(json.dumps(data).encode("utf-8")))
|
|
tmp.replace(path)
|
|
|
|
|
|
def set_keys(exchange: str, api_key: str, api_secret: str, path: Path | None = None) -> str:
|
|
if exchange not in EXCHANGES:
|
|
return "неизвестная биржа"
|
|
api_key, api_secret = (api_key or "").strip(), (api_secret or "").strip()
|
|
if not api_key or not api_secret:
|
|
return "нужны и API key, и secret"
|
|
if len(api_key) > 200 or len(api_secret) > 400 or any(c.isspace() for c in api_key + api_secret):
|
|
return "ключ выглядит неверно (пробелы или слишком длинный)"
|
|
with _lock:
|
|
data = load(path)
|
|
data[exchange] = {"key": api_key, "secret": api_secret}
|
|
_save(data, path or KEYS_FILE)
|
|
return ""
|
|
|
|
|
|
def delete_keys(exchange: str, path: Path | None = None) -> None:
|
|
with _lock:
|
|
data = load(path)
|
|
if data.pop(exchange, None) is not None:
|
|
_save(data, path or KEYS_FILE)
|
|
|
|
|
|
def get(exchange: str, path: Path | None = None) -> tuple[str, str] | None:
|
|
d = load(path).get(exchange)
|
|
return (d["key"], d["secret"]) if d and d.get("key") and d.get("secret") else None
|
|
|
|
|
|
def mask(key: str) -> str:
|
|
return key[:4] + "…" + key[-4:] if len(key) > 10 else "…" + key[-2:]
|
|
|
|
|
|
def summary(path: Path | None = None) -> dict[str, dict]:
|
|
"""What the page may see: whether keys are set and a masked key — never the secret."""
|
|
data = load(path)
|
|
return {ex: {"name": name, "set": ex in data, "key": mask(data[ex]["key"]) if ex in data else ""}
|
|
for ex, name in EXCHANGES.items()}
|