""" DevEntitle licence client for Python 3.8+. Copy into your product. client = DevEntitleClient("https://terminal.deventitle.com", "acme-crm", ACME_RELEASE_PUBLIC_KEY) result = client.activate(key, "crm.buyer.com", "1.4.2") # {"valid": True, "message": ...} latest = client.check_for_update(key, "crm.buyer.com", "1.4.2") # None when up to date if latest and latest.get("download_url"): client.download_verified(latest, "/tmp/acme-crm-%s.zip" % latest["version"]) Signature checks need PyNaCl (`pip install pynacl`) or `cryptography`. Never switch features off because of a licence answer or an unreachable server. Sends only the licence key, product, domain and version. Licence: MIT. """ import base64 import hashlib import json import os import re import urllib.error import urllib.request class DevEntitleError(Exception): pass class DevEntitleClient: def __init__(self, server, product, public_key=None): self.server = server.rstrip("/") self.product = product self.public_key = public_key def activate(self, license_key, domain, version): return self._post("activate", license_key, domain, version) def deactivate(self, license_key, domain, version): self._post("deactivate", license_key, domain, version) def check_for_update(self, license_key, domain, version): """The newest offered release when newer than `version`, else None. Without download_url, show latest["message"].""" latest = self._post("updates", license_key, domain, version).get("latest") return latest if latest and compare_versions(latest["version"], version) > 0 else None def download_verified(self, latest, target_path): """Download and check SHA-256 + Ed25519 signature; raises (and writes nothing) on any mismatch.""" if not latest.get("download_url") or not latest.get("signature"): raise DevEntitleError(latest.get("message") or "This licence may not download this release.") if not self.public_key: raise DevEntitleError("No release public key is configured, so the download can't be checked.") try: with urllib.request.urlopen(latest["download_url"], timeout=600) as response: body = response.read() except urllib.error.HTTPError as error: raise DevEntitleError("The download failed (HTTP %d). Check for updates again to get a fresh link." % error.code) sha = hashlib.sha256(body).hexdigest() message = ("%s|%s|%s" % (self.product, latest["version"], sha)).encode() if sha != str(latest["sha256"]).lower() or not _verify(self.public_key, latest["signature"], message): raise DevEntitleError("The download did not pass the integrity and signature check. Nothing was installed.") with open(target_path, "wb") as handle: handle.write(body) def _post(self, endpoint, license_key, domain, version): data = json.dumps({"license_key": license_key, "product": self.product, "domain": domain, "version": version}).encode() request = urllib.request.Request( "%s/api/v1/%s" % (self.server, endpoint), data=data, headers={"Content-Type": "application/json", "Accept": "application/json"}, method="POST", ) try: with urllib.request.urlopen(request, timeout=20) as response: return json.loads(response.read()) except urllib.error.HTTPError as error: # 429 (too many checks) still carries a JSON message; 5xx means the server has a problem. if error.code < 500: try: return json.loads(error.read()) except ValueError: pass raise DevEntitleError("The licence server could not be reached (HTTP %d). Try again later." % error.code) except (urllib.error.URLError, OSError, ValueError): raise DevEntitleError("The licence server could not be reached. Try again later.") def _verify(public_key_b64, signature_b64, message): try: public = base64.b64decode(public_key_b64, validate=True) signature = base64.b64decode(signature_b64, validate=True) except (ValueError, TypeError): return False # A malformed signature or key is simply "not verified", never a crash. if len(public) != 32 or len(signature) != 64: return False try: from nacl.exceptions import BadSignatureError from nacl.signing import VerifyKey try: VerifyKey(public).verify(message, signature) return True except BadSignatureError: return False except ImportError: pass try: from cryptography.exceptions import InvalidSignature from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey try: Ed25519PublicKey.from_public_bytes(public).verify(signature, message) return True except InvalidSignature: return False except ImportError: raise DevEntitleError("Install PyNaCl (pip install pynacl) or cryptography to check release signatures.") def compare_versions(a, b): """1.10.0 > 1.9.0; a pre-release (1.0.0-beta.1) is older than its release.""" main_a, _, pre_a = str(a).partition("-") main_b, _, pre_b = str(b).partition("-") parts_a = [int(p) for p in re.findall(r"\d+", main_a)] parts_b = [int(p) for p in re.findall(r"\d+", main_b)] length = max(len(parts_a), len(parts_b)) parts_a += [0] * (length - len(parts_a)) parts_b += [0] * (length - len(parts_b)) if parts_a != parts_b: return 1 if parts_a > parts_b else -1 if pre_a == pre_b: return 0 if not pre_a: return 1 if not pre_b: return -1 return 1 if pre_a > pre_b else -1 if __name__ == "__main__" and os.environ.get("DEVENTITLE_SELFTEST"): assert compare_versions("1.10.0", "1.9.0") == 1 assert compare_versions("1.0.0-beta.1", "1.0.0") == -1 print("ok")