bitsopay 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.
- bitsopay/__init__.py +64 -0
- bitsopay/__main__.py +6 -0
- bitsopay/cli.py +245 -0
- bitsopay/exceptions.py +31 -0
- bitsopay/link.py +122 -0
- bitsopay/models.py +57 -0
- bitsopay/page.py +133 -0
- bitsopay/py.typed +0 -0
- bitsopay/qr.py +87 -0
- bitsopay/ratelimit.py +69 -0
- bitsopay/server.py +520 -0
- bitsopay/session.py +67 -0
- bitsopay/shortlink.py +172 -0
- bitsopay/stateless.py +181 -0
- bitsopay/store.py +277 -0
- bitsopay/upi.py +47 -0
- bitsopay/validators.py +86 -0
- bitsopay-0.1.0.dist-info/METADATA +234 -0
- bitsopay-0.1.0.dist-info/RECORD +23 -0
- bitsopay-0.1.0.dist-info/WHEEL +5 -0
- bitsopay-0.1.0.dist-info/entry_points.txt +2 -0
- bitsopay-0.1.0.dist-info/licenses/LICENSE +21 -0
- bitsopay-0.1.0.dist-info/top_level.txt +1 -0
bitsopay/qr.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""QR code rendering for UPI payments (powered by ``segno``, pure Python)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import io
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Union
|
|
8
|
+
|
|
9
|
+
import segno
|
|
10
|
+
|
|
11
|
+
from .models import UPIPayment
|
|
12
|
+
|
|
13
|
+
_ERROR_LEVELS = {"L", "M", "Q", "H"}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _make(payment: UPIPayment, error: str) -> segno.QRCode:
|
|
17
|
+
error = error.upper()
|
|
18
|
+
if error not in _ERROR_LEVELS:
|
|
19
|
+
raise ValueError(f"error must be one of {sorted(_ERROR_LEVELS)}")
|
|
20
|
+
return segno.make(payment.uri, error=error, micro=False)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def qr_png(payment: UPIPayment, *, scale: int = 10, border: int = 4, error: str = "M") -> bytes:
|
|
24
|
+
"""Return the QR code as PNG bytes."""
|
|
25
|
+
buf = io.BytesIO()
|
|
26
|
+
_make(payment, error).save(buf, kind="png", scale=scale, border=border)
|
|
27
|
+
return buf.getvalue()
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def qr_svg(payment: UPIPayment, *, scale: int = 10, border: int = 4, error: str = "M") -> str:
|
|
31
|
+
"""Return the QR code as an SVG document string."""
|
|
32
|
+
buf = io.BytesIO()
|
|
33
|
+
_make(payment, error).save(buf, kind="svg", scale=scale, border=border, xmldecl=False)
|
|
34
|
+
return buf.getvalue().decode("utf-8")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def qr_data_uri(payment: UPIPayment, *, scale: int = 10, border: int = 4, error: str = "M") -> str:
|
|
38
|
+
"""Return a ``data:image/png;base64,...`` URI, ready for an ``<img src>``."""
|
|
39
|
+
return _make(payment, error).png_data_uri(scale=scale, border=border)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def save_qr(
|
|
43
|
+
payment: UPIPayment,
|
|
44
|
+
path: Union[str, Path],
|
|
45
|
+
*,
|
|
46
|
+
scale: int = 10,
|
|
47
|
+
border: int = 4,
|
|
48
|
+
error: str = "M",
|
|
49
|
+
) -> Path:
|
|
50
|
+
"""Write the QR code to ``path``; format is chosen by extension (.png / .svg)."""
|
|
51
|
+
target = Path(path)
|
|
52
|
+
ext = target.suffix.lower()
|
|
53
|
+
if ext not in {".png", ".svg"}:
|
|
54
|
+
raise ValueError("Output path must end in .png or .svg")
|
|
55
|
+
_make(payment, error).save(str(target), scale=scale, border=border)
|
|
56
|
+
return target
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
# --- QR codes for arbitrary text (used for expiring session QR codes) -------
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _make_text(text: str, error: str) -> segno.QRCode:
|
|
63
|
+
error = error.upper()
|
|
64
|
+
if error not in _ERROR_LEVELS:
|
|
65
|
+
raise ValueError(f"error must be one of {sorted(_ERROR_LEVELS)}")
|
|
66
|
+
return segno.make(text, error=error, micro=False)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def text_qr_png(text: str, *, scale: int = 10, border: int = 4, error: str = "M") -> bytes:
|
|
70
|
+
"""PNG bytes of a QR code encoding ``text`` (e.g. a payment link URL)."""
|
|
71
|
+
buf = io.BytesIO()
|
|
72
|
+
_make_text(text, error).save(buf, kind="png", scale=scale, border=border)
|
|
73
|
+
return buf.getvalue()
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def text_qr_svg(text: str, *, scale: int = 10, border: int = 4, error: str = "M") -> str:
|
|
77
|
+
buf = io.BytesIO()
|
|
78
|
+
_make_text(text, error).save(buf, kind="svg", scale=scale, border=border, xmldecl=False)
|
|
79
|
+
return buf.getvalue().decode("utf-8")
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def save_text_qr(text: str, path: Union[str, Path], *, scale: int = 10, border: int = 4, error: str = "M") -> Path:
|
|
83
|
+
target = Path(path)
|
|
84
|
+
if target.suffix.lower() not in {".png", ".svg"}:
|
|
85
|
+
raise ValueError("Output path must end in .png or .svg")
|
|
86
|
+
_make_text(text, error).save(str(target), scale=scale, border=border)
|
|
87
|
+
return target
|
bitsopay/ratelimit.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""A tiny in-memory limiter used to slow down brute-forcing of the admin token.
|
|
2
|
+
|
|
3
|
+
It counts *failures* per client key inside a sliding window. State is per process: with several
|
|
4
|
+
gunicorn workers each worker keeps its own counters, so the effective limit is
|
|
5
|
+
``max_failures * workers``. For a hard global limit, rate-limit at your reverse proxy as well
|
|
6
|
+
(see ``docs/deployment.md``).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import threading
|
|
12
|
+
import time
|
|
13
|
+
from collections import deque
|
|
14
|
+
from typing import Callable, Deque, Dict
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class FailureLimiter:
|
|
18
|
+
"""Block a key after ``max_failures`` failures within ``window`` seconds."""
|
|
19
|
+
|
|
20
|
+
def __init__(
|
|
21
|
+
self,
|
|
22
|
+
max_failures: int = 10,
|
|
23
|
+
window: float = 60.0,
|
|
24
|
+
*,
|
|
25
|
+
clock: Callable[[], float] = time.time,
|
|
26
|
+
max_keys: int = 10_000,
|
|
27
|
+
) -> None:
|
|
28
|
+
if max_failures < 1 or window <= 0:
|
|
29
|
+
raise ValueError("max_failures must be >= 1 and window > 0")
|
|
30
|
+
self.max_failures = max_failures
|
|
31
|
+
self.window = window
|
|
32
|
+
self._clock = clock
|
|
33
|
+
self._max_keys = max_keys
|
|
34
|
+
self._hits: Dict[str, Deque[float]] = {}
|
|
35
|
+
self._lock = threading.Lock()
|
|
36
|
+
|
|
37
|
+
def _trim(self, key: str, now: float) -> Deque[float]:
|
|
38
|
+
hits = self._hits.get(key)
|
|
39
|
+
if hits is None:
|
|
40
|
+
return deque()
|
|
41
|
+
while hits and hits[0] <= now - self.window:
|
|
42
|
+
hits.popleft()
|
|
43
|
+
if not hits:
|
|
44
|
+
self._hits.pop(key, None)
|
|
45
|
+
return hits
|
|
46
|
+
|
|
47
|
+
def retry_after(self, key: str) -> int:
|
|
48
|
+
"""Seconds until ``key`` may try again; ``0`` if it is not blocked."""
|
|
49
|
+
with self._lock:
|
|
50
|
+
now = self._clock()
|
|
51
|
+
hits = self._trim(key, now)
|
|
52
|
+
if len(hits) < self.max_failures:
|
|
53
|
+
return 0
|
|
54
|
+
return max(1, int(hits[0] + self.window - now) + 1)
|
|
55
|
+
|
|
56
|
+
def record_failure(self, key: str) -> None:
|
|
57
|
+
with self._lock:
|
|
58
|
+
now = self._clock()
|
|
59
|
+
if key not in self._hits and len(self._hits) >= self._max_keys:
|
|
60
|
+
# bound memory under a flood of distinct keys: drop expired entries first
|
|
61
|
+
for known in list(self._hits): # snapshot: _trim() removes emptied keys
|
|
62
|
+
self._trim(known, now)
|
|
63
|
+
if len(self._hits) >= self._max_keys:
|
|
64
|
+
self._hits.pop(next(iter(self._hits)))
|
|
65
|
+
self._hits.setdefault(key, deque()).append(now)
|
|
66
|
+
|
|
67
|
+
def reset(self, key: str) -> None:
|
|
68
|
+
with self._lock:
|
|
69
|
+
self._hits.pop(key, None)
|
bitsopay/server.py
ADDED
|
@@ -0,0 +1,520 @@
|
|
|
1
|
+
"""A dependency-free WSGI app for Bitsopay payment links.
|
|
2
|
+
|
|
3
|
+
Production::
|
|
4
|
+
|
|
5
|
+
export BITSOPAY_DB=/var/lib/bitsopay/payments.db
|
|
6
|
+
export BITSOPAY_ADMIN_TOKEN="a-long-random-token" # merchant API (>= 16 chars)
|
|
7
|
+
export BITSOPAY_BASE_URL=https://pay.example.com # public root URL
|
|
8
|
+
gunicorn "bitsopay.server:create_app()"
|
|
9
|
+
|
|
10
|
+
Public routes (short links; need a store)
|
|
11
|
+
-----------------------------------------
|
|
12
|
+
``GET /p/<ref>`` payment page (QR + UPI app buttons + countdown)
|
|
13
|
+
``GET /p/<ref>/qr.png`` UPI QR code, ``/qr.svg`` for SVG
|
|
14
|
+
``GET /p/<ref>/status`` ``{"reference", "status", "expires_at"}`` (no amount / UPI ID)
|
|
15
|
+
|
|
16
|
+
Merchant API (``Authorization: Bearer <BITSOPAY_ADMIN_TOKEN>``)
|
|
17
|
+
---------------------------------------------------------------
|
|
18
|
+
``POST /api/payments`` create ``{"upi_id","payee_name","amount","note","expires_in"}``
|
|
19
|
+
``GET /api/payments?status=&limit=`` history
|
|
20
|
+
``GET /api/payments/<ref>`` one record
|
|
21
|
+
``POST /api/payments/<ref>/paid`` mark paid after you verified it ``{"note": "..."}``
|
|
22
|
+
``POST /api/payments/<ref>/cancel`` disable the link
|
|
23
|
+
|
|
24
|
+
Database-free mode: set ``BITSOPAY_SECRET``, ``BITSOPAY_UPI_ID`` and ``BITSOPAY_PAYEE_NAME`` (no
|
|
25
|
+
``BITSOPAY_DB``); ``/p/<id>`` links then carry their own encrypted amount + expiry, and
|
|
26
|
+
``POST /api/payments`` creates them.
|
|
27
|
+
|
|
28
|
+
Legacy signed links (``BITSOPAY_SECRET``): ``/pay``, ``/qr.png``, ``/qr.svg``.
|
|
29
|
+
|
|
30
|
+
Probes: ``/health`` (process is up) and ``/ready`` (the store answers).
|
|
31
|
+
|
|
32
|
+
Other environment variables: ``BITSOPAY_TRUST_PROXY=1`` (read the client IP and scheme from
|
|
33
|
+
``X-Forwarded-*``; only behind a proxy you control) and ``BITSOPAY_LOG_LEVEL``.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
from __future__ import annotations
|
|
37
|
+
|
|
38
|
+
import hmac
|
|
39
|
+
import json
|
|
40
|
+
import logging
|
|
41
|
+
import os
|
|
42
|
+
import re
|
|
43
|
+
import secrets
|
|
44
|
+
import time
|
|
45
|
+
from typing import Any, Callable, Dict, Iterable, List, NamedTuple, Optional, Tuple, Union
|
|
46
|
+
from urllib.parse import parse_qs
|
|
47
|
+
|
|
48
|
+
from .exceptions import (
|
|
49
|
+
InvalidStateError,
|
|
50
|
+
LinkExpiredError,
|
|
51
|
+
NotFoundError,
|
|
52
|
+
SignatureError,
|
|
53
|
+
ValidationError,
|
|
54
|
+
)
|
|
55
|
+
from .link import verify_payment_link
|
|
56
|
+
from .page import render_message_page, render_payment_page
|
|
57
|
+
from .qr import qr_png, qr_svg
|
|
58
|
+
from .ratelimit import FailureLimiter
|
|
59
|
+
from .shortlink import PaymentLinks
|
|
60
|
+
from .stateless import StatelessLinks
|
|
61
|
+
from .store import EXPIRED, PAID, PENDING, PaymentStore, SQLiteStore
|
|
62
|
+
|
|
63
|
+
log = logging.getLogger("bitsopay.server")
|
|
64
|
+
|
|
65
|
+
Headers = List[Tuple[str, str]]
|
|
66
|
+
Environ = Dict[str, Any]
|
|
67
|
+
StartResponse = Callable[..., Any]
|
|
68
|
+
WSGIApp = Callable[[Environ, StartResponse], Iterable[bytes]]
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class BitsoPayApp:
|
|
72
|
+
"""The WSGI callable returned by :func:`create_app`.
|
|
73
|
+
|
|
74
|
+
Use it like any WSGI app. Call :meth:`close` (or use ``with``) to release the SQLite
|
|
75
|
+
connection that :func:`create_app` opened from ``$BITSOPAY_DB``; a store you passed in
|
|
76
|
+
yourself is never closed for you.
|
|
77
|
+
"""
|
|
78
|
+
|
|
79
|
+
def __init__(self, handler: WSGIApp, owned_store: Optional[SQLiteStore] = None) -> None:
|
|
80
|
+
self._handler = handler
|
|
81
|
+
self._owned_store = owned_store
|
|
82
|
+
|
|
83
|
+
def __call__(self, environ: Environ, start_response: StartResponse) -> Iterable[bytes]:
|
|
84
|
+
return self._handler(environ, start_response)
|
|
85
|
+
|
|
86
|
+
def close(self) -> None:
|
|
87
|
+
if self._owned_store is not None:
|
|
88
|
+
self._owned_store.close()
|
|
89
|
+
self._owned_store = None
|
|
90
|
+
|
|
91
|
+
def __enter__(self) -> BitsoPayApp:
|
|
92
|
+
return self
|
|
93
|
+
|
|
94
|
+
def __exit__(self, *exc: object) -> None:
|
|
95
|
+
self.close()
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
_REF_RE = re.compile(r"^[A-Za-z0-9]{8,35}$")
|
|
99
|
+
_REQUEST_ID_RE = re.compile(r"^[A-Za-z0-9._\-]{1,64}$")
|
|
100
|
+
_MAX_BODY = 16 * 1024
|
|
101
|
+
_MAX_PAGE_LIMIT = 500
|
|
102
|
+
_TRUTHY = {"1", "true", "yes", "on"}
|
|
103
|
+
|
|
104
|
+
# The payment page is self-contained (inline style + script, data: QR image) and needs no network.
|
|
105
|
+
_CSP_PAGE = (
|
|
106
|
+
"default-src 'none'; img-src data:; style-src 'unsafe-inline'; script-src 'unsafe-inline'; "
|
|
107
|
+
"base-uri 'none'; form-action 'none'; frame-ancestors 'none'"
|
|
108
|
+
)
|
|
109
|
+
_CSP_STRICT = "default-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'"
|
|
110
|
+
_SECURITY_HEADERS: Headers = [
|
|
111
|
+
("X-Content-Type-Options", "nosniff"),
|
|
112
|
+
("Referrer-Policy", "no-referrer"),
|
|
113
|
+
("X-Frame-Options", "DENY"),
|
|
114
|
+
("Cache-Control", "no-store"),
|
|
115
|
+
("Cross-Origin-Opener-Policy", "same-origin"),
|
|
116
|
+
("Cross-Origin-Resource-Policy", "same-origin"),
|
|
117
|
+
("Permissions-Policy", "camera=(), microphone=(), geolocation=(), payment=()"),
|
|
118
|
+
]
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
class _Resp(NamedTuple):
|
|
122
|
+
status: str
|
|
123
|
+
body: bytes
|
|
124
|
+
ctype: str
|
|
125
|
+
extra: Tuple[Tuple[str, str], ...] = ()
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _text(status: str, message: str, extra: Optional[Headers] = None) -> _Resp:
|
|
129
|
+
return _Resp(status, message.encode("utf-8"), "text/plain; charset=utf-8", tuple(extra or ()))
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _html(status: str, html: str) -> _Resp:
|
|
133
|
+
return _Resp(status, html.encode("utf-8"), "text/html; charset=utf-8")
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _json(status: str, obj: Any, extra: Optional[Headers] = None) -> _Resp:
|
|
137
|
+
return _Resp(status, json.dumps(obj).encode("utf-8"), "application/json", tuple(extra or ()))
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _query_dict(qs: str) -> Dict[str, str]:
|
|
141
|
+
return {k: v[0] for k, v in parse_qs(qs).items() if v}
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _int_param(params: Dict[str, str], name: str, default: int, lo: int, hi: int) -> int:
|
|
145
|
+
raw = params.get(name)
|
|
146
|
+
if raw is None:
|
|
147
|
+
return default
|
|
148
|
+
try:
|
|
149
|
+
value = int(raw)
|
|
150
|
+
except ValueError:
|
|
151
|
+
raise ValidationError(f"{name} must be an integer") from None
|
|
152
|
+
if not lo <= value <= hi:
|
|
153
|
+
raise ValidationError(f"{name} must be between {lo} and {hi}")
|
|
154
|
+
return value
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _expires_in(data: Dict[str, Any], default: int = 86400) -> Optional[int]:
|
|
158
|
+
"""``expires_in`` from a JSON body: a positive integer, or ``null`` for no expiry."""
|
|
159
|
+
if "expires_in" not in data:
|
|
160
|
+
return default
|
|
161
|
+
value = data["expires_in"]
|
|
162
|
+
if value is None:
|
|
163
|
+
return None
|
|
164
|
+
if isinstance(value, bool) or not isinstance(value, int):
|
|
165
|
+
raise ValidationError("expires_in must be a whole number of seconds (or null)")
|
|
166
|
+
return int(value)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _read_json(environ: Environ) -> Dict[str, Any]:
|
|
170
|
+
try:
|
|
171
|
+
length = int(environ.get("CONTENT_LENGTH") or 0)
|
|
172
|
+
except ValueError:
|
|
173
|
+
raise ValidationError("Invalid Content-Length") from None
|
|
174
|
+
if length < 0:
|
|
175
|
+
raise ValidationError("Invalid Content-Length")
|
|
176
|
+
if length > _MAX_BODY:
|
|
177
|
+
raise _TooLarge()
|
|
178
|
+
if length == 0:
|
|
179
|
+
return {}
|
|
180
|
+
raw = environ["wsgi.input"].read(length)
|
|
181
|
+
try:
|
|
182
|
+
data = json.loads(raw.decode("utf-8"))
|
|
183
|
+
except (UnicodeDecodeError, json.JSONDecodeError):
|
|
184
|
+
raise ValidationError("Body must be valid JSON") from None
|
|
185
|
+
if not isinstance(data, dict):
|
|
186
|
+
raise ValidationError("Body must be a JSON object")
|
|
187
|
+
return data
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
class _TooLarge(Exception):
|
|
191
|
+
"""Request body over the size cap."""
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _configure_logging(level: str) -> None:
|
|
195
|
+
"""Send ``bitsopay.*`` logs to stderr at ``level`` (once), for gunicorn/Docker setups."""
|
|
196
|
+
logger = logging.getLogger("bitsopay")
|
|
197
|
+
try:
|
|
198
|
+
logger.setLevel(level.upper())
|
|
199
|
+
except ValueError:
|
|
200
|
+
raise ValueError(f"Invalid BITSOPAY_LOG_LEVEL: {level!r}") from None
|
|
201
|
+
if not logger.handlers:
|
|
202
|
+
handler = logging.StreamHandler()
|
|
203
|
+
handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(name)s %(message)s"))
|
|
204
|
+
logger.addHandler(handler)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def create_app(
|
|
208
|
+
secret: Optional[Union[str, bytes]] = None,
|
|
209
|
+
*,
|
|
210
|
+
store: Optional[PaymentStore] = None,
|
|
211
|
+
admin_token: Optional[str] = None,
|
|
212
|
+
base_url: Optional[str] = None,
|
|
213
|
+
stateless: Optional[StatelessLinks] = None,
|
|
214
|
+
clock: Callable[[], float] = time.time,
|
|
215
|
+
trust_proxy: Optional[bool] = None,
|
|
216
|
+
limiter: Optional[FailureLimiter] = None,
|
|
217
|
+
) -> BitsoPayApp:
|
|
218
|
+
"""Build the WSGI app.
|
|
219
|
+
|
|
220
|
+
* ``secret`` (``$BITSOPAY_SECRET``) enables legacy signed links
|
|
221
|
+
* ``store`` (``$BITSOPAY_DB`` = SQLite path) enables short links + merchant API
|
|
222
|
+
* ``admin_token`` (``$BITSOPAY_ADMIN_TOKEN``) enables the merchant API
|
|
223
|
+
* ``base_url`` (``$BITSOPAY_BASE_URL``) public root used in returned links
|
|
224
|
+
* ``stateless`` database-free short links; built from ``$BITSOPAY_UPI_ID`` +
|
|
225
|
+
``$BITSOPAY_PAYEE_NAME`` + ``$BITSOPAY_SECRET`` when those are set
|
|
226
|
+
* ``trust_proxy`` (``$BITSOPAY_TRUST_PROXY``) trust ``X-Forwarded-For/Proto`` (proxy you control)
|
|
227
|
+
* ``limiter`` failed-login limiter for the merchant API (default: 10 failures / minute / IP)
|
|
228
|
+
"""
|
|
229
|
+
env = os.environ
|
|
230
|
+
if env.get("BITSOPAY_LOG_LEVEL"):
|
|
231
|
+
_configure_logging(env["BITSOPAY_LOG_LEVEL"])
|
|
232
|
+
key = secret if secret is not None else (env.get("BITSOPAY_SECRET") or None)
|
|
233
|
+
owned_store: Optional[SQLiteStore] = None
|
|
234
|
+
if store is None and env.get("BITSOPAY_DB"):
|
|
235
|
+
store = owned_store = SQLiteStore(env["BITSOPAY_DB"])
|
|
236
|
+
env_upi, env_name = env.get("BITSOPAY_UPI_ID"), env.get("BITSOPAY_PAYEE_NAME")
|
|
237
|
+
if stateless is None and key and env_upi and env_name:
|
|
238
|
+
stateless = StatelessLinks(env_upi, env_name, key, clock=clock)
|
|
239
|
+
if not key and store is None and stateless is None:
|
|
240
|
+
raise RuntimeError(
|
|
241
|
+
"Set BITSOPAY_DB (short links), BITSOPAY_SECRET (+ BITSOPAY_UPI_ID and "
|
|
242
|
+
"BITSOPAY_PAYEE_NAME for database-free links), or pass store= / secret= / stateless= to create_app()"
|
|
243
|
+
)
|
|
244
|
+
if key is not None and len(key) < 16:
|
|
245
|
+
raise ValidationError("BITSOPAY_SECRET must be at least 16 characters")
|
|
246
|
+
token = admin_token if admin_token is not None else env.get("BITSOPAY_ADMIN_TOKEN")
|
|
247
|
+
if token and len(token) < 16:
|
|
248
|
+
raise ValueError("Admin token must be at least 16 characters")
|
|
249
|
+
public_base = (base_url or env.get("BITSOPAY_BASE_URL") or "").rstrip("/")
|
|
250
|
+
behind_proxy = trust_proxy if trust_proxy is not None else env.get("BITSOPAY_TRUST_PROXY", "").lower() in _TRUTHY
|
|
251
|
+
fail_limiter = limiter or FailureLimiter(clock=clock)
|
|
252
|
+
links = PaymentLinks(store, clock=clock) if store is not None else None
|
|
253
|
+
|
|
254
|
+
# ---- request helpers -----------------------------------------------
|
|
255
|
+
def client_ip(environ: Environ) -> str:
|
|
256
|
+
if behind_proxy:
|
|
257
|
+
forwarded = environ.get("HTTP_X_FORWARDED_FOR", "")
|
|
258
|
+
if forwarded: # the last hop is the one our own proxy appended
|
|
259
|
+
return forwarded.split(",")[-1].strip() or "unknown"
|
|
260
|
+
return str(environ.get("REMOTE_ADDR") or "unknown")
|
|
261
|
+
|
|
262
|
+
def scheme(environ: Environ) -> str:
|
|
263
|
+
if behind_proxy and environ.get("HTTP_X_FORWARDED_PROTO"):
|
|
264
|
+
return str(environ["HTTP_X_FORWARDED_PROTO"]).split(",")[-1].strip().lower()
|
|
265
|
+
return str(environ.get("wsgi.url_scheme", "https"))
|
|
266
|
+
|
|
267
|
+
# ---- short links ---------------------------------------------------
|
|
268
|
+
def pending(
|
|
269
|
+
environ: Environ,
|
|
270
|
+
sub: str,
|
|
271
|
+
payment: Any,
|
|
272
|
+
expires_at: Optional[int],
|
|
273
|
+
on_view: Optional[Callable[[], None]] = None,
|
|
274
|
+
) -> _Resp:
|
|
275
|
+
if sub == "":
|
|
276
|
+
if on_view is not None and environ.get("REQUEST_METHOD") == "GET":
|
|
277
|
+
on_view()
|
|
278
|
+
return _html("200 OK", render_payment_page(payment, expires_at))
|
|
279
|
+
if sub == "qr.png":
|
|
280
|
+
return _Resp("200 OK", qr_png(payment), "image/png")
|
|
281
|
+
return _Resp("200 OK", qr_svg(payment).encode("utf-8"), "image/svg+xml")
|
|
282
|
+
|
|
283
|
+
def gone(sub: str, ref: str, state: str) -> _Resp:
|
|
284
|
+
if sub != "":
|
|
285
|
+
return _text("410 Gone", f"Payment {state}")
|
|
286
|
+
msg = "This payment link has expired." if state == EXPIRED else "This payment link was cancelled."
|
|
287
|
+
return _html("410 Gone", render_message_page("Link unavailable", msg + " Please request a new one.", ref))
|
|
288
|
+
|
|
289
|
+
def short(environ: Environ, path: str) -> _Resp:
|
|
290
|
+
parts = path[len("/p/") :].split("/")
|
|
291
|
+
ref, sub = parts[0], (parts[1] if len(parts) > 1 else "")
|
|
292
|
+
if len(parts) > 2 or sub not in ("", "qr.png", "qr.svg", "status") or not _REF_RE.match(ref):
|
|
293
|
+
return _text("404 Not Found", "Not found")
|
|
294
|
+
rec = links.get(ref) if links is not None else None
|
|
295
|
+
if links is not None and rec is not None:
|
|
296
|
+
state = links.status_of(rec)
|
|
297
|
+
if sub == "status":
|
|
298
|
+
return _json("200 OK", {"reference": rec.reference, "status": state, "expires_at": rec.expires_at})
|
|
299
|
+
if state == PAID:
|
|
300
|
+
if sub != "":
|
|
301
|
+
return _text("410 Gone", "Payment paid")
|
|
302
|
+
return _html(
|
|
303
|
+
"200 OK",
|
|
304
|
+
render_message_page(
|
|
305
|
+
"Payment received", "This payment has been confirmed. Thank you!", rec.reference
|
|
306
|
+
),
|
|
307
|
+
)
|
|
308
|
+
if state != PENDING:
|
|
309
|
+
return gone(sub, rec.reference, state)
|
|
310
|
+
return pending(environ, sub, rec.to_payment(), rec.expires_at, lambda: links.record_view(ref))
|
|
311
|
+
if stateless is not None:
|
|
312
|
+
try:
|
|
313
|
+
payment, exp = stateless.decode(ref)
|
|
314
|
+
except LinkExpiredError:
|
|
315
|
+
if sub == "status":
|
|
316
|
+
return _json("200 OK", {"reference": ref.upper(), "status": EXPIRED, "expires_at": None})
|
|
317
|
+
return gone(sub, ref.upper(), EXPIRED)
|
|
318
|
+
except (SignatureError, ValidationError):
|
|
319
|
+
pass
|
|
320
|
+
else:
|
|
321
|
+
if sub == "status":
|
|
322
|
+
return _json("200 OK", {"reference": payment.reference, "status": PENDING, "expires_at": exp})
|
|
323
|
+
return pending(environ, sub, payment, exp)
|
|
324
|
+
if sub == "":
|
|
325
|
+
return _html("404 Not Found", render_message_page("Link not found", "This payment link is not valid."))
|
|
326
|
+
return _text("404 Not Found", "Not found")
|
|
327
|
+
|
|
328
|
+
# ---- merchant API --------------------------------------------------
|
|
329
|
+
def authorised(environ: Environ) -> Optional[_Resp]:
|
|
330
|
+
"""``None`` when the bearer token is right, otherwise the error response."""
|
|
331
|
+
ip = client_ip(environ)
|
|
332
|
+
wait = fail_limiter.retry_after(ip)
|
|
333
|
+
if wait:
|
|
334
|
+
return _json("429 Too Many Requests", {"error": "too many failed attempts"}, [("Retry-After", str(wait))])
|
|
335
|
+
auth = environ.get("HTTP_AUTHORIZATION", "")
|
|
336
|
+
supplied = auth[7:].strip() if auth.lower().startswith("bearer ") else ""
|
|
337
|
+
if not token or not hmac.compare_digest(supplied.encode("utf-8"), token.encode("utf-8")):
|
|
338
|
+
fail_limiter.record_failure(ip)
|
|
339
|
+
log.warning("admin auth failed ip=%s", ip)
|
|
340
|
+
return _json(
|
|
341
|
+
"401 Unauthorized", {"error": "unauthorized"}, [("WWW-Authenticate", 'Bearer realm="bitsopay"')]
|
|
342
|
+
)
|
|
343
|
+
fail_limiter.reset(ip)
|
|
344
|
+
return None
|
|
345
|
+
|
|
346
|
+
def admin(environ: Environ, path: str) -> _Resp:
|
|
347
|
+
if not token:
|
|
348
|
+
return _json("404 Not Found", {"error": "merchant API disabled"})
|
|
349
|
+
denied = authorised(environ)
|
|
350
|
+
if denied is not None:
|
|
351
|
+
return denied
|
|
352
|
+
method = environ.get("REQUEST_METHOD")
|
|
353
|
+
parts = [p for p in path[len("/api/") :].split("/") if p]
|
|
354
|
+
host = environ.get("HTTP_HOST") or environ.get("SERVER_NAME", "localhost")
|
|
355
|
+
base = public_base or f"{scheme(environ)}://{host}"
|
|
356
|
+
if links is None and not (parts == ["payments"] and method == "POST"):
|
|
357
|
+
return _json("501 Not Implemented", {"error": "history and status changes need a store (BITSOPAY_DB)"})
|
|
358
|
+
try:
|
|
359
|
+
if parts == ["payments"] and method == "POST":
|
|
360
|
+
data = _read_json(environ)
|
|
361
|
+
if links is None:
|
|
362
|
+
if stateless is None: # pragma: no cover - guarded by create_app
|
|
363
|
+
return _json("501 Not Implemented", {"error": "no link backend configured"})
|
|
364
|
+
sl = stateless.create(data.get("amount"), expires_in=_expires_in(data), base_url=base)
|
|
365
|
+
return _json(
|
|
366
|
+
"201 Created",
|
|
367
|
+
{
|
|
368
|
+
"reference": sl.reference,
|
|
369
|
+
"status": PENDING,
|
|
370
|
+
"url": sl.url,
|
|
371
|
+
"amount": None if sl.amount is None else f"{sl.amount:.2f}",
|
|
372
|
+
"expires_at": sl.expires_at,
|
|
373
|
+
},
|
|
374
|
+
)
|
|
375
|
+
link = links.create(
|
|
376
|
+
data.get("upi_id", ""),
|
|
377
|
+
data.get("payee_name", ""),
|
|
378
|
+
data.get("amount"),
|
|
379
|
+
note=data.get("note"),
|
|
380
|
+
merchant_code=data.get("merchant_code"),
|
|
381
|
+
expires_in=_expires_in(data),
|
|
382
|
+
base_url=base,
|
|
383
|
+
)
|
|
384
|
+
out = link.record.to_dict(clock())
|
|
385
|
+
out["url"] = link.url
|
|
386
|
+
return _json("201 Created", out)
|
|
387
|
+
if links is None: # pragma: no cover - guarded above
|
|
388
|
+
return _json("501 Not Implemented", {"error": "needs a store"})
|
|
389
|
+
if parts == ["payments"] and method == "GET":
|
|
390
|
+
q = _query_dict(environ.get("QUERY_STRING", ""))
|
|
391
|
+
rows = links.history(
|
|
392
|
+
q.get("status"),
|
|
393
|
+
_int_param(q, "limit", 50, 1, _MAX_PAGE_LIMIT),
|
|
394
|
+
_int_param(q, "offset", 0, 0, 10**9),
|
|
395
|
+
)
|
|
396
|
+
now = clock()
|
|
397
|
+
return _json("200 OK", {"payments": [r.to_dict(now) for r in rows]})
|
|
398
|
+
if len(parts) == 2 and parts[0] == "payments" and method == "GET":
|
|
399
|
+
rec = links.get(parts[1])
|
|
400
|
+
if rec is None:
|
|
401
|
+
raise NotFoundError(parts[1])
|
|
402
|
+
out = rec.to_dict(clock())
|
|
403
|
+
out["url"] = links.url_for(rec.reference, base)
|
|
404
|
+
return _json("200 OK", out)
|
|
405
|
+
if len(parts) == 3 and parts[0] == "payments" and method == "POST":
|
|
406
|
+
if parts[2] == "paid":
|
|
407
|
+
rec = links.mark_paid(parts[1], _read_json(environ).get("note"))
|
|
408
|
+
elif parts[2] == "cancel":
|
|
409
|
+
rec = links.cancel(parts[1])
|
|
410
|
+
else:
|
|
411
|
+
return _json("404 Not Found", {"error": "not found"})
|
|
412
|
+
return _json("200 OK", rec.to_dict(clock()))
|
|
413
|
+
except _TooLarge:
|
|
414
|
+
return _json("413 Payload Too Large", {"error": "body too large"})
|
|
415
|
+
except ValidationError as exc:
|
|
416
|
+
return _json("400 Bad Request", {"error": str(exc)})
|
|
417
|
+
except NotFoundError:
|
|
418
|
+
return _json("404 Not Found", {"error": "payment not found"})
|
|
419
|
+
except InvalidStateError as exc:
|
|
420
|
+
return _json("409 Conflict", {"error": str(exc)})
|
|
421
|
+
except ValueError:
|
|
422
|
+
return _json("400 Bad Request", {"error": "invalid request"})
|
|
423
|
+
return _json("404 Not Found", {"error": "not found"})
|
|
424
|
+
|
|
425
|
+
# ---- legacy signed links -------------------------------------------
|
|
426
|
+
def legacy(environ: Environ, path: str) -> _Resp:
|
|
427
|
+
if key is None: # pragma: no cover - guarded by caller
|
|
428
|
+
return _text("404 Not Found", "Not found")
|
|
429
|
+
try:
|
|
430
|
+
payment, expires_at = verify_payment_link(environ.get("QUERY_STRING", ""), key)
|
|
431
|
+
except LinkExpiredError:
|
|
432
|
+
return _text("410 Gone", "This payment link has expired")
|
|
433
|
+
except (SignatureError, ValidationError):
|
|
434
|
+
return _text("400 Bad Request", "Invalid payment link")
|
|
435
|
+
if path == "/pay":
|
|
436
|
+
return _html("200 OK", render_payment_page(payment, expires_at))
|
|
437
|
+
if path == "/qr.png":
|
|
438
|
+
return _Resp("200 OK", qr_png(payment), "image/png")
|
|
439
|
+
return _Resp("200 OK", qr_svg(payment).encode("utf-8"), "image/svg+xml")
|
|
440
|
+
|
|
441
|
+
# ---- probes --------------------------------------------------------
|
|
442
|
+
def ready() -> _Resp:
|
|
443
|
+
if store is not None:
|
|
444
|
+
try:
|
|
445
|
+
store.list(limit=1, now=clock())
|
|
446
|
+
except Exception:
|
|
447
|
+
log.exception("readiness check failed")
|
|
448
|
+
return _text("503 Service Unavailable", "store unavailable")
|
|
449
|
+
return _text("200 OK", "ready")
|
|
450
|
+
|
|
451
|
+
# ---- dispatch ------------------------------------------------------
|
|
452
|
+
def route(environ: Environ) -> _Resp:
|
|
453
|
+
method = environ.get("REQUEST_METHOD")
|
|
454
|
+
path = environ.get("PATH_INFO", "/")
|
|
455
|
+
if path == "/health":
|
|
456
|
+
return _text("200 OK", "ok")
|
|
457
|
+
if path == "/ready":
|
|
458
|
+
return ready()
|
|
459
|
+
if path.startswith("/api/") and (links is not None or stateless is not None):
|
|
460
|
+
return admin(environ, path)
|
|
461
|
+
if method not in ("GET", "HEAD"):
|
|
462
|
+
return _text("405 Method Not Allowed", "Method not allowed", [("Allow", "GET, HEAD")])
|
|
463
|
+
if (links is not None or stateless is not None) and path.startswith("/p/"):
|
|
464
|
+
return short(environ, path)
|
|
465
|
+
if key and path in ("/pay", "/qr.png", "/qr.svg"):
|
|
466
|
+
return legacy(environ, path)
|
|
467
|
+
return _text("404 Not Found", "Not found")
|
|
468
|
+
|
|
469
|
+
def app(environ: Environ, start_response: StartResponse) -> Iterable[bytes]:
|
|
470
|
+
began = time.perf_counter()
|
|
471
|
+
supplied_id = environ.get("HTTP_X_REQUEST_ID", "")
|
|
472
|
+
request_id = supplied_id if _REQUEST_ID_RE.match(supplied_id) else secrets.token_hex(8)
|
|
473
|
+
try:
|
|
474
|
+
resp = route(environ)
|
|
475
|
+
except Exception:
|
|
476
|
+
log.exception("unhandled error id=%s", request_id)
|
|
477
|
+
resp = _json("500 Internal Server Error", {"error": "internal error", "request_id": request_id})
|
|
478
|
+
body = resp.body
|
|
479
|
+
headers: Headers = [("Content-Type", resp.ctype), ("Content-Length", str(len(body)))]
|
|
480
|
+
headers += _SECURITY_HEADERS
|
|
481
|
+
headers.append(("Content-Security-Policy", _CSP_PAGE if resp.ctype.startswith("text/html") else _CSP_STRICT))
|
|
482
|
+
headers.append(("X-Request-ID", request_id))
|
|
483
|
+
if scheme(environ) == "https":
|
|
484
|
+
headers.append(("Strict-Transport-Security", "max-age=31536000"))
|
|
485
|
+
headers += list(resp.extra)
|
|
486
|
+
start_response(resp.status, headers)
|
|
487
|
+
if log.isEnabledFor(logging.INFO):
|
|
488
|
+
log.info(
|
|
489
|
+
"%s %s -> %s %.1fms ip=%s id=%s",
|
|
490
|
+
environ.get("REQUEST_METHOD"),
|
|
491
|
+
environ.get("PATH_INFO"),
|
|
492
|
+
resp.status.split(" ", 1)[0],
|
|
493
|
+
(time.perf_counter() - began) * 1000,
|
|
494
|
+
client_ip(environ),
|
|
495
|
+
request_id,
|
|
496
|
+
)
|
|
497
|
+
return [] if environ.get("REQUEST_METHOD") == "HEAD" else [body]
|
|
498
|
+
|
|
499
|
+
return BitsoPayApp(app, owned_store)
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
def serve(
|
|
503
|
+
secret: Optional[Union[str, bytes]] = None,
|
|
504
|
+
host: str = "127.0.0.1",
|
|
505
|
+
port: int = 8080,
|
|
506
|
+
*,
|
|
507
|
+
store: Optional[PaymentStore] = None,
|
|
508
|
+
admin_token: Optional[str] = None,
|
|
509
|
+
base_url: Optional[str] = None,
|
|
510
|
+
stateless: Optional[StatelessLinks] = None,
|
|
511
|
+
) -> None:
|
|
512
|
+
"""Run a development server (use gunicorn/uwsgi in production)."""
|
|
513
|
+
from wsgiref.simple_server import make_server
|
|
514
|
+
|
|
515
|
+
with (
|
|
516
|
+
create_app(secret, store=store, admin_token=admin_token, base_url=base_url, stateless=stateless) as app,
|
|
517
|
+
make_server(host, port, app) as httpd,
|
|
518
|
+
):
|
|
519
|
+
print(f"bitsopay serving on http://{host}:{port} (Ctrl+C to stop; development server only)")
|
|
520
|
+
httpd.serve_forever()
|