monemee 0.1.0__tar.gz
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.
- monemee-0.1.0/.gitignore +10 -0
- monemee-0.1.0/LICENSE +21 -0
- monemee-0.1.0/PKG-INFO +86 -0
- monemee-0.1.0/README.md +63 -0
- monemee-0.1.0/package.json +5 -0
- monemee-0.1.0/pyproject.toml +35 -0
- monemee-0.1.0/src/monemee/__init__.py +23 -0
- monemee-0.1.0/src/monemee/_errors.py +7 -0
- monemee-0.1.0/src/monemee/_http.py +30 -0
- monemee-0.1.0/src/monemee/app.py +115 -0
- monemee-0.1.0/src/monemee/license.py +241 -0
- monemee-0.1.0/src/monemee/webhook.py +32 -0
- monemee-0.1.0/tests/test_monemee.py +195 -0
monemee-0.1.0/.gitignore
ADDED
monemee-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Monemee
|
|
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.
|
monemee-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: monemee
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: License key validation with offline support for Python apps, plus paywall access checks for Flask, FastAPI and Django, powered by Monemee.
|
|
5
|
+
Project-URL: Homepage, https://dev.monemee.com
|
|
6
|
+
Project-URL: Source, https://github.com/monemee/monemee-sdk/tree/main/packages/python
|
|
7
|
+
Project-URL: Issues, https://github.com/monemee/monemee-sdk/issues
|
|
8
|
+
Project-URL: Changelog, https://github.com/monemee/monemee-sdk/blob/main/CHANGELOG.md
|
|
9
|
+
Author-email: Monemee <info@monemee.com>
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: django,ed25519,fastapi,flask,license key,license validation,monemee,offline licensing,paywall,software licensing
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Topic :: Office/Business :: Financial :: Point-Of-Sale
|
|
18
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
19
|
+
Requires-Python: >=3.10
|
|
20
|
+
Provides-Extra: offline
|
|
21
|
+
Requires-Dist: cryptography>=41; extra == 'offline'
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
|
|
24
|
+
# monemee (Python)
|
|
25
|
+
|
|
26
|
+
Sell your Python app through Monemee: license key validation with offline support for CLIs and desktop tools, plus access checks for web apps built with Flask, FastAPI or Django. Standard library only; `cryptography` is optional for offline verification.
|
|
27
|
+
|
|
28
|
+
[Monemee SDK](https://github.com/monemee/monemee-sdk) · [Deutsch](https://github.com/monemee/monemee-sdk/blob/main/README.de.md) · [Documentation](https://dev.monemee.com)
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
pip install "monemee[offline]" # [offline] enables offline verification of signed responses
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## License keys for CLIs and desktop apps
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
from monemee import License
|
|
38
|
+
|
|
39
|
+
lic = License(product_id=123)
|
|
40
|
+
|
|
41
|
+
if not lic.stored_key:
|
|
42
|
+
result = lic.activate(input("License key: "))
|
|
43
|
+
if not result.valid:
|
|
44
|
+
raise SystemExit(f"Invalid: {result.reason}")
|
|
45
|
+
|
|
46
|
+
status = lic.check() # online; offline the last check stays valid for grace_days (7)
|
|
47
|
+
if status.valid:
|
|
48
|
+
run_pro(plan=status.plan)
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Data is stored in `~/.config/monemee-<id>/license.json` (`%APPDATA%` on Windows). `lic.deactivate()` frees the device slot.
|
|
52
|
+
|
|
53
|
+
## Web apps with login (Flask, FastAPI, Django)
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
from monemee import App
|
|
57
|
+
monemee = App() # reads MONEMEE_APP_SECRET (npx monemee init)
|
|
58
|
+
|
|
59
|
+
# Flask
|
|
60
|
+
@app.get("/pro")
|
|
61
|
+
def pro():
|
|
62
|
+
if not monemee.has_access(current_user.id):
|
|
63
|
+
return redirect(monemee.buy_url(current_user.id))
|
|
64
|
+
return render_template("pro.html")
|
|
65
|
+
|
|
66
|
+
# Return after purchase (set the return URL in Monemee to https://your-app.com/monemee/return)
|
|
67
|
+
@app.get("/monemee/return")
|
|
68
|
+
def monemee_return():
|
|
69
|
+
result = monemee.unlock(current_user.id, claim=request.args["monemee_claim"])
|
|
70
|
+
return redirect("/pro" if result.access else f"/?error={result.reason}")
|
|
71
|
+
|
|
72
|
+
# Webhook (optional, applies refunds instantly)
|
|
73
|
+
@app.post("/monemee/webhook")
|
|
74
|
+
def monemee_webhook():
|
|
75
|
+
try:
|
|
76
|
+
monemee.handle_webhook(request.get_data(), request.headers.get("Monemee-Signature"))
|
|
77
|
+
except ValueError:
|
|
78
|
+
abort(400)
|
|
79
|
+
return "", 204
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Free test purchase (with a `mmapp_test_...` secret only): `redirect(monemee.test_buy_url(current_user.id, "http://localhost:5000/monemee/return"))`.
|
|
83
|
+
|
|
84
|
+
Requires Python 3.10 or newer.
|
|
85
|
+
|
|
86
|
+
MIT License
|
monemee-0.1.0/README.md
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
# monemee (Python)
|
|
2
|
+
|
|
3
|
+
Sell your Python app through Monemee: license key validation with offline support for CLIs and desktop tools, plus access checks for web apps built with Flask, FastAPI or Django. Standard library only; `cryptography` is optional for offline verification.
|
|
4
|
+
|
|
5
|
+
[Monemee SDK](https://github.com/monemee/monemee-sdk) · [Deutsch](https://github.com/monemee/monemee-sdk/blob/main/README.de.md) · [Documentation](https://dev.monemee.com)
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install "monemee[offline]" # [offline] enables offline verification of signed responses
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## License keys for CLIs and desktop apps
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
from monemee import License
|
|
15
|
+
|
|
16
|
+
lic = License(product_id=123)
|
|
17
|
+
|
|
18
|
+
if not lic.stored_key:
|
|
19
|
+
result = lic.activate(input("License key: "))
|
|
20
|
+
if not result.valid:
|
|
21
|
+
raise SystemExit(f"Invalid: {result.reason}")
|
|
22
|
+
|
|
23
|
+
status = lic.check() # online; offline the last check stays valid for grace_days (7)
|
|
24
|
+
if status.valid:
|
|
25
|
+
run_pro(plan=status.plan)
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Data is stored in `~/.config/monemee-<id>/license.json` (`%APPDATA%` on Windows). `lic.deactivate()` frees the device slot.
|
|
29
|
+
|
|
30
|
+
## Web apps with login (Flask, FastAPI, Django)
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
from monemee import App
|
|
34
|
+
monemee = App() # reads MONEMEE_APP_SECRET (npx monemee init)
|
|
35
|
+
|
|
36
|
+
# Flask
|
|
37
|
+
@app.get("/pro")
|
|
38
|
+
def pro():
|
|
39
|
+
if not monemee.has_access(current_user.id):
|
|
40
|
+
return redirect(monemee.buy_url(current_user.id))
|
|
41
|
+
return render_template("pro.html")
|
|
42
|
+
|
|
43
|
+
# Return after purchase (set the return URL in Monemee to https://your-app.com/monemee/return)
|
|
44
|
+
@app.get("/monemee/return")
|
|
45
|
+
def monemee_return():
|
|
46
|
+
result = monemee.unlock(current_user.id, claim=request.args["monemee_claim"])
|
|
47
|
+
return redirect("/pro" if result.access else f"/?error={result.reason}")
|
|
48
|
+
|
|
49
|
+
# Webhook (optional, applies refunds instantly)
|
|
50
|
+
@app.post("/monemee/webhook")
|
|
51
|
+
def monemee_webhook():
|
|
52
|
+
try:
|
|
53
|
+
monemee.handle_webhook(request.get_data(), request.headers.get("Monemee-Signature"))
|
|
54
|
+
except ValueError:
|
|
55
|
+
abort(400)
|
|
56
|
+
return "", 204
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Free test purchase (with a `mmapp_test_...` secret only): `redirect(monemee.test_buy_url(current_user.id, "http://localhost:5000/monemee/return"))`.
|
|
60
|
+
|
|
61
|
+
Requires Python 3.10 or newer.
|
|
62
|
+
|
|
63
|
+
MIT License
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.21"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "monemee"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "License key validation with offline support for Python apps, plus paywall access checks for Flask, FastAPI and Django, powered by Monemee."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
requires-python = ">=3.10"
|
|
12
|
+
dependencies = []
|
|
13
|
+
keywords = ["monemee", "license key", "license validation", "software licensing", "paywall", "flask", "fastapi", "django", "offline licensing", "ed25519"]
|
|
14
|
+
authors = [{ name = "Monemee", email = "info@monemee.com" }]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 4 - Beta",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"License :: OSI Approved :: MIT License",
|
|
19
|
+
"Programming Language :: Python :: 3",
|
|
20
|
+
"Topic :: Software Development :: Libraries",
|
|
21
|
+
"Topic :: Office/Business :: Financial :: Point-Of-Sale",
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
[project.optional-dependencies]
|
|
25
|
+
# Offline-Prüfung signierter Lizenzantworten (Ed25519)
|
|
26
|
+
offline = ["cryptography>=41"]
|
|
27
|
+
|
|
28
|
+
[project.urls]
|
|
29
|
+
Homepage = "https://dev.monemee.com"
|
|
30
|
+
Source = "https://github.com/monemee/monemee-sdk/tree/main/packages/python"
|
|
31
|
+
Issues = "https://github.com/monemee/monemee-sdk/issues"
|
|
32
|
+
Changelog = "https://github.com/monemee/monemee-sdk/blob/main/CHANGELOG.md"
|
|
33
|
+
|
|
34
|
+
[tool.hatch.build.targets.wheel]
|
|
35
|
+
packages = ["src/monemee"]
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Monemee für Python.
|
|
2
|
+
|
|
3
|
+
Download-Software (CLI, Desktop):
|
|
4
|
+
|
|
5
|
+
from monemee import License
|
|
6
|
+
lic = License(product_id=123)
|
|
7
|
+
lic.activate("MM-XXXX-XXXX-XXXX-XXXX") # einmal
|
|
8
|
+
if lic.check().valid: ... # bei jedem Start, offline bis grace_days
|
|
9
|
+
|
|
10
|
+
Web-App mit Login (Flask, FastAPI, Django):
|
|
11
|
+
|
|
12
|
+
from monemee import App
|
|
13
|
+
monemee = App() # liest MONEMEE_APP_SECRET
|
|
14
|
+
monemee.has_access(user_id)
|
|
15
|
+
monemee.buy_url(user_id)
|
|
16
|
+
"""
|
|
17
|
+
from ._errors import MonemeeError
|
|
18
|
+
from .license import License, LicenseResult
|
|
19
|
+
from .app import App, AccessResult
|
|
20
|
+
from .webhook import verify_webhook
|
|
21
|
+
|
|
22
|
+
__all__ = ["License", "LicenseResult", "App", "AccessResult", "verify_webhook", "MonemeeError"]
|
|
23
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import urllib.error
|
|
3
|
+
import urllib.request
|
|
4
|
+
|
|
5
|
+
from ._errors import MonemeeError
|
|
6
|
+
|
|
7
|
+
USER_AGENT = "monemee-python/0.1.0"
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def request(method, url, body=None, token=None, timeout=8):
|
|
11
|
+
"""JSON-Request mit der Standardbibliothek. Gibt das geparste JSON zurück."""
|
|
12
|
+
data = json.dumps(body).encode("utf-8") if body is not None else None
|
|
13
|
+
req = urllib.request.Request(url, data=data, method=method)
|
|
14
|
+
req.add_header("Accept", "application/json")
|
|
15
|
+
req.add_header("User-Agent", USER_AGENT)
|
|
16
|
+
if data is not None:
|
|
17
|
+
req.add_header("Content-Type", "application/json")
|
|
18
|
+
if token:
|
|
19
|
+
req.add_header("Authorization", "Bearer " + token)
|
|
20
|
+
try:
|
|
21
|
+
with urllib.request.urlopen(req, timeout=timeout) as res:
|
|
22
|
+
return json.loads(res.read().decode("utf-8") or "null")
|
|
23
|
+
except urllib.error.HTTPError as err:
|
|
24
|
+
try:
|
|
25
|
+
payload = json.loads(err.read().decode("utf-8"))
|
|
26
|
+
except Exception:
|
|
27
|
+
payload = {}
|
|
28
|
+
raise MonemeeError(payload.get("message") or "HTTP %s" % err.code, code=payload.get("code") or "SERVER", status=err.code)
|
|
29
|
+
except (urllib.error.URLError, TimeoutError, OSError) as err:
|
|
30
|
+
raise MonemeeError("Monemee nicht erreichbar (%s)" % getattr(err, "reason", err), code="NETWORK")
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""Zugang für Web-Apps mit Login (Flask, FastAPI, Django …)."""
|
|
2
|
+
import os
|
|
3
|
+
import re
|
|
4
|
+
import threading
|
|
5
|
+
import time
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Optional
|
|
8
|
+
from urllib.parse import urlencode
|
|
9
|
+
|
|
10
|
+
from ._errors import MonemeeError
|
|
11
|
+
from . import _http
|
|
12
|
+
from .webhook import verify_webhook
|
|
13
|
+
|
|
14
|
+
SECRET_RE = re.compile(r"^mmapp_(test|live)_[0-9A-Za-z]{32}$")
|
|
15
|
+
REF_RE = re.compile(r"^[A-Za-z0-9._:@-]{1,128}$")
|
|
16
|
+
CACHE_EVENTS = {"license.created", "license.revoked", "license.activated", "sale.completed"}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass
|
|
20
|
+
class AccessResult:
|
|
21
|
+
access: bool
|
|
22
|
+
reason: Optional[str] = None
|
|
23
|
+
plan: Optional[str] = None
|
|
24
|
+
expires_at: Optional[str] = None
|
|
25
|
+
test: bool = False
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class App:
|
|
29
|
+
"""App(app_secret=None, product_id=None, webhook_secret=None, cache_seconds=300)
|
|
30
|
+
|
|
31
|
+
Werte kommen standardmäßig aus MONEMEE_APP_SECRET, MONEMEE_PRODUCT_ID,
|
|
32
|
+
MONEMEE_WEBHOOK_SECRET, MONEMEE_BASE_URL.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
def __init__(self, app_secret=None, product_id=None, webhook_secret=None, base_url=None, cache_seconds=300, timeout=8):
|
|
36
|
+
self.app_secret = app_secret or os.environ.get("MONEMEE_APP_SECRET", "")
|
|
37
|
+
if not SECRET_RE.match(self.app_secret):
|
|
38
|
+
raise MonemeeError("MONEMEE_APP_SECRET fehlt oder ist ungültig (npx monemee init oder Dashboard → App-Anbindung)", code="CONFIG")
|
|
39
|
+
self.mode = "test" if self.app_secret.startswith("mmapp_test_") else "live"
|
|
40
|
+
self.product_id = product_id or os.environ.get("MONEMEE_PRODUCT_ID")
|
|
41
|
+
self.webhook_secret = webhook_secret or os.environ.get("MONEMEE_WEBHOOK_SECRET")
|
|
42
|
+
self.base_url = (base_url or os.environ.get("MONEMEE_BASE_URL") or "https://monemee.com").rstrip("/")
|
|
43
|
+
self.cache_seconds = cache_seconds
|
|
44
|
+
self.timeout = timeout
|
|
45
|
+
self._cache = {}
|
|
46
|
+
self._lock = threading.Lock()
|
|
47
|
+
|
|
48
|
+
def _api(self, method, path, body=None):
|
|
49
|
+
res = _http.request(method, "%s/api/v1/apps%s" % (self.base_url, path), body, token=self.app_secret, timeout=self.timeout)
|
|
50
|
+
return (res or {}).get("data") or {}
|
|
51
|
+
|
|
52
|
+
@staticmethod
|
|
53
|
+
def _ref(ref):
|
|
54
|
+
ref = str(ref).strip() if ref is not None else ""
|
|
55
|
+
if not REF_RE.match(ref):
|
|
56
|
+
raise MonemeeError("ref muss eine Nutzer-ID sein (max. 128 Zeichen aus A-Z a-z 0-9 . _ : @ -)", code="INVALID_REF")
|
|
57
|
+
return ref
|
|
58
|
+
|
|
59
|
+
@staticmethod
|
|
60
|
+
def _result(d):
|
|
61
|
+
return AccessResult(access=bool(d.get("access")), reason=d.get("reason"), plan=d.get("plan"),
|
|
62
|
+
expires_at=d.get("expires_at"), test=bool(d.get("test")))
|
|
63
|
+
|
|
64
|
+
def access(self, ref):
|
|
65
|
+
ref = self._ref(ref)
|
|
66
|
+
with self._lock:
|
|
67
|
+
hit = self._cache.get(ref)
|
|
68
|
+
if hit and hit[1] > time.time():
|
|
69
|
+
return hit[0]
|
|
70
|
+
result = self._result(self._api("POST", "/access", {"ref": ref}))
|
|
71
|
+
if self.cache_seconds > 0:
|
|
72
|
+
with self._lock:
|
|
73
|
+
self._cache[ref] = (result, time.time() + self.cache_seconds)
|
|
74
|
+
return result
|
|
75
|
+
|
|
76
|
+
def has_access(self, ref):
|
|
77
|
+
return self.access(ref).access
|
|
78
|
+
|
|
79
|
+
def unlock(self, ref, claim=None, key=None):
|
|
80
|
+
"""Rücksprung-Token (?monemee_claim=…) oder Lizenzschlüssel einlösen und an ref binden."""
|
|
81
|
+
ref = self._ref(ref)
|
|
82
|
+
if not claim and not key:
|
|
83
|
+
raise MonemeeError("claim oder key ist erforderlich", code="INVALID_INPUT")
|
|
84
|
+
body = {"ref": ref}
|
|
85
|
+
if claim:
|
|
86
|
+
body["claim"] = claim
|
|
87
|
+
else:
|
|
88
|
+
body["key"] = key
|
|
89
|
+
result = self._result(self._api("POST", "/claim", body))
|
|
90
|
+
with self._lock:
|
|
91
|
+
self._cache.pop(ref, None)
|
|
92
|
+
return result
|
|
93
|
+
|
|
94
|
+
def buy_url(self, ref=None):
|
|
95
|
+
if not self.product_id:
|
|
96
|
+
self.product_id = self._api("GET", "/me").get("product_id")
|
|
97
|
+
url = "%s/buy/%s" % (self.base_url, self.product_id)
|
|
98
|
+
return url + ("?" + urlencode({"ref": self._ref(ref)}) if ref not in (None, "") else "")
|
|
99
|
+
|
|
100
|
+
def test_buy_url(self, ref, return_url=None):
|
|
101
|
+
if self.mode != "test":
|
|
102
|
+
raise MonemeeError("Testkäufe gehen nur mit einem Test-Secret (mmapp_test_…)", code="TEST_ONLY")
|
|
103
|
+
body = {"ref": self._ref(ref)}
|
|
104
|
+
if return_url:
|
|
105
|
+
body["return_url"] = return_url
|
|
106
|
+
return self._api("POST", "/test-claim", body).get("redirectUrl")
|
|
107
|
+
|
|
108
|
+
def handle_webhook(self, raw_body, signature_header):
|
|
109
|
+
"""Signatur prüfen (roher Body!), Cache leeren. Gibt das Event zurück; ValueError bei falscher Signatur."""
|
|
110
|
+
event = verify_webhook(raw_body, signature_header, self.webhook_secret)
|
|
111
|
+
ref = (event.get("data") or {}).get("external_ref")
|
|
112
|
+
if ref and event.get("event") in CACHE_EVENTS:
|
|
113
|
+
with self._lock:
|
|
114
|
+
self._cache.pop(ref, None)
|
|
115
|
+
return event
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
"""Lizenzschlüssel für Download-Software (CLI, Desktop, Skripte)."""
|
|
2
|
+
import base64
|
|
3
|
+
import hashlib
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
import secrets
|
|
8
|
+
import time
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from datetime import datetime, timezone
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Optional
|
|
13
|
+
|
|
14
|
+
from ._errors import MonemeeError
|
|
15
|
+
from . import _http
|
|
16
|
+
|
|
17
|
+
KEY_RE = re.compile(r"^MM(-[A-Z0-9]{4}){4}$")
|
|
18
|
+
STORE_VERSION = 1
|
|
19
|
+
# Public signing keys of monemee.com (also at /.well-known/monemee-license-keys.json).
|
|
20
|
+
# Unknown key IDs (after a key rotation) are fetched on the next online check.
|
|
21
|
+
BUNDLED_PUBLIC_KEYS = [
|
|
22
|
+
{"kid": "mm-1", "kty": "OKP", "crv": "Ed25519", "x": "-dEgFSZLvP66Cqh_ksHi4rfOJoR2IKp8k3s9LBtUMgM"},
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass
|
|
27
|
+
class LicenseResult:
|
|
28
|
+
valid: bool
|
|
29
|
+
reason: Optional[str] = None
|
|
30
|
+
plan: Optional[str] = None
|
|
31
|
+
expires_at: Optional[str] = None
|
|
32
|
+
test: bool = False
|
|
33
|
+
offline: bool = False
|
|
34
|
+
activations: Optional[dict] = field(default=None)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _default_dir(app_name):
|
|
38
|
+
if os.name == "nt":
|
|
39
|
+
base = Path(os.environ.get("APPDATA", Path.home()))
|
|
40
|
+
else:
|
|
41
|
+
base = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config"))
|
|
42
|
+
return base / app_name
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _parse_time(value):
|
|
46
|
+
if not value:
|
|
47
|
+
return None
|
|
48
|
+
return datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp()
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _b64url(data):
|
|
52
|
+
return base64.urlsafe_b64decode(data + "=" * (-len(data) % 4))
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def verify_signed(signed, public_keys):
|
|
56
|
+
"""Prüft signed["signature"] über den exakten String signed["payload"]. Payload-Dict oder None."""
|
|
57
|
+
if not isinstance(signed, dict) or not isinstance(signed.get("payload"), str):
|
|
58
|
+
return None
|
|
59
|
+
jwk = next((k for k in public_keys or [] if k.get("kid") == signed.get("kid")), None)
|
|
60
|
+
if not jwk:
|
|
61
|
+
return None
|
|
62
|
+
try:
|
|
63
|
+
from cryptography.exceptions import InvalidSignature
|
|
64
|
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
|
|
65
|
+
except ImportError:
|
|
66
|
+
return None # pip install "monemee[offline]" für Offline-Prüfung
|
|
67
|
+
try:
|
|
68
|
+
Ed25519PublicKey.from_public_bytes(_b64url(jwk["x"])).verify(_b64url(signed["signature"]), signed["payload"].encode("utf-8"))
|
|
69
|
+
return json.loads(signed["payload"])
|
|
70
|
+
except (InvalidSignature, ValueError, KeyError):
|
|
71
|
+
return None
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class License:
|
|
75
|
+
"""Lizenz eines Produkts auf diesem Gerät.
|
|
76
|
+
|
|
77
|
+
License(product_id=123, grace_days=7, app_name=None, base_url="https://monemee.com")
|
|
78
|
+
"""
|
|
79
|
+
|
|
80
|
+
def __init__(self, product_id, base_url=None, grace_days=7, app_name=None, store_dir=None,
|
|
81
|
+
device_id=None, device_name=None, public_keys=None, now=None, timeout=8):
|
|
82
|
+
self.product_id = int(product_id)
|
|
83
|
+
if self.product_id <= 0:
|
|
84
|
+
raise MonemeeError("product_id fehlt", code="CONFIG")
|
|
85
|
+
self.base_url = (base_url or os.environ.get("MONEMEE_BASE_URL") or "https://monemee.com").rstrip("/")
|
|
86
|
+
self.grace_seconds = grace_days * 86400
|
|
87
|
+
self.dir = Path(store_dir) if store_dir else _default_dir(app_name or "monemee-%d" % self.product_id)
|
|
88
|
+
self._device_id = device_id
|
|
89
|
+
self.device_name = device_name
|
|
90
|
+
self._keys = list(public_keys or []) + BUNDLED_PUBLIC_KEYS
|
|
91
|
+
self._now = now or time.time
|
|
92
|
+
self.timeout = timeout
|
|
93
|
+
|
|
94
|
+
# ---------- Speicher ----------
|
|
95
|
+
@property
|
|
96
|
+
def _file(self):
|
|
97
|
+
return self.dir / "license.json"
|
|
98
|
+
|
|
99
|
+
def _load(self):
|
|
100
|
+
try:
|
|
101
|
+
data = json.loads(self._file.read_text("utf-8"))
|
|
102
|
+
return data if isinstance(data, dict) else {}
|
|
103
|
+
except (OSError, ValueError):
|
|
104
|
+
return {}
|
|
105
|
+
|
|
106
|
+
def _save(self, data):
|
|
107
|
+
self.dir.mkdir(parents=True, exist_ok=True)
|
|
108
|
+
tmp = self._file.with_suffix(".tmp")
|
|
109
|
+
tmp.write_text(json.dumps(data), "utf-8")
|
|
110
|
+
try:
|
|
111
|
+
os.chmod(tmp, 0o600)
|
|
112
|
+
except OSError:
|
|
113
|
+
pass
|
|
114
|
+
tmp.replace(self._file)
|
|
115
|
+
|
|
116
|
+
def device_id(self):
|
|
117
|
+
if self._device_id:
|
|
118
|
+
return str(self._device_id)[:128]
|
|
119
|
+
data = self._load()
|
|
120
|
+
if not data.get("device"):
|
|
121
|
+
data["device"] = "d_" + secrets.token_hex(16)
|
|
122
|
+
self._save(data)
|
|
123
|
+
return data["device"]
|
|
124
|
+
|
|
125
|
+
# ---------- Netzwerk ----------
|
|
126
|
+
def _post(self, path, body):
|
|
127
|
+
res = _http.request("POST", "%s/api/v1/licenses/%s" % (self.base_url, path), body, timeout=self.timeout)
|
|
128
|
+
return (res or {}).get("data") or {}
|
|
129
|
+
|
|
130
|
+
def _add_keys(self, keys):
|
|
131
|
+
known = {k.get("kid") for k in self._keys}
|
|
132
|
+
for k in keys or []:
|
|
133
|
+
if isinstance(k, dict) and k.get("kid") and k.get("x") and k["kid"] not in known:
|
|
134
|
+
self._keys.append(k)
|
|
135
|
+
known.add(k["kid"])
|
|
136
|
+
|
|
137
|
+
def _ensure_keys(self, data, kid):
|
|
138
|
+
# Fetch keys only for a key ID we do not know yet (key rotation).
|
|
139
|
+
if any(k.get("kid") == kid for k in self._keys):
|
|
140
|
+
return
|
|
141
|
+
self._add_keys(data.get("keys"))
|
|
142
|
+
if any(k.get("kid") == kid for k in self._keys):
|
|
143
|
+
return
|
|
144
|
+
res = _http.request("GET", "%s/.well-known/monemee-license-keys.json" % self.base_url, timeout=self.timeout)
|
|
145
|
+
fetched = (res or {}).get("keys") or []
|
|
146
|
+
self._add_keys(fetched)
|
|
147
|
+
if fetched:
|
|
148
|
+
data["keys"] = fetched
|
|
149
|
+
self._save(data)
|
|
150
|
+
|
|
151
|
+
def _trusted(self, signed, key, device, max_age, data):
|
|
152
|
+
try:
|
|
153
|
+
self._ensure_keys(data, (signed or {}).get("kid"))
|
|
154
|
+
except MonemeeError:
|
|
155
|
+
pass
|
|
156
|
+
p = verify_signed(signed, self._keys)
|
|
157
|
+
if not p:
|
|
158
|
+
return None
|
|
159
|
+
if p.get("product_id") != self.product_id or p.get("key_sha256") != hashlib.sha256(key.encode()).hexdigest():
|
|
160
|
+
return None
|
|
161
|
+
if p.get("device_id") and p["device_id"] != device:
|
|
162
|
+
return None
|
|
163
|
+
issued = _parse_time(p.get("issued_at"))
|
|
164
|
+
now = self._now()
|
|
165
|
+
if issued is None or issued > now + 300 or now - issued > max_age:
|
|
166
|
+
return None
|
|
167
|
+
expires = _parse_time(p.get("expires_at"))
|
|
168
|
+
if expires is not None and expires < now:
|
|
169
|
+
return dict(p, valid=False, reason="expired")
|
|
170
|
+
return p
|
|
171
|
+
|
|
172
|
+
@staticmethod
|
|
173
|
+
def _result(d, **extra):
|
|
174
|
+
valid = bool(d.get("valid"))
|
|
175
|
+
return LicenseResult(valid=valid, reason=None if valid else d.get("reason"), plan=d.get("plan"),
|
|
176
|
+
expires_at=d.get("expires_at"), test=bool(d.get("test")), **extra)
|
|
177
|
+
|
|
178
|
+
# ---------- Öffentliche API ----------
|
|
179
|
+
def activate(self, key, device_name=None):
|
|
180
|
+
"""Schlüssel einmal aktivieren (bindet ihn an dieses Gerät)."""
|
|
181
|
+
key = re.sub(r"\s+", "", str(key or "")).upper()
|
|
182
|
+
if not KEY_RE.match(key):
|
|
183
|
+
raise MonemeeError("Schlüssel im Format MM-XXXX-XXXX-XXXX-XXXX eingeben", code="INVALID_KEY")
|
|
184
|
+
device = self.device_id()
|
|
185
|
+
body = {"key": key, "product_id": self.product_id, "device_id": device}
|
|
186
|
+
if device_name or self.device_name:
|
|
187
|
+
body["device_name"] = device_name or self.device_name
|
|
188
|
+
res = self._post("activate", body)
|
|
189
|
+
if res.get("valid"):
|
|
190
|
+
data = self._load()
|
|
191
|
+
data.update({"v": STORE_VERSION, "key": key, "signed": res.get("signed"), "checked_at": self._now()})
|
|
192
|
+
self._save(data)
|
|
193
|
+
return self._result(res, activations=res.get("activations"))
|
|
194
|
+
|
|
195
|
+
def check(self):
|
|
196
|
+
"""Gilt die Lizenz? Online prüfen, ohne Netz gilt die letzte signierte Antwort (grace_days)."""
|
|
197
|
+
data = self._load()
|
|
198
|
+
key = data.get("key")
|
|
199
|
+
if not key:
|
|
200
|
+
return LicenseResult(valid=False, reason="not_activated")
|
|
201
|
+
device = self.device_id()
|
|
202
|
+
try:
|
|
203
|
+
res = self._post("validate", {"key": key, "product_id": self.product_id, "device_id": device})
|
|
204
|
+
except MonemeeError as err:
|
|
205
|
+
if err.code not in ("NETWORK", "SERVER"):
|
|
206
|
+
raise
|
|
207
|
+
p = self._trusted(data.get("signed"), key, device, self.grace_seconds, data) if data.get("signed") else None
|
|
208
|
+
if not p:
|
|
209
|
+
return LicenseResult(valid=False, reason="offline", offline=True)
|
|
210
|
+
return self._result(p, offline=True)
|
|
211
|
+
|
|
212
|
+
if res.get("signed"):
|
|
213
|
+
p = self._trusted(res["signed"], key, device, 600, data)
|
|
214
|
+
if p and bool(p.get("valid")) == bool(res.get("valid")):
|
|
215
|
+
data.update({"signed": res["signed"], "checked_at": self._now()})
|
|
216
|
+
self._save(data)
|
|
217
|
+
elif self._keys:
|
|
218
|
+
return LicenseResult(valid=False, reason="invalid_signature")
|
|
219
|
+
if not res.get("valid") and res.get("reason") in ("revoked", "not_found", "product_mismatch"):
|
|
220
|
+
for k in ("key", "signed", "checked_at"):
|
|
221
|
+
data.pop(k, None)
|
|
222
|
+
self._save(data)
|
|
223
|
+
return self._result(res, activations=res.get("activations"))
|
|
224
|
+
|
|
225
|
+
def deactivate(self):
|
|
226
|
+
"""Gerät freigeben und gespeicherten Schlüssel vergessen."""
|
|
227
|
+
data = self._load()
|
|
228
|
+
key = data.get("key")
|
|
229
|
+
if not key:
|
|
230
|
+
return False
|
|
231
|
+
try:
|
|
232
|
+
res = self._post("deactivate", {"key": key, "product_id": self.product_id, "device_id": self.device_id()})
|
|
233
|
+
finally:
|
|
234
|
+
for k in ("key", "signed", "checked_at"):
|
|
235
|
+
data.pop(k, None)
|
|
236
|
+
self._save(data)
|
|
237
|
+
return bool(res.get("deactivated"))
|
|
238
|
+
|
|
239
|
+
@property
|
|
240
|
+
def stored_key(self):
|
|
241
|
+
return self._load().get("key")
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import hashlib
|
|
2
|
+
import hmac
|
|
3
|
+
import json
|
|
4
|
+
import time
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def verify_webhook(raw_body, signature_header, secret, tolerance_seconds=300, now=None):
|
|
8
|
+
"""Prüft einen Monemee-Webhook und gibt das Event zurück.
|
|
9
|
+
|
|
10
|
+
raw_body: der UNVERÄNDERTE Body (bytes oder str)
|
|
11
|
+
signature_header: Wert von "Monemee-Signature" (t=<unix>,v1=<hex>)
|
|
12
|
+
Wirft ValueError bei fehlender, falscher oder zu alter Signatur.
|
|
13
|
+
"""
|
|
14
|
+
if not secret:
|
|
15
|
+
raise ValueError("Webhook-Secret fehlt (MONEMEE_WEBHOOK_SECRET)")
|
|
16
|
+
if not signature_header:
|
|
17
|
+
raise ValueError("Monemee-Signature-Header fehlt")
|
|
18
|
+
parts = dict(p.strip().split("=", 1) for p in signature_header.split(",") if "=" in p)
|
|
19
|
+
try:
|
|
20
|
+
t = int(parts.get("t", ""))
|
|
21
|
+
except ValueError:
|
|
22
|
+
raise ValueError("Signatur hat ein ungültiges Format")
|
|
23
|
+
v1 = parts.get("v1", "")
|
|
24
|
+
if len(v1) != 64:
|
|
25
|
+
raise ValueError("Signatur hat ein ungültiges Format")
|
|
26
|
+
if abs(int(now if now is not None else time.time()) - t) > tolerance_seconds:
|
|
27
|
+
raise ValueError("Signatur ist zu alt")
|
|
28
|
+
body = raw_body.decode("utf-8") if isinstance(raw_body, (bytes, bytearray)) else str(raw_body)
|
|
29
|
+
expected = hmac.new(secret.encode("utf-8"), ("%d.%s" % (t, body)).encode("utf-8"), hashlib.sha256).hexdigest()
|
|
30
|
+
if not hmac.compare_digest(expected, v1):
|
|
31
|
+
raise ValueError("Signatur stimmt nicht")
|
|
32
|
+
return json.loads(body)
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import base64
|
|
2
|
+
import hashlib
|
|
3
|
+
import hmac
|
|
4
|
+
import json
|
|
5
|
+
import sys
|
|
6
|
+
import tempfile
|
|
7
|
+
import threading
|
|
8
|
+
import time
|
|
9
|
+
import unittest
|
|
10
|
+
from datetime import datetime, timezone
|
|
11
|
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
|
|
15
|
+
|
|
16
|
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey # noqa: E402
|
|
17
|
+
from cryptography.hazmat.primitives import serialization # noqa: E402
|
|
18
|
+
|
|
19
|
+
from monemee import App, License, MonemeeError, verify_webhook # noqa: E402
|
|
20
|
+
|
|
21
|
+
PRIV = Ed25519PrivateKey.generate()
|
|
22
|
+
X = base64.urlsafe_b64encode(PRIV.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw)).rstrip(b"=").decode()
|
|
23
|
+
KEY = "MM-A7K2-9FQ3-XT8M-2B4C"
|
|
24
|
+
PID = 42
|
|
25
|
+
SECRET = "mmapp_test_" + "a" * 32
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def signed(fields):
|
|
29
|
+
payload = dict(v=1, key_sha256=hashlib.sha256(KEY.encode()).hexdigest(), product_id=PID, device_id=None,
|
|
30
|
+
valid=True, reason=None, plan="pro", expires_at=None, test=False,
|
|
31
|
+
issued_at=datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"))
|
|
32
|
+
payload.update(fields)
|
|
33
|
+
text = json.dumps(payload, sort_keys=True, separators=(",", ":"))
|
|
34
|
+
sig = base64.urlsafe_b64encode(PRIV.sign(text.encode())).rstrip(b"=").decode()
|
|
35
|
+
return {"payload": text, "signature": sig, "kid": "test-1", "alg": "EdDSA"}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class Fake:
|
|
39
|
+
valid = True
|
|
40
|
+
reason = None
|
|
41
|
+
access = False
|
|
42
|
+
calls = []
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class Handler(BaseHTTPRequestHandler):
|
|
46
|
+
def log_message(self, *a):
|
|
47
|
+
pass
|
|
48
|
+
|
|
49
|
+
def _json(self, obj, status=200):
|
|
50
|
+
body = json.dumps(obj).encode()
|
|
51
|
+
self.send_response(status)
|
|
52
|
+
self.send_header("Content-Type", "application/json")
|
|
53
|
+
self.send_header("Content-Length", str(len(body)))
|
|
54
|
+
self.end_headers()
|
|
55
|
+
self.wfile.write(body)
|
|
56
|
+
|
|
57
|
+
def do_GET(self):
|
|
58
|
+
if self.path.endswith("monemee-license-keys.json"):
|
|
59
|
+
return self._json({"keys": [{"kid": "test-1", "x": X, "kty": "OKP", "crv": "Ed25519"}]})
|
|
60
|
+
if self.path == "/api/v1/apps/me":
|
|
61
|
+
return self._json({"success": True, "data": {"product_id": 7}})
|
|
62
|
+
self._json({}, 404)
|
|
63
|
+
|
|
64
|
+
def do_POST(self):
|
|
65
|
+
body = json.loads(self.rfile.read(int(self.headers["Content-Length"])) or b"{}")
|
|
66
|
+
Fake.calls.append((self.path, body, self.headers.get("Authorization")))
|
|
67
|
+
if self.path.startswith("/api/v1/licenses/"):
|
|
68
|
+
if self.path.endswith("deactivate"):
|
|
69
|
+
return self._json({"success": True, "data": {"deactivated": True}})
|
|
70
|
+
data = {"valid": Fake.valid, "reason": None if Fake.valid else Fake.reason, "product_id": PID, "plan": "pro"}
|
|
71
|
+
data["signed"] = signed({"device_id": body.get("device_id"), "valid": Fake.valid, "reason": data["reason"]})
|
|
72
|
+
return self._json({"success": True, "data": data})
|
|
73
|
+
if self.path == "/api/v1/apps/access":
|
|
74
|
+
return self._json({"success": True, "data": {"access": Fake.access, "reason": None if Fake.access else "no_license", "ref": body["ref"]}})
|
|
75
|
+
if self.path == "/api/v1/apps/claim":
|
|
76
|
+
Fake.access = True
|
|
77
|
+
return self._json({"success": True, "data": {"access": True, "plan": "pro", "ref": body["ref"]}})
|
|
78
|
+
if self.path == "/api/v1/apps/test-claim":
|
|
79
|
+
return self._json({"success": True, "data": {"redirectUrl": (body.get("return_url") or "https://x/r") + "?monemee_claim=mmc_t"}})
|
|
80
|
+
self._json({}, 404)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class Base(unittest.TestCase):
|
|
84
|
+
@classmethod
|
|
85
|
+
def setUpClass(cls):
|
|
86
|
+
cls.server = HTTPServer(("127.0.0.1", 0), Handler)
|
|
87
|
+
cls.base = "http://127.0.0.1:%d" % cls.server.server_address[1]
|
|
88
|
+
threading.Thread(target=cls.server.serve_forever, daemon=True).start()
|
|
89
|
+
|
|
90
|
+
@classmethod
|
|
91
|
+
def tearDownClass(cls):
|
|
92
|
+
cls.server.shutdown()
|
|
93
|
+
|
|
94
|
+
def setUp(self):
|
|
95
|
+
Fake.valid, Fake.reason, Fake.access, Fake.calls = True, None, False, []
|
|
96
|
+
self.dir = tempfile.mkdtemp()
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class LicenseTests(Base):
|
|
100
|
+
def lic(self, **kw):
|
|
101
|
+
return License(product_id=PID, base_url=kw.pop("base_url", self.base), store_dir=self.dir, **kw)
|
|
102
|
+
|
|
103
|
+
def test_activate_check_online(self):
|
|
104
|
+
lic = self.lic()
|
|
105
|
+
self.assertTrue(lic.activate(" mm-a7k2-9fq3-xt8m-2b4c ").valid)
|
|
106
|
+
self.assertEqual(Fake.calls[0][1]["key"], KEY)
|
|
107
|
+
r = lic.check()
|
|
108
|
+
self.assertTrue(r.valid)
|
|
109
|
+
self.assertEqual(r.plan, "pro")
|
|
110
|
+
self.assertFalse(r.offline)
|
|
111
|
+
self.assertEqual(lic.stored_key, KEY)
|
|
112
|
+
|
|
113
|
+
def test_offline_grace(self):
|
|
114
|
+
t = [time.time()]
|
|
115
|
+
lic = self.lic(now=lambda: t[0], grace_days=7)
|
|
116
|
+
lic.activate(KEY)
|
|
117
|
+
lic.check()
|
|
118
|
+
off = License(product_id=PID, base_url="http://127.0.0.1:1", store_dir=self.dir, now=lambda: t[0], timeout=1)
|
|
119
|
+
r = off.check()
|
|
120
|
+
self.assertTrue(r.valid)
|
|
121
|
+
self.assertTrue(r.offline)
|
|
122
|
+
t[0] += 8 * 86400
|
|
123
|
+
self.assertEqual(off.check().reason, "offline")
|
|
124
|
+
|
|
125
|
+
def test_tampered_store_rejected_offline(self):
|
|
126
|
+
lic = self.lic()
|
|
127
|
+
lic.activate(KEY)
|
|
128
|
+
lic.check()
|
|
129
|
+
f = Path(self.dir) / "license.json"
|
|
130
|
+
data = json.loads(f.read_text())
|
|
131
|
+
data["signed"]["payload"] = data["signed"]["payload"].replace('"pro"', '"elite"')
|
|
132
|
+
f.write_text(json.dumps(data))
|
|
133
|
+
off = License(product_id=PID, base_url="http://127.0.0.1:1", store_dir=self.dir, timeout=1)
|
|
134
|
+
self.assertFalse(off.check().valid)
|
|
135
|
+
|
|
136
|
+
def test_revoked_forgets_key(self):
|
|
137
|
+
lic = self.lic()
|
|
138
|
+
lic.activate(KEY)
|
|
139
|
+
Fake.valid, Fake.reason = False, "revoked"
|
|
140
|
+
r = lic.check()
|
|
141
|
+
self.assertEqual((r.valid, r.reason), (False, "revoked"))
|
|
142
|
+
self.assertIsNone(lic.stored_key)
|
|
143
|
+
self.assertEqual(lic.check().reason, "not_activated")
|
|
144
|
+
|
|
145
|
+
def test_bad_format_and_deactivate(self):
|
|
146
|
+
lic = self.lic()
|
|
147
|
+
with self.assertRaises(MonemeeError):
|
|
148
|
+
lic.activate("quatsch")
|
|
149
|
+
self.assertEqual(Fake.calls, [])
|
|
150
|
+
lic.activate(KEY)
|
|
151
|
+
self.assertTrue(lic.deactivate())
|
|
152
|
+
self.assertIsNone(lic.stored_key)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
class AppTests(Base):
|
|
156
|
+
def app(self, **kw):
|
|
157
|
+
return App(app_secret=SECRET, base_url=self.base, **kw)
|
|
158
|
+
|
|
159
|
+
def test_config_error(self):
|
|
160
|
+
with self.assertRaises(MonemeeError):
|
|
161
|
+
App(app_secret="falsch")
|
|
162
|
+
|
|
163
|
+
def test_access_cache_unlock(self):
|
|
164
|
+
app = self.app()
|
|
165
|
+
self.assertFalse(app.has_access("u1"))
|
|
166
|
+
self.assertFalse(app.has_access("u1"))
|
|
167
|
+
self.assertEqual(sum(1 for c in Fake.calls if c[0].endswith("/access")), 1)
|
|
168
|
+
self.assertEqual(Fake.calls[0][2], "Bearer " + SECRET)
|
|
169
|
+
r = app.unlock("u1", claim="mmc_x")
|
|
170
|
+
self.assertTrue(r.access)
|
|
171
|
+
self.assertTrue(app.has_access("u1"))
|
|
172
|
+
|
|
173
|
+
def test_buy_and_test_urls(self):
|
|
174
|
+
app = self.app()
|
|
175
|
+
self.assertEqual(app.buy_url("u 1".replace(" ", "_")), self.base + "/buy/7?ref=u_1")
|
|
176
|
+
self.assertEqual(app.test_buy_url("u1", "http://localhost:8000/pro"), "http://localhost:8000/pro?monemee_claim=mmc_t")
|
|
177
|
+
with self.assertRaises(MonemeeError):
|
|
178
|
+
app.has_access("mit leerzeichen")
|
|
179
|
+
|
|
180
|
+
def test_webhook(self):
|
|
181
|
+
app = self.app(webhook_secret="whsec_x")
|
|
182
|
+
app._cache["u1"] = (None, time.time() + 100)
|
|
183
|
+
body = json.dumps({"event": "license.revoked", "data": {"external_ref": "u1"}})
|
|
184
|
+
t = int(time.time())
|
|
185
|
+
sig = "t=%d,v1=%s" % (t, hmac.new(b"whsec_x", ("%d.%s" % (t, body)).encode(), hashlib.sha256).hexdigest())
|
|
186
|
+
self.assertEqual(app.handle_webhook(body, sig)["event"], "license.revoked")
|
|
187
|
+
self.assertNotIn("u1", app._cache)
|
|
188
|
+
with self.assertRaises(ValueError):
|
|
189
|
+
verify_webhook(body, sig.replace("v1=", "v1=0"), "whsec_x")
|
|
190
|
+
with self.assertRaises(ValueError):
|
|
191
|
+
verify_webhook(body, sig, "whsec_x", now=t + 1000)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
if __name__ == "__main__":
|
|
195
|
+
unittest.main()
|