""" CodeVault Python SDK ------------------------------------------------------------ التحقق من كود ترخيص + نبض دوري + تحقق اختياري من توقيع الخادم (RSA). التثبيت (اختياري للتحقق من التوقيع): pip install cryptography مثال: from license_client import LicenseClient lic = LicenseClient( server_url="http://127.0.0.1:8787", app_id="app_xxx", api_key="ak_xxx", api_secret="as_xxx", code="CV-XXXX-XXXX-XXXX", ) res = lic.validate() if not res["valid"]: raise SystemExit(res["message"]) lic.start_heartbeat(60, lambda err: print("توقف:", err)) """ import base64 import hashlib import hmac import json import os import platform import socket import tempfile import threading import time import urllib.error import urllib.request import uuid try: # اختياري: للتحقق من توقيع الخادم from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import padding HAVE_CRYPTO = True except Exception: # pragma: no cover HAVE_CRYPTO = False def default_hwid() -> str: parts = [ socket.gethostname(), platform.system(), platform.machine(), platform.node(), str(uuid.getnode()), ] return "hw_" + hashlib.sha256("|".join(parts).encode("utf-8")).hexdigest()[:32] class LicenseClient: def __init__( self, server_url: str, app_id: str, api_secret: str, api_key: str = "", code: str = "", version: str = "1.0.0", hwid: str = None, meta: dict = None, timeout: int = 12, public_key: str = None, verify_signature: bool = True, offline_grace_seconds: int = 0, cache_file: str = None, ): if not server_url or not app_id or not api_secret: raise ValueError("server_url و app_id و api_secret مطلوبة") self.server_url = server_url.rstrip("/") self.app_id = app_id self.api_key = api_key self.api_secret = api_secret self.code = code self.version = version self.hwid = hwid or default_hwid() self.meta = meta or {} self.timeout = timeout self.public_key_pem = public_key self.verify_signature = verify_signature and HAVE_CRYPTO self.offline_grace_seconds = offline_grace_seconds self.cache_file = cache_file or os.path.join( tempfile.gettempdir(), "codevault-%s.json" % app_id ) self.last_result = None self._stop = threading.Event() self._thread = None # ------------------------------------------------------------------ def validate(self, code: str = None, hwid: str = None) -> dict: license_code = (code or self.code or "").strip() if not license_code: raise ValueError("لم يتم تمرير كود الترخيص") self.code = license_code payload = { "code": license_code, "hwid": hwid or self.hwid, "version": self.version, "meta": self.meta, } body = json.dumps(payload, separators=(",", ":"), ensure_ascii=False).encode("utf-8") ts = str(int(time.time() * 1000)) nonce = uuid.uuid4().hex message = ("%s.%s.%s." % (self.app_id, ts, nonce)).encode("utf-8") + body signature = hmac.new(self.api_secret.encode("utf-8"), message, hashlib.sha256).hexdigest() req = urllib.request.Request( self.server_url + "/api/v1/validate", data=body, method="POST", headers={ "content-type": "application/json", "x-app-id": self.app_id, "x-api-key": self.api_key, "x-timestamp": ts, "x-nonce": nonce, "x-signature": signature, "user-agent": "CodeVault-PythonSDK/1.0", }, ) try: with urllib.request.urlopen(req, timeout=self.timeout) as resp: data = json.loads(resp.read().decode("utf-8")) except urllib.error.HTTPError as err: try: data = json.loads(err.read().decode("utf-8")) except Exception: data = {"valid": False, "message": "HTTP %s" % err.code, "reason": "HTTP_ERROR"} except Exception: cached = self._read_cache() if ( self.offline_grace_seconds > 0 and cached and cached.get("valid") and time.time() - cached.get("checked_at", 0) <= self.offline_grace_seconds ): lic = cached.get("license") or {} exp = lic.get("expiresAt") if not exp or exp > int(time.time() * 1000): cached["offline"] = True return cached raise if self.verify_signature: if not data.get("payload") or not data.get("signature"): raise RuntimeError("رد الخادم غير موقّع — تم رفضه") verified = self.verify_response(data["payload"], data["signature"]) data["verified"] = True data["valid"] = bool(verified.get("valid")) data["reason"] = verified.get("reason") data["license"] = verified.get("license") else: data["verified"] = False self.last_result = data if data.get("valid"): self._write_cache(data) return data # ------------------------------------------------------------------ def verify_response(self, payload_b64: str, signature_b64: str) -> dict: if not HAVE_CRYPTO: raise RuntimeError("مكتبة cryptography غير مثبتة — pip install cryptography") if not self.public_key_pem: with urllib.request.urlopen(self.server_url + "/api/v1/pubkey", timeout=self.timeout) as resp: self.public_key_pem = json.loads(resp.read().decode("utf-8"))["pem"] raw = base64.urlsafe_b64decode(payload_b64 + "=" * (-len(payload_b64) % 4)) sig = base64.b64decode(signature_b64) key = serialization.load_pem_public_key(self.public_key_pem.encode("utf-8")) key.verify(sig, raw, padding.PKCS1v15(), hashes.SHA256()) return json.loads(raw.decode("utf-8")) # ------------------------------------------------------------------ def start_heartbeat(self, interval_seconds: int = 60, on_invalid=None, on_error=None): self.stop_heartbeat() self._stop.clear() def loop(): while not self._stop.wait(max(5, interval_seconds)): try: res = self.validate() if not res.get("valid") and on_invalid: on_invalid(RuntimeError(res.get("message") or res.get("reason") or "الترخيص غير صالح")) return except Exception as err: # noqa: BLE001 if on_error: on_error(err) self._thread = threading.Thread(target=loop, daemon=True) self._thread.start() return self def stop_heartbeat(self): self._stop.set() if self._thread and self._thread.is_alive(): self._thread.join(timeout=0.1) self._thread = None return self # ------------------------------------------------------------------ def _write_cache(self, data: dict) -> None: try: with open(self.cache_file, "w", encoding="utf-8") as fh: json.dump( { "valid": True, "checked_at": time.time(), "reason": data.get("reason"), "license": data.get("license"), }, fh, ) except Exception: pass def _read_cache(self): try: with open(self.cache_file, "r", encoding="utf-8") as fh: return json.load(fh) except Exception: return None