licenserail 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- licenserail/__init__.py +13 -0
- licenserail/client.py +330 -0
- licenserail/core.py +159 -0
- licenserail/management.py +73 -0
- licenserail-0.1.0.dist-info/METADATA +32 -0
- licenserail-0.1.0.dist-info/RECORD +8 -0
- licenserail-0.1.0.dist-info/WHEEL +4 -0
- licenserail-0.1.0.dist-info/licenses/LICENSE +21 -0
licenserail/__init__.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""LicenseRail: licensing for your software."""
|
|
2
|
+
from .client import ActivationResult, CheckResult, License, LicenseClient, collect_fingerprint
|
|
3
|
+
from .core import (
|
|
4
|
+
REVOKING_CODES, Fingerprint, evaluate, fingerprint_matches, hash_component, load_public_key, verify_token,
|
|
5
|
+
)
|
|
6
|
+
from .management import ApiRequestError, ManagementClient, verify_webhook
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"ActivationResult", "ApiRequestError", "CheckResult", "Fingerprint", "License", "LicenseClient", "ManagementClient",
|
|
10
|
+
"REVOKING_CODES", "collect_fingerprint", "evaluate", "fingerprint_matches", "hash_component", "load_public_key",
|
|
11
|
+
"verify_token", "verify_webhook",
|
|
12
|
+
]
|
|
13
|
+
__version__ = "0.1.0"
|
licenserail/client.py
ADDED
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
"""The licensing client for a vendor's app (no secrets: only the environment's public key)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import http.client
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import platform
|
|
8
|
+
import re
|
|
9
|
+
import socket
|
|
10
|
+
import subprocess
|
|
11
|
+
import threading
|
|
12
|
+
import urllib.error
|
|
13
|
+
import urllib.request
|
|
14
|
+
import warnings
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
from datetime import datetime, timezone
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import Callable, Optional
|
|
19
|
+
|
|
20
|
+
from .core import (
|
|
21
|
+
REVOKING_CODES, Fingerprint, decode_run_history, encode_run_history, evaluate, fingerprint_matches, hash_component, load_public_key, parse_time,
|
|
22
|
+
verify_token,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
MESSAGES = {
|
|
26
|
+
"Valid": "The license is valid.",
|
|
27
|
+
"Missing": "No license is activated on this device.",
|
|
28
|
+
"InvalidSignature": "The license file is invalid. Activate it again.",
|
|
29
|
+
"WrongProduct": "The license is for another product.",
|
|
30
|
+
"WrongMachine": "The license belongs to another device.",
|
|
31
|
+
"Expired": "The license has expired.",
|
|
32
|
+
"OfflineTooLong": "Connect to the internet to verify the license.",
|
|
33
|
+
"ClockTampered": "The device's clock looks wrong. Correct it and connect to the internet.",
|
|
34
|
+
"Unverified": "Connect to the internet to verify the license.",
|
|
35
|
+
"Suspended": "The license has been suspended.",
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass
|
|
40
|
+
class License:
|
|
41
|
+
payload: dict
|
|
42
|
+
|
|
43
|
+
key = property(lambda self: self.payload["licenseKey"])
|
|
44
|
+
customer = property(lambda self: self.payload["customer"])
|
|
45
|
+
kind = property(lambda self: self.payload["kind"])
|
|
46
|
+
expires_at = property(lambda self: parse_time(self.payload.get("expiresAt")))
|
|
47
|
+
offline_until = property(lambda self: parse_time(self.payload["offlineUntil"]))
|
|
48
|
+
is_test = property(lambda self: self.payload.get("test") is True)
|
|
49
|
+
is_floating = property(lambda self: self.payload.get("floating") is True)
|
|
50
|
+
features = property(lambda self: list(self.payload.get("entitlements") or []))
|
|
51
|
+
metadata = property(lambda self: dict(self.payload.get("metadata") or {}))
|
|
52
|
+
|
|
53
|
+
def has_feature(self, code: str) -> bool:
|
|
54
|
+
return code in self.features
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass
|
|
58
|
+
class CheckResult:
|
|
59
|
+
status: str
|
|
60
|
+
license: Optional[License] = None
|
|
61
|
+
|
|
62
|
+
@property
|
|
63
|
+
def valid(self) -> bool:
|
|
64
|
+
return self.status == "Valid"
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@dataclass
|
|
68
|
+
class ActivationResult:
|
|
69
|
+
success: bool
|
|
70
|
+
message: str
|
|
71
|
+
error_code: Optional[str] = None
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _run(cmd: list[str]) -> Optional[str]:
|
|
75
|
+
try:
|
|
76
|
+
return subprocess.run(cmd, capture_output=True, text=True, timeout=5, check=False).stdout
|
|
77
|
+
except (OSError, subprocess.SubprocessError):
|
|
78
|
+
return None
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _read(path: str) -> Optional[str]:
|
|
82
|
+
try:
|
|
83
|
+
v = Path(path).read_text().strip()
|
|
84
|
+
return v or None
|
|
85
|
+
except OSError:
|
|
86
|
+
return None
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def collect_fingerprint(vendor: str, product: str) -> Fingerprint:
|
|
90
|
+
"""Hashed device fingerprint (Windows, macOS, Linux)."""
|
|
91
|
+
system = platform.system()
|
|
92
|
+
if system == "Windows":
|
|
93
|
+
reg = _run(["reg", "query", r"HKLM\SOFTWARE\Microsoft\Cryptography", "/v", "MachineGuid", "/reg:64"]) or ""
|
|
94
|
+
m = re.search(r"MachineGuid\s+REG_SZ\s+(\S+)", reg)
|
|
95
|
+
vol = _run(["cmd", "/c", "vol", os.environ.get("SystemDrive", "C:")]) or ""
|
|
96
|
+
s = re.search(r"([0-9A-F]{4})-([0-9A-F]{4})", vol, re.I)
|
|
97
|
+
board = (_run(["powershell", "-NoProfile", "-Command", "(Get-CimInstance Win32_ComputerSystemProduct).UUID"]) or "").strip()
|
|
98
|
+
raw = (m.group(1) if m else None, (s.group(1) + s.group(2)).upper() if s else None, socket.gethostname(), board, "windows")
|
|
99
|
+
elif system == "Darwin":
|
|
100
|
+
io = _run(["ioreg", "-rd1", "-c", "IOPlatformExpertDevice"]) or ""
|
|
101
|
+
uuid = re.search(r'"IOPlatformUUID"\s*=\s*"([^"]+)"', io)
|
|
102
|
+
serial = re.search(r'"IOPlatformSerialNumber"\s*=\s*"([^"]+)"', io)
|
|
103
|
+
vol = re.search(r"Volume UUID:\s*([0-9A-F-]+)", _run(["diskutil", "info", "/"]) or "", re.I)
|
|
104
|
+
host = (_run(["scutil", "--get", "LocalHostName"]) or "").strip() or socket.gethostname()
|
|
105
|
+
raw = (serial and serial.group(1), vol and vol.group(1), host, uuid and uuid.group(1), "macos")
|
|
106
|
+
else:
|
|
107
|
+
machine = _read("/etc/machine-id") or _read("/var/lib/dbus/machine-id")
|
|
108
|
+
disk = None
|
|
109
|
+
for line in (_read("/proc/self/mountinfo") or "").splitlines():
|
|
110
|
+
f = line.split(" ")
|
|
111
|
+
if len(f) > 4 and f[4] == "/" and "-" in f:
|
|
112
|
+
disk = (_run(["blkid", "-s", "UUID", "-o", "value", f[f.index("-") + 2]]) or "").strip() or None
|
|
113
|
+
break
|
|
114
|
+
raw = (machine, disk, socket.gethostname(), _read("/sys/class/dmi/id/product_uuid"), "linux")
|
|
115
|
+
board = raw[3]
|
|
116
|
+
if board and re.fullmatch(r"[0F-]+", board.replace("-", ""), re.I):
|
|
117
|
+
board = None
|
|
118
|
+
return Fingerprint(hash_component(vendor, product, "machine", raw[0]), hash_component(vendor, product, "disk", raw[1]),
|
|
119
|
+
hash_component(vendor, product, "host", raw[2]), hash_component(vendor, product, "board", board), raw[4])
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _default_dir(product: str) -> Path:
|
|
123
|
+
if platform.system() == "Windows":
|
|
124
|
+
base = Path(os.environ.get("LOCALAPPDATA", Path.home() / "AppData" / "Local"))
|
|
125
|
+
elif platform.system() == "Darwin":
|
|
126
|
+
base = Path.home() / "Library" / "Application Support"
|
|
127
|
+
else:
|
|
128
|
+
base = Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local" / "share"))
|
|
129
|
+
return base / "licenserail" / product
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
class LicenseClient:
|
|
133
|
+
"""Offline verification on every start, online refresh when due, activation, deactivation and floating leases."""
|
|
134
|
+
|
|
135
|
+
def __init__(self, server_url: str, vendor: str, product: str, public_key_pem: str, storage_dir: Optional[str] = None,
|
|
136
|
+
app_version: Optional[str] = None, refresh_on_startup: bool = False, timeout: float = 10.0,
|
|
137
|
+
fingerprint: Optional[Callable[[], Fingerprint]] = None, now: Optional[Callable[[], datetime]] = None,
|
|
138
|
+
machine_name: Optional[str] = None):
|
|
139
|
+
if not server_url or not product or not public_key_pem:
|
|
140
|
+
raise ValueError("server_url, vendor, product and public_key_pem are required")
|
|
141
|
+
#: The organization ID from the dashboard (ten_...; part of every device identity).
|
|
142
|
+
self.vendor = vendor
|
|
143
|
+
self.server_url = server_url.rstrip("/")
|
|
144
|
+
self.product = product
|
|
145
|
+
self._key = load_public_key(public_key_pem)
|
|
146
|
+
self._dir = Path(storage_dir) if storage_dir else _default_dir(product)
|
|
147
|
+
self.app_version = app_version
|
|
148
|
+
self.refresh_on_startup = refresh_on_startup
|
|
149
|
+
self.timeout = timeout
|
|
150
|
+
self._fingerprint_factory = fingerprint or (lambda: collect_fingerprint(vendor, product))
|
|
151
|
+
self._fp: Optional[Fingerprint] = None
|
|
152
|
+
self._now = now or (lambda: datetime.now(timezone.utc))
|
|
153
|
+
self.machine_name = machine_name or socket.gethostname()
|
|
154
|
+
self.last_server_message: Optional[str] = None
|
|
155
|
+
self._heartbeat: Optional[threading.Timer] = None
|
|
156
|
+
self._warned_test = False
|
|
157
|
+
|
|
158
|
+
# ---------------------------------------------------------------- state
|
|
159
|
+
|
|
160
|
+
@property
|
|
161
|
+
def fingerprint(self) -> Fingerprint:
|
|
162
|
+
if self._fp is None:
|
|
163
|
+
self._fp = self._fingerprint_factory()
|
|
164
|
+
return self._fp
|
|
165
|
+
|
|
166
|
+
@property
|
|
167
|
+
def license(self) -> Optional[License]:
|
|
168
|
+
payload = self._payload()
|
|
169
|
+
return License(payload) if payload else None
|
|
170
|
+
|
|
171
|
+
def message(self, status: str) -> str:
|
|
172
|
+
return self.last_server_message if status == "Missing" and self.last_server_message else MESSAGES[status]
|
|
173
|
+
|
|
174
|
+
def evaluate_local(self) -> CheckResult:
|
|
175
|
+
token = self._read("license.lic")
|
|
176
|
+
if not token:
|
|
177
|
+
return CheckResult("Missing")
|
|
178
|
+
payload = verify_token(token, self._key)
|
|
179
|
+
last_seen = decode_run_history(self._read("license.seen"), self.vendor, self.product, self.fingerprint)
|
|
180
|
+
now = self._now()
|
|
181
|
+
status = evaluate(payload, self.product, self.fingerprint, now, last_seen)
|
|
182
|
+
if status in ("Valid", "Expired", "OfflineTooLong") and (last_seen is None or now > last_seen):
|
|
183
|
+
self._write("license.seen", encode_run_history(now, self.vendor, self.product, self.fingerprint))
|
|
184
|
+
if payload and payload.get("test") and not self._warned_test:
|
|
185
|
+
self._warned_test = True
|
|
186
|
+
warnings.warn("licenserail: test license, not for production use")
|
|
187
|
+
return CheckResult(status, License(payload) if payload else None)
|
|
188
|
+
|
|
189
|
+
def check(self) -> CheckResult:
|
|
190
|
+
"""Call on startup: evaluates offline, refreshes online when due or when only the server can clear the state."""
|
|
191
|
+
result = self.evaluate_local()
|
|
192
|
+
due = result.valid and (self.refresh_on_startup or self._now() >= parse_time(result.license.payload["refreshAfter"]))
|
|
193
|
+
if due or result.status in ("Expired", "Suspended", "OfflineTooLong", "ClockTampered", "Unverified"):
|
|
194
|
+
anomalies = ["clock_rollback"] if result.status == "ClockTampered" else ["history_missing"] if result.status == "Unverified" else None
|
|
195
|
+
try:
|
|
196
|
+
self.refresh(anomalies)
|
|
197
|
+
except OSError:
|
|
198
|
+
pass
|
|
199
|
+
result = self.evaluate_local()
|
|
200
|
+
return result
|
|
201
|
+
|
|
202
|
+
# ---------------------------------------------------------------- server calls
|
|
203
|
+
|
|
204
|
+
def activate(self, license_key: str, machine_name: Optional[str] = None) -> ActivationResult:
|
|
205
|
+
if not license_key or not license_key.strip():
|
|
206
|
+
return ActivationResult(False, "Enter the license key.", "bad_request")
|
|
207
|
+
if not fingerprint_matches(self.fingerprint, self.fingerprint): # would only use up a seat
|
|
208
|
+
return ActivationResult(False, "This device can't be identified, so a license can't be activated on it.", "device_not_identified")
|
|
209
|
+
body = {"licenseKey": license_key.strip(), "product": self.product, "fingerprint": self.fingerprint.to_json(),
|
|
210
|
+
"machineName": machine_name or self.machine_name, "appVersion": self.app_version}
|
|
211
|
+
try:
|
|
212
|
+
ok, data = self._post("/api/client/v2/activate", body)
|
|
213
|
+
if not ok and data.get("code") == "bad_request" and "floating" in data.get("message", "").lower():
|
|
214
|
+
ok, data = self._post("/api/client/v2/floating/checkout", body)
|
|
215
|
+
except OSError:
|
|
216
|
+
return ActivationResult(False, "Could not connect to the license server.", "network")
|
|
217
|
+
if not ok:
|
|
218
|
+
return ActivationResult(False, data.get("message", "Server error."), data.get("code"))
|
|
219
|
+
if not self._save_if_valid(data.get("token", "")):
|
|
220
|
+
return ActivationResult(False, "The server returned an invalid license.", "invalid_token")
|
|
221
|
+
result = self.evaluate_local()
|
|
222
|
+
if result.license and result.license.is_floating:
|
|
223
|
+
self._start_heartbeat()
|
|
224
|
+
return ActivationResult(True, "The license has been activated.") if result.valid else ActivationResult(False, MESSAGES[result.status], result.status)
|
|
225
|
+
|
|
226
|
+
checkout = activate
|
|
227
|
+
|
|
228
|
+
def release(self) -> ActivationResult:
|
|
229
|
+
return self.deactivate()
|
|
230
|
+
|
|
231
|
+
def deactivate(self) -> ActivationResult:
|
|
232
|
+
self._stop_heartbeat()
|
|
233
|
+
token = self._read("license.lic")
|
|
234
|
+
if not token:
|
|
235
|
+
return ActivationResult(True, "There is no license on this device.")
|
|
236
|
+
floating = (verify_token(token, self._key) or {}).get("floating") is True
|
|
237
|
+
try:
|
|
238
|
+
ok, data = self._post("/api/client/v2/floating/release" if floating else "/api/client/v2/deactivate",
|
|
239
|
+
{"token": token, "fingerprint": self.fingerprint.to_json()})
|
|
240
|
+
except OSError:
|
|
241
|
+
return ActivationResult(False, "Removing the license needs an internet connection.", "network")
|
|
242
|
+
if not ok and data.get("code") not in REVOKING_CODES:
|
|
243
|
+
return ActivationResult(False, data.get("message", "Server error."), data.get("code"))
|
|
244
|
+
self._delete("license.lic")
|
|
245
|
+
if not ok and data.get("code") == "wrong_machine":
|
|
246
|
+
return ActivationResult(False, data["message"], "wrong_machine")
|
|
247
|
+
return ActivationResult(True, "The license has been removed from this device.")
|
|
248
|
+
|
|
249
|
+
def refresh(self, anomalies: Optional[list] = None) -> None:
|
|
250
|
+
token = self._read("license.lic")
|
|
251
|
+
if not token:
|
|
252
|
+
return
|
|
253
|
+
floating = (verify_token(token, self._key) or {}).get("floating") is True
|
|
254
|
+
ok, data = self._post("/api/client/v2/floating/heartbeat" if floating else "/api/client/v2/refresh",
|
|
255
|
+
{"token": token, "fingerprint": self.fingerprint.to_json(), "appVersion": self.app_version, "anomalies": anomalies})
|
|
256
|
+
if ok:
|
|
257
|
+
self._save_if_valid(data.get("token", ""))
|
|
258
|
+
elif data.get("code") in REVOKING_CODES or data.get("code") == "lease_expired":
|
|
259
|
+
self._delete("license.lic")
|
|
260
|
+
self.last_server_message = data.get("message")
|
|
261
|
+
|
|
262
|
+
# ---------------------------------------------------------------- internals
|
|
263
|
+
|
|
264
|
+
def _start_heartbeat(self) -> None:
|
|
265
|
+
self._stop_heartbeat()
|
|
266
|
+
payload = self._payload()
|
|
267
|
+
if not payload or not payload.get("floating"):
|
|
268
|
+
return
|
|
269
|
+
interval = max(30.0, (parse_time(payload["offlineUntil"]) - parse_time(payload["issuedAt"])).total_seconds() / 2)
|
|
270
|
+
|
|
271
|
+
def beat():
|
|
272
|
+
try:
|
|
273
|
+
self.refresh()
|
|
274
|
+
except OSError:
|
|
275
|
+
pass
|
|
276
|
+
self._start_heartbeat()
|
|
277
|
+
|
|
278
|
+
self._heartbeat = threading.Timer(interval, beat)
|
|
279
|
+
self._heartbeat.daemon = True
|
|
280
|
+
self._heartbeat.start()
|
|
281
|
+
|
|
282
|
+
def _stop_heartbeat(self) -> None:
|
|
283
|
+
if self._heartbeat:
|
|
284
|
+
self._heartbeat.cancel()
|
|
285
|
+
self._heartbeat = None
|
|
286
|
+
|
|
287
|
+
def _post(self, path: str, body: dict) -> tuple[bool, dict]:
|
|
288
|
+
request = urllib.request.Request(self.server_url + path, data=json.dumps(body).encode(), method="POST",
|
|
289
|
+
headers={"Content-Type": "application/json", "User-Agent": "licenserail-python/0.1"})
|
|
290
|
+
try:
|
|
291
|
+
with urllib.request.urlopen(request, timeout=self.timeout) as response:
|
|
292
|
+
text = response.read().decode()
|
|
293
|
+
data = json.loads(text) if text else {}
|
|
294
|
+
except urllib.error.HTTPError as e:
|
|
295
|
+
try:
|
|
296
|
+
data = json.loads(e.read().decode() or "{}")
|
|
297
|
+
except (OSError, ValueError, http.client.HTTPException):
|
|
298
|
+
data = None
|
|
299
|
+
return False, data if isinstance(data, dict) else {"message": f"Server error ({e.code})."}
|
|
300
|
+
except (ValueError, http.client.HTTPException) as e:
|
|
301
|
+
# Not our server (a captive portal, a proxy) or a broken connection: the same as being offline.
|
|
302
|
+
raise ConnectionError(f"unexpected response from the license server: {e}") from e
|
|
303
|
+
if not isinstance(data, dict):
|
|
304
|
+
raise ConnectionError("unexpected response from the license server")
|
|
305
|
+
return True, data
|
|
306
|
+
|
|
307
|
+
def _save_if_valid(self, token: str) -> bool:
|
|
308
|
+
payload = verify_token(token, self._key)
|
|
309
|
+
if not payload or str(payload.get("product", "")).lower() != self.product.lower():
|
|
310
|
+
return False
|
|
311
|
+
self._write("license.lic", token)
|
|
312
|
+
self._write("license.seen", encode_run_history(self._now(), self.vendor, self.product, self.fingerprint))
|
|
313
|
+
return True
|
|
314
|
+
|
|
315
|
+
def _payload(self) -> Optional[dict]:
|
|
316
|
+
token = self._read("license.lic")
|
|
317
|
+
return verify_token(token, self._key) if token else None
|
|
318
|
+
|
|
319
|
+
def _read(self, name: str) -> Optional[str]:
|
|
320
|
+
return _read(str(self._dir / name))
|
|
321
|
+
|
|
322
|
+
def _write(self, name: str, value: str) -> None:
|
|
323
|
+
self._dir.mkdir(parents=True, exist_ok=True)
|
|
324
|
+
(self._dir / name).write_text(value)
|
|
325
|
+
|
|
326
|
+
def _delete(self, name: str) -> None:
|
|
327
|
+
try:
|
|
328
|
+
(self._dir / name).unlink()
|
|
329
|
+
except FileNotFoundError:
|
|
330
|
+
pass
|
licenserail/core.py
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
"""Offline license logic shared by every LicenseRail SDK (see the test vectors)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import base64
|
|
5
|
+
import binascii
|
|
6
|
+
import hashlib
|
|
7
|
+
import hmac
|
|
8
|
+
import json
|
|
9
|
+
import re
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from datetime import datetime, timedelta, timezone
|
|
12
|
+
from typing import Any, Optional
|
|
13
|
+
|
|
14
|
+
from cryptography.exceptions import InvalidSignature
|
|
15
|
+
from cryptography.hazmat.primitives import hashes, serialization
|
|
16
|
+
from cryptography.hazmat.primitives.asymmetric import ec
|
|
17
|
+
from cryptography.hazmat.primitives.asymmetric.utils import encode_dss_signature
|
|
18
|
+
|
|
19
|
+
UNAVAILABLE = "none"
|
|
20
|
+
CLOCK_TOLERANCE = timedelta(minutes=10)
|
|
21
|
+
ISSUED_AT_TOLERANCE = timedelta(days=1)
|
|
22
|
+
|
|
23
|
+
#: Error codes on which the local license is deleted; others (network, 402...) keep it.
|
|
24
|
+
REVOKING_CODES = frozenset({
|
|
25
|
+
"license_not_found", "license_suspended", "license_expired", "activation_revoked", "wrong_machine", "invalid_token",
|
|
26
|
+
"license_revoked",
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
STATUSES = ("Valid", "Missing", "InvalidSignature", "WrongProduct", "WrongMachine", "Expired", "OfflineTooLong",
|
|
30
|
+
"ClockTampered", "Unverified", "Suspended")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True)
|
|
34
|
+
class Fingerprint:
|
|
35
|
+
machine_id: str
|
|
36
|
+
disk_id: str
|
|
37
|
+
host_name: str
|
|
38
|
+
board_id: str
|
|
39
|
+
os: Optional[str] = None
|
|
40
|
+
|
|
41
|
+
@staticmethod
|
|
42
|
+
def from_json(d: dict) -> "Fingerprint":
|
|
43
|
+
return Fingerprint(d.get("machineId", ""), d.get("diskId", ""), d.get("hostName", ""), d.get("boardId", ""), d.get("os"))
|
|
44
|
+
|
|
45
|
+
def to_json(self) -> dict:
|
|
46
|
+
d = {"machineId": self.machine_id, "diskId": self.disk_id, "hostName": self.host_name, "boardId": self.board_id}
|
|
47
|
+
if self.os:
|
|
48
|
+
d["os"] = self.os
|
|
49
|
+
return d
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _b64url_decode(text: str) -> bytes:
|
|
53
|
+
if not re.fullmatch(r"[A-Za-z0-9_-]*", text) or len(text) % 4 == 1:
|
|
54
|
+
raise ValueError("invalid base64url")
|
|
55
|
+
return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def load_public_key(pem: str) -> ec.EllipticCurvePublicKey:
|
|
59
|
+
key = serialization.load_pem_public_key(pem.encode("ascii"))
|
|
60
|
+
if not isinstance(key, ec.EllipticCurvePublicKey):
|
|
61
|
+
raise ValueError("not an EC public key")
|
|
62
|
+
return key
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def verify_token(token: str, public_key: Any) -> Optional[dict]:
|
|
66
|
+
"""Verifies the ECDSA P-256 / SHA-256 signature (IEEE P1363 r||s) and returns the payload dict, or None."""
|
|
67
|
+
if not token or not isinstance(token, str):
|
|
68
|
+
return None
|
|
69
|
+
parts = token.strip().split(".")
|
|
70
|
+
if len(parts) != 2:
|
|
71
|
+
return None
|
|
72
|
+
try:
|
|
73
|
+
key = load_public_key(public_key) if isinstance(public_key, str) else public_key
|
|
74
|
+
signature = _b64url_decode(parts[1])
|
|
75
|
+
if len(signature) != 64:
|
|
76
|
+
return None
|
|
77
|
+
der = encode_dss_signature(int.from_bytes(signature[:32], "big"), int.from_bytes(signature[32:], "big"))
|
|
78
|
+
key.verify(der, parts[0].encode("ascii"), ec.ECDSA(hashes.SHA256()))
|
|
79
|
+
payload = json.loads(_b64url_decode(parts[0]).decode("utf-8"))
|
|
80
|
+
return payload if isinstance(payload, dict) and "fingerprint" in payload else None
|
|
81
|
+
except (InvalidSignature, ValueError, binascii.Error, UnicodeDecodeError, json.JSONDecodeError):
|
|
82
|
+
return None
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def hash_component(vendor: str, product: str, part: str, raw: Optional[str]) -> str:
|
|
86
|
+
"""vendor = the organization ID (ten_..., never changes). hex(SHA256(vendor + ":" + product + ":" + part + ":" + upper(trim(raw)))); blank -> "none"."""
|
|
87
|
+
if raw is None or raw.strip() == "":
|
|
88
|
+
return UNAVAILABLE
|
|
89
|
+
return hashlib.sha256(f"{vendor}:{product}:{part}:{raw.strip().upper()}".encode("utf-8")).hexdigest()
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _available(v: Optional[str]) -> bool:
|
|
93
|
+
return bool(v) and v != UNAVAILABLE
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _same(a: Optional[str], b: Optional[str]) -> bool:
|
|
97
|
+
return _available(a) and a == b
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def fingerprint_matches(registered: Fingerprint, presented: Fingerprint) -> bool:
|
|
101
|
+
if registered.os and presented.os and registered.os.lower() != presented.os.lower():
|
|
102
|
+
return False
|
|
103
|
+
matches = sum(1 for a, b in ((registered.machine_id, presented.machine_id), (registered.disk_id, presented.disk_id),
|
|
104
|
+
(registered.host_name, presented.host_name)) if _same(a, b))
|
|
105
|
+
if _available(registered.board_id):
|
|
106
|
+
return _same(registered.board_id, presented.board_id) and matches >= 1
|
|
107
|
+
return matches >= 2
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def parse_time(value: Optional[str]) -> Optional[datetime]:
|
|
111
|
+
if not value:
|
|
112
|
+
return None
|
|
113
|
+
text = value.replace("Z", "+00:00")
|
|
114
|
+
# .NET writes up to 7 fractional digits; Python accepts 6.
|
|
115
|
+
text = re.sub(r"(\.\d{6})\d+", r"\1", text)
|
|
116
|
+
dt = datetime.fromisoformat(text)
|
|
117
|
+
return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def evaluate(payload: Optional[dict], product: str, machine: Fingerprint, now: datetime, last_seen: Optional[datetime]) -> str:
|
|
121
|
+
if not payload:
|
|
122
|
+
return "InvalidSignature"
|
|
123
|
+
if str(payload.get("product", "")).lower() != product.lower():
|
|
124
|
+
return "WrongProduct"
|
|
125
|
+
if not fingerprint_matches(Fingerprint.from_json(payload["fingerprint"]), machine):
|
|
126
|
+
return "WrongMachine"
|
|
127
|
+
if payload.get("suspended"):
|
|
128
|
+
return "Suspended"
|
|
129
|
+
if last_seen is None:
|
|
130
|
+
return "Unverified"
|
|
131
|
+
if now + ISSUED_AT_TOLERANCE < parse_time(payload["issuedAt"]) or now + CLOCK_TOLERANCE < last_seen:
|
|
132
|
+
return "ClockTampered"
|
|
133
|
+
expires = parse_time(payload.get("expiresAt"))
|
|
134
|
+
if expires is not None and now >= expires:
|
|
135
|
+
return "Expired"
|
|
136
|
+
if now >= parse_time(payload["offlineUntil"]):
|
|
137
|
+
return "OfflineTooLong"
|
|
138
|
+
return "Valid"
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _history_mac(ms: str, vendor: str, product: str, machine: Fingerprint) -> str:
|
|
142
|
+
key = hashlib.sha256(f"{vendor}:run-history:{product}:{machine.machine_id}:{machine.board_id}".encode()).digest()
|
|
143
|
+
return hmac.new(key, ms.encode(), hashlib.sha256).hexdigest()[:32].upper()
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def encode_run_history(at: datetime, vendor: str, product: str, machine: Fingerprint) -> str:
|
|
147
|
+
ms = str(int(at.timestamp() * 1000))
|
|
148
|
+
return f"{ms}.{_history_mac(ms, vendor, product, machine)}"
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def decode_run_history(value: Optional[str], vendor: str, product: str, machine: Fingerprint) -> Optional[datetime]:
|
|
152
|
+
if not value:
|
|
153
|
+
return None
|
|
154
|
+
parts = value.strip().split(".")
|
|
155
|
+
if len(parts) != 2 or not re.fullmatch(r"\d{1,15}", parts[0]):
|
|
156
|
+
return None
|
|
157
|
+
if not hmac.compare_digest(parts[1], _history_mac(parts[0], vendor, product, machine)):
|
|
158
|
+
return None
|
|
159
|
+
return datetime.fromtimestamp(int(parts[0]) / 1000, tz=timezone.utc)
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""Server-side client for the management API (/api/v2). Needs a secret API key: never ship it in an app."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import base64
|
|
5
|
+
import hashlib
|
|
6
|
+
import hmac
|
|
7
|
+
import json
|
|
8
|
+
import time
|
|
9
|
+
import urllib.error
|
|
10
|
+
import urllib.request
|
|
11
|
+
import uuid
|
|
12
|
+
from typing import Any, Optional
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class ApiRequestError(Exception):
|
|
16
|
+
def __init__(self, status: int, code: str, message: str, body: Any):
|
|
17
|
+
super().__init__(message)
|
|
18
|
+
self.status, self.code, self.body = status, code, body
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class ManagementClient:
|
|
22
|
+
def __init__(self, api_key: str, base_url: str = "https://api.licenserail.com", environment: Optional[str] = None, timeout: float = 30):
|
|
23
|
+
self.api_key, self.base_url, self.environment, self.timeout = api_key, base_url.rstrip("/"), environment, timeout
|
|
24
|
+
|
|
25
|
+
def request(self, method: str, path: str, body: Any = None, headers: Optional[dict] = None) -> Any:
|
|
26
|
+
h = {"Authorization": f"Bearer {self.api_key}", "User-Agent": "licenserail-python/0.1", **(headers or {})}
|
|
27
|
+
if self.environment:
|
|
28
|
+
h["X-Environment"] = self.environment
|
|
29
|
+
data = None
|
|
30
|
+
if body is not None:
|
|
31
|
+
data = json.dumps(body).encode()
|
|
32
|
+
h["Content-Type"] = "application/json"
|
|
33
|
+
if method != "GET":
|
|
34
|
+
h.setdefault("Idempotency-Key", str(uuid.uuid4()))
|
|
35
|
+
req = urllib.request.Request(f"{self.base_url}/api/v2{path}", data=data, method=method, headers=h)
|
|
36
|
+
try:
|
|
37
|
+
with urllib.request.urlopen(req, timeout=self.timeout) as r:
|
|
38
|
+
text = r.read().decode()
|
|
39
|
+
return json.loads(text) if text else None
|
|
40
|
+
except urllib.error.HTTPError as e:
|
|
41
|
+
text = e.read().decode()
|
|
42
|
+
parsed = json.loads(text) if text.startswith("{") else {}
|
|
43
|
+
err = parsed.get("error", {})
|
|
44
|
+
raise ApiRequestError(e.code, err.get("code", "error"), err.get("message", f"HTTP {e.code}"), parsed) from None
|
|
45
|
+
|
|
46
|
+
def create_product(self, code: str, name: str, **fields) -> dict:
|
|
47
|
+
return self.request("POST", "/products", {"code": code, "name": name, **fields})
|
|
48
|
+
|
|
49
|
+
def create_customer(self, name: str, **fields) -> dict:
|
|
50
|
+
return self.request("POST", "/customers", {"name": name, **fields})
|
|
51
|
+
|
|
52
|
+
def create_licenses(self, product_id: str, customer_id: str, **fields) -> dict:
|
|
53
|
+
return self.request("POST", "/licenses", {"productId": product_id, "customerId": customer_id, **fields})
|
|
54
|
+
|
|
55
|
+
def get_license(self, license_id: str) -> dict:
|
|
56
|
+
return self.request("GET", f"/licenses/{license_id}")
|
|
57
|
+
|
|
58
|
+
def update_license(self, license_id: str, **patch) -> dict:
|
|
59
|
+
return self.request("PATCH", f"/licenses/{license_id}", patch)
|
|
60
|
+
|
|
61
|
+
def revoke_license(self, license_id: str, approval_id: Optional[str] = None) -> dict:
|
|
62
|
+
return self.request("POST", f"/licenses/{license_id}/revoke", headers={"Approval-Id": approval_id} if approval_id else None)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def verify_webhook(secret: str, headers: dict, body: str, tolerance: int = 300) -> bool:
|
|
66
|
+
"""Verifies a Standard Webhooks signature with the endpoint's whsec_ secret."""
|
|
67
|
+
lower = {k.lower(): v for k, v in headers.items()}
|
|
68
|
+
msg_id, ts, sig = lower.get("webhook-id"), lower.get("webhook-timestamp"), lower.get("webhook-signature")
|
|
69
|
+
if not msg_id or not ts or not sig or abs(time.time() - int(ts)) > tolerance:
|
|
70
|
+
return False
|
|
71
|
+
key = base64.b64decode(secret[6:] if secret.startswith("whsec_") else secret)
|
|
72
|
+
expected = base64.b64encode(hmac.new(key, f"{msg_id}.{ts}.{body}".encode(), hashlib.sha256).digest()).decode()
|
|
73
|
+
return any(s.startswith("v1,") and hmac.compare_digest(s[3:], expected) for s in sig.split(" "))
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: licenserail
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: LicenseRail client SDK: offline license verification, activation, refresh, floating leases and the management API.
|
|
5
|
+
Project-URL: Homepage, https://licenserail.com
|
|
6
|
+
Project-URL: Repository, https://github.com/codeo-engineering/licenserail-sdks
|
|
7
|
+
Author: Codeo Solutions Limited
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Requires-Python: >=3.10
|
|
11
|
+
Requires-Dist: cryptography>=41
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
|
|
14
|
+
# licenserail (Python)
|
|
15
|
+
|
|
16
|
+
```
|
|
17
|
+
pip install licenserail
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
```python
|
|
21
|
+
from licenserail import LicenseClient
|
|
22
|
+
|
|
23
|
+
client = LicenseClient(server_url="https://api.licenserail.com", vendor="ten_6f1a7e2c3b4d4e5f8a9b0c1d2e3f4a5b", product="my-app", public_key_pem=PUBLIC_KEY)
|
|
24
|
+
result = client.check() # offline check, refreshed online when due
|
|
25
|
+
if not result.valid:
|
|
26
|
+
client.activate(license_key)
|
|
27
|
+
if client.license and client.license.has_feature("export"):
|
|
28
|
+
...
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Management API (server side only, needs a secret key): `from licenserail import ManagementClient`.
|
|
32
|
+
Tests: `python -m unittest discover -s tests` (runs the shared vectors in `../test-vectors`).
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
licenserail/__init__.py,sha256=7CSfmqsSeEKgmCO-cp0YjU6dSZc4I7BMzlID336NYt8,663
|
|
2
|
+
licenserail/client.py,sha256=lLj_HrTY_ew1hSOIeWVVISMnxMYTwzgji4V2NFe0lZ4,15753
|
|
3
|
+
licenserail/core.py,sha256=YPfvnikKNFr1R4VxlcUapeoJxkkadfVkt3C06ILmLYw,6470
|
|
4
|
+
licenserail/management.py,sha256=Im8lmnL0Md4YasMW8S386dgpZshyPzFpFor34ytBatk,3646
|
|
5
|
+
licenserail-0.1.0.dist-info/METADATA,sha256=zX8g47ipqN0NYPn0GMzzIrjcdRWIYseDvwiQYfSgfOY,1140
|
|
6
|
+
licenserail-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
7
|
+
licenserail-0.1.0.dist-info/licenses/LICENSE,sha256=IjBc9sg4uVwrNDoqg10I60M0r-kllTxds_fSKEZzoQ4,1080
|
|
8
|
+
licenserail-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Codeo Solutions Limited
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|