cmi-python 1.0.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.
cmi/standard/_form.py ADDED
@@ -0,0 +1,235 @@
1
+ """The auto-submitting HTML page that sends the customer to CMI's payment page.
2
+
3
+ The page shows a loading overlay (spinner, lock icon, "Secured by CMI" badge) while the
4
+ form submits itself. It uses one inline ``<style>`` and one inline ``<script>``: under a
5
+ strict Content-Security-Policy, pass a ``nonce``, or build your own form from the hidden
6
+ inputs.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import re
12
+ from collections.abc import Mapping
13
+ from typing import Any
14
+
15
+ from .._compat import js_string
16
+ from ._sanitize import escape_html
17
+
18
+ _TEMPLATE = """<!DOCTYPE html>
19
+ <html lang="en">
20
+ <head>
21
+ <meta charset="UTF-8">
22
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
23
+ <title>Payment Redirect</title>
24
+ <style__NONCE__>
25
+ *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
26
+
27
+ body {
28
+ min-height: 100vh;
29
+ display: flex;
30
+ align-items: center;
31
+ justify-content: center;
32
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
33
+ background: linear-gradient(135deg, #0f172a 0%, #1e293b 50%, #0f172a 100%);
34
+ color: #e2e8f0;
35
+ overflow: hidden;
36
+ }
37
+
38
+ .loader-overlay {
39
+ display: flex;
40
+ flex-direction: column;
41
+ align-items: center;
42
+ gap: 2rem;
43
+ animation: fadeIn 0.4s ease-out;
44
+ }
45
+
46
+ /* Spinner ring */
47
+ .spinner {
48
+ position: relative;
49
+ width: 72px;
50
+ height: 72px;
51
+ }
52
+
53
+ .spinner-ring {
54
+ width: 72px;
55
+ height: 72px;
56
+ border: 3px solid rgba(99, 102, 241, 0.15);
57
+ border-top-color: #818cf8;
58
+ border-radius: 50%;
59
+ animation: spin 0.9s cubic-bezier(0.4, 0, 0.2, 1) infinite;
60
+ }
61
+
62
+ .spinner-glow {
63
+ position: absolute;
64
+ inset: -4px;
65
+ border-radius: 50%;
66
+ background: conic-gradient(from 0deg, transparent 60%, rgba(129, 140, 248, 0.12));
67
+ animation: spin 0.9s cubic-bezier(0.4, 0, 0.2, 1) infinite;
68
+ filter: blur(6px);
69
+ }
70
+
71
+ /* Lock icon inside spinner */
72
+ .spinner-icon {
73
+ position: absolute;
74
+ top: 50%;
75
+ left: 50%;
76
+ transform: translate(-50%, -50%);
77
+ width: 22px;
78
+ height: 22px;
79
+ opacity: 0.7;
80
+ }
81
+
82
+ .spinner-icon svg {
83
+ width: 100%;
84
+ height: 100%;
85
+ fill: #a5b4fc;
86
+ }
87
+
88
+ /* Text */
89
+ .loader-text {
90
+ text-align: center;
91
+ }
92
+
93
+ .loader-title {
94
+ font-size: 1.125rem;
95
+ font-weight: 600;
96
+ letter-spacing: 0.025em;
97
+ color: #f1f5f9;
98
+ }
99
+
100
+ .loader-subtitle {
101
+ margin-top: 0.5rem;
102
+ font-size: 0.875rem;
103
+ color: #94a3b8;
104
+ display: flex;
105
+ align-items: center;
106
+ justify-content: center;
107
+ gap: 2px;
108
+ }
109
+
110
+ /* Animated dots */
111
+ .dot {
112
+ display: inline-block;
113
+ width: 4px;
114
+ height: 4px;
115
+ margin: 0 1px;
116
+ border-radius: 50%;
117
+ background: #94a3b8;
118
+ animation: dotPulse 1.4s ease-in-out infinite;
119
+ }
120
+ .dot:nth-child(2) { animation-delay: 0.2s; }
121
+ .dot:nth-child(3) { animation-delay: 0.4s; }
122
+
123
+ /* Subtle footer badge */
124
+ .secure-badge {
125
+ margin-top: 0.5rem;
126
+ display: flex;
127
+ align-items: center;
128
+ gap: 0.375rem;
129
+ font-size: 0.75rem;
130
+ color: #64748b;
131
+ letter-spacing: 0.04em;
132
+ }
133
+
134
+ .secure-badge svg {
135
+ width: 12px;
136
+ height: 12px;
137
+ fill: #64748b;
138
+ }
139
+
140
+ /* Animations */
141
+ @keyframes spin {
142
+ to { transform: rotate(360deg); }
143
+ }
144
+
145
+ @keyframes fadeIn {
146
+ from { opacity: 0; transform: translateY(10px); }
147
+ to { opacity: 1; transform: translateY(0); }
148
+ }
149
+
150
+ @keyframes dotPulse {
151
+ 0%, 80%, 100% { opacity: 0.3; transform: scale(0.8); }
152
+ 40% { opacity: 1; transform: scale(1.2); }
153
+ }
154
+
155
+ /* Noscript fallback styling */
156
+ noscript {
157
+ display: flex;
158
+ flex-direction: column;
159
+ align-items: center;
160
+ gap: 1rem;
161
+ color: #cbd5e1;
162
+ font-size: 0.9375rem;
163
+ }
164
+
165
+ noscript button {
166
+ padding: 0.75rem 2rem;
167
+ border: none;
168
+ border-radius: 8px;
169
+ background: linear-gradient(135deg, #6366f1, #818cf8);
170
+ color: #fff;
171
+ font-size: 0.9375rem;
172
+ font-weight: 600;
173
+ cursor: pointer;
174
+ transition: opacity 0.2s;
175
+ }
176
+
177
+ noscript button:hover { opacity: 0.9; }
178
+ </style>
179
+ </head>
180
+ <body>
181
+ <form method="POST" action="__ACTION__" name="paymentForm" id="paymentForm">
182
+ __INPUTS__
183
+ <noscript>
184
+ <p>JavaScript is required for automatic redirect.</p>
185
+ <button type="submit">Continue to Payment</button>
186
+ </noscript>
187
+ </form>
188
+
189
+ <div class="loader-overlay" id="loaderOverlay">
190
+ <div class="spinner">
191
+ <div class="spinner-glow"></div>
192
+ <div class="spinner-ring"></div>
193
+ <div class="spinner-icon">
194
+ <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zm-6 9c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zm3.1-9H8.9V6c0-1.71 1.39-3.1 3.1-3.1s3.1 1.39 3.1 3.1v2z"/></svg>
195
+ </div>
196
+ </div>
197
+ <div class="loader-text">
198
+ <div class="loader-title">Redirecting to secure payment via CMI platform</div>
199
+ <div class="loader-subtitle">
200
+ Please wait<span class="dot"></span><span class="dot"></span><span class="dot"></span>
201
+ </div>
202
+ </div>
203
+ <div class="secure-badge">
204
+ <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M12 1L3 5v6c0 5.55 3.84 10.74 9 12 5.16-1.26 9-6.45 9-12V5l-9-4zm-2 16l-4-4 1.41-1.41L10 14.17l6.59-6.59L18 9l-8 8z"/></svg>
205
+ Secured by CMI
206
+ </div>
207
+ </div>
208
+
209
+ <script__NONCE__>
210
+ // Use HTMLFormElement.prototype.submit.call() to prevent
211
+ // DOM clobbering if a hidden input is named "submit".
212
+ HTMLFormElement.prototype.submit.call(document.forms.namedItem('paymentForm'));
213
+ </script>
214
+ </body>
215
+ </html>"""
216
+
217
+ _PLACEHOLDER = re.compile(r"__(NONCE|ACTION|INPUTS)__")
218
+
219
+
220
+ def generate_inputs(params: Mapping[str, Any]) -> list[str]:
221
+ """One escaped ``<input type="hidden">`` per parameter."""
222
+ return [
223
+ f'<input type="hidden" name="{escape_html(str(key))}" value="{escape_html(js_string(value))}" />'
224
+ for key, value in params.items()
225
+ ]
226
+
227
+
228
+ def generate_form(gateway_url: str, params: Mapping[str, Any], nonce: str | None = None) -> str:
229
+ values = {
230
+ "NONCE": f' nonce="{escape_html(nonce)}"' if nonce else "",
231
+ "ACTION": escape_html(gateway_url),
232
+ "INPUTS": "\n".join(generate_inputs(params)),
233
+ }
234
+ # One pass over the template only: the inserted values are never scanned again.
235
+ return _PLACEHOLDER.sub(lambda m: values[m.group(1)], _TEMPLATE)
cmi/standard/_hash.py ADDED
@@ -0,0 +1,53 @@
1
+ """CMI "ver3" hash, as in CMI's reference PHP scripts.
2
+
3
+ Field names sorted with natcasesort(), "hash" and "encoding" skipped, "\\" then "|"
4
+ escaped, values joined with "|", the escaped store key appended, then base64(sha512).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import base64
10
+ import hashlib
11
+ from collections.abc import Callable, Mapping
12
+ from functools import cmp_to_key
13
+ from typing import Any
14
+
15
+ from .._compat import to_field_string, utf8
16
+ from .._php import php_html_entity_decode, php_strip_trailing_newline, php_strnatcasecmp
17
+ from .._security import SecretString
18
+ from ._sanitize import apply_document_rule
19
+
20
+ _natcase_key = cmp_to_key(php_strnatcasecmp)
21
+
22
+
23
+ def _escape(value: str) -> str:
24
+ return value.replace("\\", "\\\\").replace("|", "\\|")
25
+
26
+
27
+ def _compute(params: Mapping[str, Any], store_key: str | SecretString, transform: Callable[[str], str]) -> str:
28
+ # sorted() is stable, like PHP 8's natcasesort().
29
+ parts: list[str] = []
30
+ for key in sorted(params.keys(), key=_natcase_key):
31
+ if key.lower() in ("hash", "encoding"):
32
+ continue
33
+ value = transform(to_field_string(params[key]))
34
+ parts.append(_escape(apply_document_rule(value)) + "|")
35
+ key_value = store_key.get_value() if isinstance(store_key, SecretString) else store_key
36
+ hashval = "".join(parts) + _escape(key_value)
37
+ return base64.b64encode(hashlib.sha512(utf8(hashval)).digest()).decode("ascii")
38
+
39
+
40
+ def generate(params: Mapping[str, Any], store_key: str | SecretString) -> str:
41
+ """Hash of a payment request (2.SendData.php). Values are hashed exactly as they are
42
+ posted to CMI: the builder has already trimmed and cleaned them."""
43
+ return _compute(params, store_key, lambda value: value)
44
+
45
+
46
+ def _callback_value(value: str) -> str:
47
+ return php_html_entity_decode(php_strip_trailing_newline(value))
48
+
49
+
50
+ def generate_for_callback(params: Mapping[str, Any], store_key: str | SecretString) -> str:
51
+ """Hash of a callback or okUrl/failUrl request (callback.php): each received value loses
52
+ one trailing newline and is HTML-entity-decoded, and is not trimmed."""
53
+ return _compute(params, store_key, _callback_value)
@@ -0,0 +1,77 @@
1
+ """Cleaning of payment values, as in CMI's reference 2.SendData.php."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import unicodedata
7
+
8
+ from .._compat import js_trim, php_trim
9
+
10
+ # Letters that PHP's htmlentities() turns into an entity which str_without_accents() reduces
11
+ # to plain letters, other than the usual accent entities (acute, grave, circ, tilde, uml,
12
+ # ring, cedil, caron, slash). Entities not listed here and not reducible through Unicode
13
+ # decomposition (Ð, Þ, þ, ×, ÷, µ...) are removed, as in PHP.
14
+ _SPECIAL_LETTERS = {
15
+ "Æ": "AE", "æ": "ae", # &AElig; &aelig;
16
+ "Œ": "OE", "œ": "oe", # &OElig; &oelig;
17
+ "ß": "sz", # &szlig;
18
+ "Ø": "O", "ø": "o", # &Oslash; &oslash;
19
+ "ð": "e", # &eth; matches the "th" suffix in CMI's regex
20
+ } # fmt: skip
21
+
22
+ _KEPT = re.compile(r"[a-zA-Z0-9_ -]", re.ASCII)
23
+ _LETTER = re.compile(r"[a-zA-Z]", re.ASCII)
24
+ _COMBINING = re.compile("[̀-ͯ]")
25
+ _HTML_UNSAFE = re.compile(r"[<>'\"]")
26
+ _DOCUMENT = re.compile(r"(document)[\s\S]", re.ASCII | re.IGNORECASE)
27
+ _HTML_ESCAPES = {"&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;"}
28
+ _HTML_ESCAPE = re.compile(r"[&<>\"']")
29
+
30
+
31
+ def _is_accent_entity_letter(char: str) -> bool:
32
+ """Characters from the HTML 4.01 entity table that keep their base letter."""
33
+ code = ord(char)
34
+ # Latin-1 letters (À-ÿ) plus Š š Ÿ, the only other HTML 4.01 letter entities.
35
+ return 0xC0 <= code <= 0xFF or code in (0x160, 0x161, 0x178)
36
+
37
+
38
+ def sanitize_string(value: str | None, max_length: int = 255) -> str:
39
+ """Trimmed, without ``< > ' "``, cut to ``max_length``."""
40
+ if not value:
41
+ return ""
42
+ return _HTML_UNSAFE.sub("", js_trim(value))[:max_length]
43
+
44
+
45
+ def sanitize_email(email: str) -> str:
46
+ return js_trim(email).lower()[:64]
47
+
48
+
49
+ def escape_html(value: str) -> str:
50
+ return _HTML_ESCAPE.sub(lambda m: _HTML_ESCAPES[m.group(0)], value)
51
+
52
+
53
+ def remove_accents(value: str) -> str:
54
+ """Port of ``str_without_accents()`` from CMI's reference 2.SendData.php.
55
+
56
+ Accented letters lose their accent (é -> e, Æ -> AE), and every character other than
57
+ a-z, A-Z, 0-9, "_", space and "-" is removed. The result is trimmed.
58
+ """
59
+ out: list[str] = []
60
+ for char in value:
61
+ if _KEPT.fullmatch(char):
62
+ out.append(char)
63
+ elif char in _SPECIAL_LETTERS:
64
+ out.append(_SPECIAL_LETTERS[char])
65
+ elif _is_accent_entity_letter(char):
66
+ base = _COMBINING.sub("", unicodedata.normalize("NFD", char))
67
+ if _LETTER.fullmatch(base):
68
+ out.append(base)
69
+ # Anything else (punctuation, other scripts, symbols) is dropped, as in PHP.
70
+ return php_trim("".join(out))
71
+
72
+
73
+ def apply_document_rule(value: str) -> str:
74
+ """CMI's anti-XSS filter replaces the character that follows "document" with "." before
75
+ checking the hash (integration guide V2.0, §4.1.4). Applying the same change keeps the
76
+ hash identical on both sides; it is idempotent ("document.x" is left unchanged)."""
77
+ return _DOCUMENT.sub(r"\1.", value)