skapi 2.4.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.
- skapi/__init__.py +15 -0
- skapi/_cognito.py +386 -0
- skapi/_database.py +1454 -0
- skapi/_encryption.py +1359 -0
- skapi/_forward.py +484 -0
- skapi/_http.py +373 -0
- skapi/_md5.py +94 -0
- skapi/_project.py +83 -0
- skapi/_realtime.py +549 -0
- skapi/_social.py +323 -0
- skapi/_srp.py +126 -0
- skapi/_user.py +880 -0
- skapi/_ws.py +176 -0
- skapi/client.py +270 -0
- skapi/errors.py +26 -0
- skapi-2.4.0.dist-info/METADATA +46 -0
- skapi-2.4.0.dist-info/RECORD +20 -0
- skapi-2.4.0.dist-info/WHEEL +5 -0
- skapi-2.4.0.dist-info/licenses/LICENSE +201 -0
- skapi-2.4.0.dist-info/top_level.txt +1 -0
skapi/_social.py
ADDED
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
"""
|
|
2
|
+
User-side newsletters, subscriptions between users, the feed, and ticket listings, ported from
|
|
3
|
+
skapi-js (src/methods/subscription.ts, src/methods/user.ts).
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import re
|
|
10
|
+
import time
|
|
11
|
+
from typing import Any, Dict, Optional
|
|
12
|
+
|
|
13
|
+
from ._database import from_base62, user_id as _user_id
|
|
14
|
+
from ._user import _url, validate_email
|
|
15
|
+
from .errors import SkapiError
|
|
16
|
+
|
|
17
|
+
_RESERVED_GROUPS = {"tp", "admin", "public", "authorized", "newsletter", "forward", "all", "true", "false", "null"}
|
|
18
|
+
|
|
19
|
+
_TICKET_KEYS = {
|
|
20
|
+
"tkid": "ticket_id", "cond": "condition", "stmp": "timestamp", "upd": "updated", "acts": "actions", "actn": "action",
|
|
21
|
+
"cnt": "count", "ttl": "time_to_live", "plch": "placeholder", "hash": "hash", "desc": "description", "pmc": "limit_per_user",
|
|
22
|
+
"fail": "failed", "rv": "rules_version", "on": "enabled", "qn": "queued", "qdue": "queued_due", "cc": "concurrency",
|
|
23
|
+
"cf": "when_full", "cn": "running", "ln": "waiting", "sc": "self_calling",
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _jd(v):
|
|
28
|
+
"""A value as it appears in an error message; never fails on odd types."""
|
|
29
|
+
return json.dumps(v, default=repr, ensure_ascii=False)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _p(message: str, code: str = "INVALID_PARAMETER") -> SkapiError:
|
|
33
|
+
return SkapiError(message, code)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def newsletter_group(group: Any, allow_null: bool = False):
|
|
37
|
+
"""'public' -> 0, 'authorized' -> 1, an integer 0..99, or a newsletter group name."""
|
|
38
|
+
if group is None:
|
|
39
|
+
if allow_null:
|
|
40
|
+
return None
|
|
41
|
+
raise _p('"group" is required.')
|
|
42
|
+
if group == "public":
|
|
43
|
+
return 0
|
|
44
|
+
if group == "authorized":
|
|
45
|
+
return 1
|
|
46
|
+
if isinstance(group, (int, float)) and not isinstance(group, bool):
|
|
47
|
+
if group != int(group) or not 0 <= group <= 99:
|
|
48
|
+
raise _p('"group" should be an integer between 0 and 99.')
|
|
49
|
+
return int(group)
|
|
50
|
+
if (isinstance(group, str) and re.match(r"^[a-z0-9]{2,20}$", group) and re.search(r"[a-z]", group)
|
|
51
|
+
and not re.match(r"^[0-9]+e[0-9]+$", group) and group not in _RESERVED_GROUPS):
|
|
52
|
+
return group
|
|
53
|
+
raise _p("Newsletter group name must be 2-20 lowercase alphanumeric characters, contain a letter, and not be a reserved name.")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def map_ticket(t: Dict[str, Any]) -> Dict[str, Any]:
|
|
57
|
+
"""A ticket row as skapi-js returns it (short server keys renamed, consume ids split)."""
|
|
58
|
+
out: Dict[str, Any] = {}
|
|
59
|
+
for k, v in t.items():
|
|
60
|
+
if k == "tkid" and isinstance(v, str):
|
|
61
|
+
parts = v.split("#")
|
|
62
|
+
if len(parts) == 1:
|
|
63
|
+
out["ticket_id"] = parts[0]
|
|
64
|
+
else:
|
|
65
|
+
out["ticket_id"] = parts[1]
|
|
66
|
+
consume_id = parts[2] if len(parts) > 2 else ""
|
|
67
|
+
out["consume_id"] = consume_id
|
|
68
|
+
out["user_id"] = "#".join(parts[3:])
|
|
69
|
+
out["is_test"] = consume_id[-4:] == ":CHK"
|
|
70
|
+
if not t.get("stmp"):
|
|
71
|
+
ts = consume_id[:-4]
|
|
72
|
+
out["timestamp"] = int(ts) if re.match(r"^[0-9]+$", ts) else from_base62(ts)
|
|
73
|
+
elif k in _TICKET_KEYS:
|
|
74
|
+
out[_TICKET_KEYS[k]] = v
|
|
75
|
+
else:
|
|
76
|
+
out[k] = v
|
|
77
|
+
return out
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _subscription_row(s: Dict[str, Any]) -> Dict[str, Any]:
|
|
81
|
+
sub = s.get("sub")
|
|
82
|
+
grp = s.get("grp") or ""
|
|
83
|
+
parts = sub.split("#") if isinstance(sub, str) else []
|
|
84
|
+
row = {
|
|
85
|
+
"subscriber": parts[2] if len(parts) > 2 else s.get("subscriber"),
|
|
86
|
+
"subscription": parts[0] if parts else s.get("subscription"),
|
|
87
|
+
"timestamp": s.get("timestamp") or s.get("stmp"),
|
|
88
|
+
"blocked": bool(s.get("blocked")) or grp[:1] == "N",
|
|
89
|
+
}
|
|
90
|
+
if isinstance(s.get("opt"), dict):
|
|
91
|
+
row.update(s["opt"])
|
|
92
|
+
return row
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class SocialMixin:
|
|
96
|
+
"""Mixed into Skapi."""
|
|
97
|
+
|
|
98
|
+
def _target(self, params: Any) -> str:
|
|
99
|
+
if not isinstance(params, dict) or "user_id" not in params:
|
|
100
|
+
raise _p('Key "user_id" is required.')
|
|
101
|
+
return self._not_self(params["user_id"])
|
|
102
|
+
|
|
103
|
+
def _not_self(self, uid: Any, field: str = '"user_id"') -> str:
|
|
104
|
+
if self._user and uid == self._user.get("user_id"):
|
|
105
|
+
raise _p('"user_id" cannot be the user\'s own ID.')
|
|
106
|
+
return _user_id(uid, field)
|
|
107
|
+
|
|
108
|
+
# ---- newsletters ------------------------------------------------------------------------------
|
|
109
|
+
|
|
110
|
+
def subscribe_newsletter(self, params: Dict[str, Any]) -> str:
|
|
111
|
+
"""
|
|
112
|
+
Subscribes to the project's newsletters of one group. Signed in: the user's verified e-mail.
|
|
113
|
+
Signed out: params["email"], which gets a confirmation e-mail first.
|
|
114
|
+
"""
|
|
115
|
+
self._ensure_connection()
|
|
116
|
+
self._refuse_anonymous("subscribe to newsletters")
|
|
117
|
+
params = dict(params or {})
|
|
118
|
+
signed_in = self._signed_in()
|
|
119
|
+
if "group" not in params:
|
|
120
|
+
raise _p('Key "group" is required.')
|
|
121
|
+
if not signed_in and "email" not in params:
|
|
122
|
+
raise _p('Key "email" is required.')
|
|
123
|
+
body: Dict[str, Any] = {}
|
|
124
|
+
if "email" in params:
|
|
125
|
+
e = params["email"]
|
|
126
|
+
if isinstance(e, list) and e:
|
|
127
|
+
body["email"] = validate_email(e[0]) if len(e) == 1 else [validate_email(x) for x in e]
|
|
128
|
+
else:
|
|
129
|
+
body["email"] = validate_email(e) if not isinstance(e, list) else validate_email("")
|
|
130
|
+
body["group"] = newsletter_group(params["group"])
|
|
131
|
+
if "redirect" in params:
|
|
132
|
+
body["redirect"] = _url(params["redirect"])
|
|
133
|
+
path = "subscribe-newsletter" if signed_in else "subscribe-public-newsletter"
|
|
134
|
+
return self._call(path, body, auth=signed_in)
|
|
135
|
+
|
|
136
|
+
def unsubscribe_newsletter(self, group: Any) -> str:
|
|
137
|
+
"""Unsubscribes the signed-in user from one group, or from every group with group=None."""
|
|
138
|
+
self._ensure_connection()
|
|
139
|
+
self._refuse_anonymous("subscribe to newsletters")
|
|
140
|
+
return self._call("subscribe-newsletter", {"action": "unsubscribe", "group": newsletter_group(group, allow_null=True)}, auth=True)
|
|
141
|
+
|
|
142
|
+
def get_newsletters(self, params: Optional[Dict[str, Any]] = None, fetch_options: Optional[dict] = None) -> dict:
|
|
143
|
+
"""Newsletters sent to a group, newest first by default. Each has a url to its content."""
|
|
144
|
+
self._ensure_connection()
|
|
145
|
+
is_admin = self._is_admin()
|
|
146
|
+
fetch_options = dict(fetch_options or {})
|
|
147
|
+
if params is None:
|
|
148
|
+
fetch_options = dict({"ascending": False}, **fetch_options)
|
|
149
|
+
params = {"searchFor": "timestamp", "value": int(time.time() * 1000), "condition": "<", "group": "public"}
|
|
150
|
+
params = dict(params)
|
|
151
|
+
for key in ("searchFor", "value", "group"):
|
|
152
|
+
if key not in params:
|
|
153
|
+
raise _p(f'Key "{key}" is required.')
|
|
154
|
+
fields = ["message_id", "timestamp", "subject", "complaint", "read", "bounced"]
|
|
155
|
+
search_for = params["searchFor"]
|
|
156
|
+
if search_for not in fields:
|
|
157
|
+
raise _p(f'{_jd(search_for)} is invalid in "searchFor". allowed types or values are: ' + ", ".join(_jd(f) for f in fields) + ".")
|
|
158
|
+
value = params["value"]
|
|
159
|
+
wants_str = search_for in ("message_id", "subject")
|
|
160
|
+
if (wants_str and not isinstance(value, str)) or (not wants_str and (isinstance(value, bool) or not isinstance(value, (int, float)))):
|
|
161
|
+
raise _p(f'"value" type does not match the type of "{search_for}" index.')
|
|
162
|
+
if value == "":
|
|
163
|
+
raise _p('"value" should not be empty string.')
|
|
164
|
+
body: Dict[str, Any] = {"searchFor": search_for, "value": value}
|
|
165
|
+
if "range" in params:
|
|
166
|
+
r = params["range"]
|
|
167
|
+
if type(r) is not type(value) and not (isinstance(r, (int, float)) and isinstance(value, (int, float)) and not isinstance(r, bool)):
|
|
168
|
+
raise _p('"range" should match type of "value".')
|
|
169
|
+
body["range"] = r
|
|
170
|
+
conditions = [">", ">=", "=", "<", "<=", "gt", "gte", "eq", "lt", "lte"]
|
|
171
|
+
body["condition"] = params.get("condition") if params.get("condition") in conditions else "="
|
|
172
|
+
raw_group = params["group"]
|
|
173
|
+
group = newsletter_group(raw_group)
|
|
174
|
+
if isinstance(group, int) and group >= 1:
|
|
175
|
+
if not self._signed_in():
|
|
176
|
+
raise _p("User should be logged in.")
|
|
177
|
+
if not is_admin and group > int(self._user.get("access_group") or 0):
|
|
178
|
+
raise _p("User has no access.")
|
|
179
|
+
body["group"] = group
|
|
180
|
+
signed_in = self._signed_in()
|
|
181
|
+
if group == 0 or (isinstance(group, str) and not signed_in):
|
|
182
|
+
res = self._call("get-public-newsletters", body, auth=signed_in, method="GET", fetch_options=fetch_options)
|
|
183
|
+
else:
|
|
184
|
+
res = self._call("get-newsletters", body, auth=True, method="GET", fetch_options=fetch_options)
|
|
185
|
+
if isinstance(res, dict) and isinstance(res.get("list"), list):
|
|
186
|
+
out = []
|
|
187
|
+
defaults = {"message_id": "", "timestamp": 0, "complaint": 0, "read": 0, "subject": "", "bounced": "", "url": "",
|
|
188
|
+
"delivered": 0, "group": group, "dry": False, "sent": 0}
|
|
189
|
+
source = {"message_id": "mid", "timestamp": "stmp", "complaint": "cmpl", "read": "read", "subject": "subj", "bounced": "bnce",
|
|
190
|
+
"url": "url", "delivered": "delv", "group": "grp", "dry": "dry", "sent": "sent"}
|
|
191
|
+
for row in res["list"]:
|
|
192
|
+
item = {k: (row.get(src) or defaults[k]) for k, src in source.items()}
|
|
193
|
+
item["bounced"] = str(item["bounced"])
|
|
194
|
+
item["dry"] = bool(item["dry"])
|
|
195
|
+
if not item["sent"]:
|
|
196
|
+
del item["sent"]
|
|
197
|
+
out.append(item)
|
|
198
|
+
res["list"] = out
|
|
199
|
+
return res
|
|
200
|
+
|
|
201
|
+
def get_newsletter_subscription(self, params: Optional[Dict[str, Any]] = None, fetch_options: Optional[dict] = None) -> list:
|
|
202
|
+
"""The signed-in user's newsletter subscriptions: [{timestamp, group, subscribed_email, active}]."""
|
|
203
|
+
self._ensure_connection()
|
|
204
|
+
self._refuse_anonymous("subscribe to newsletters")
|
|
205
|
+
params = dict(params or {})
|
|
206
|
+
body: Dict[str, Any] = {}
|
|
207
|
+
if "user_id" in params:
|
|
208
|
+
if params["user_id"] != (self._user or {}).get("user_id") and not self._is_admin():
|
|
209
|
+
raise _p("No access.")
|
|
210
|
+
body["user_id"] = params["user_id"]
|
|
211
|
+
if "group" in params:
|
|
212
|
+
body["group"] = newsletter_group(params["group"], allow_null=True)
|
|
213
|
+
data = self._call("get-newsletter-subscription", body, auth=True, fetch_options=fetch_options)
|
|
214
|
+
rows = data.get("list") if isinstance(data, dict) and "list" in data else data
|
|
215
|
+
out = []
|
|
216
|
+
for r in rows if isinstance(rows, list) else []:
|
|
217
|
+
parts = str(r.get("subt", "")).split("#")
|
|
218
|
+
token = parts[0]
|
|
219
|
+
active = not token.startswith("@")
|
|
220
|
+
token = token.lstrip("@")
|
|
221
|
+
item = {"timestamp": r.get("stmp"), "group": int(token) if re.match(r"^\d+$", token) else token,
|
|
222
|
+
"subscribed_email": parts[1] if len(parts) > 1 else "", "active": active}
|
|
223
|
+
if isinstance(r.get("email_token"), str) and r["email_token"]:
|
|
224
|
+
item["subscriber_token"] = r["email_token"]
|
|
225
|
+
out.append(item)
|
|
226
|
+
if isinstance(data, dict) and "list" in data:
|
|
227
|
+
data["list"] = out
|
|
228
|
+
return data
|
|
229
|
+
return out
|
|
230
|
+
|
|
231
|
+
# ---- subscriptions between users -------------------------------------------------------------
|
|
232
|
+
|
|
233
|
+
def subscribe(self, params: Dict[str, Any]) -> Dict[str, Any]:
|
|
234
|
+
"""Subscribes the signed-in user to another user: {"user_id", "get_feed"?, "get_notified"?, "get_email"?}."""
|
|
235
|
+
self._require_session()
|
|
236
|
+
params = dict(params or {})
|
|
237
|
+
if "user_id" not in params:
|
|
238
|
+
raise _p('Key "user_id" is required.')
|
|
239
|
+
target = self._not_self(params["user_id"])
|
|
240
|
+
option: Dict[str, bool] = {}
|
|
241
|
+
for k in ("get_feed", "get_notified"):
|
|
242
|
+
if k in params:
|
|
243
|
+
if not isinstance(params[k], bool):
|
|
244
|
+
raise _p(f'{_jd(params[k])} is invalid in "{k}". allowed type or value is: Type<boolean>.')
|
|
245
|
+
option[k] = params[k]
|
|
246
|
+
if "get_email" in params:
|
|
247
|
+
if params["get_email"] and not (self._user.get("email") and self._user.get("email_verified")):
|
|
248
|
+
raise _p("User has no verified email address.")
|
|
249
|
+
option["get_email"] = bool(params["get_email"])
|
|
250
|
+
s = self._call("subscription", {"subscribe": target, "option": option}, auth=True)
|
|
251
|
+
if not isinstance(s, dict):
|
|
252
|
+
raise SkapiError("The subscription is blocked.", "INVALID_REQUEST")
|
|
253
|
+
return _subscription_row(s)
|
|
254
|
+
|
|
255
|
+
def unsubscribe(self, params: Dict[str, Any]) -> str:
|
|
256
|
+
self._require_session()
|
|
257
|
+
return self._call("subscription", {"unsubscribe": self._target(params)}, auth=True)
|
|
258
|
+
|
|
259
|
+
def block_subscriber(self, params: Dict[str, Any]) -> str:
|
|
260
|
+
"""Stops a user from subscribing to the signed-in user (and from getting their feed)."""
|
|
261
|
+
self._require_session()
|
|
262
|
+
return self._call("subscription", {"block": self._target(params)}, auth=True)
|
|
263
|
+
|
|
264
|
+
def unblock_subscriber(self, params: Dict[str, Any]) -> str:
|
|
265
|
+
self._require_session()
|
|
266
|
+
return self._call("subscription", {"unblock": self._target(params)}, auth=True)
|
|
267
|
+
|
|
268
|
+
def get_subscriptions(self, params: Dict[str, Any], fetch_options: Optional[dict] = None) -> dict:
|
|
269
|
+
"""Who a user subscribes to (subscriber=...) or who subscribes to a user (subscription=...)."""
|
|
270
|
+
self._require_session()
|
|
271
|
+
params = dict(params or {})
|
|
272
|
+
body: Dict[str, Any] = {}
|
|
273
|
+
if "subscriber" in params:
|
|
274
|
+
body["subscriber"] = _user_id(params["subscriber"], 'User ID in "subscriber"')
|
|
275
|
+
if "subscription" in params:
|
|
276
|
+
# any user, yourself included: your own id lists your own subscribers
|
|
277
|
+
body["subscription"] = _user_id(params["subscription"], 'User ID in "subscription"')
|
|
278
|
+
if "blocked" in params:
|
|
279
|
+
if not isinstance(params["blocked"], bool):
|
|
280
|
+
raise _p(f'{_jd(params["blocked"])} is invalid in "blocked". allowed type or value is: Type<boolean>.')
|
|
281
|
+
body["blocked"] = params["blocked"]
|
|
282
|
+
if not body.get("subscriber") and not body.get("subscription"):
|
|
283
|
+
raise _p('At least either "subscriber" or "subscription" should have a value.')
|
|
284
|
+
res = self._call("get-subscription", body, auth=True, fetch_options=fetch_options)
|
|
285
|
+
if isinstance(res, dict) and isinstance(res.get("list"), list):
|
|
286
|
+
res["list"] = [_subscription_row(r) for r in res["list"]]
|
|
287
|
+
return res
|
|
288
|
+
|
|
289
|
+
def get_feed(self, params: Optional[Dict[str, Any]] = None, fetch_options: Optional[dict] = None) -> dict:
|
|
290
|
+
"""Records the users you subscribe to (with get_feed on) posted to their feed, newest first."""
|
|
291
|
+
self._require_session()
|
|
292
|
+
params = dict(params or {})
|
|
293
|
+
body: Dict[str, Any] = {}
|
|
294
|
+
if "access_group" in params:
|
|
295
|
+
v = params["access_group"]
|
|
296
|
+
g = 1 if v == "authorized" else 0 if v == "public" else v
|
|
297
|
+
if isinstance(g, bool) or not isinstance(g, (int, float)):
|
|
298
|
+
raise _p('"access_group" should be type number.')
|
|
299
|
+
if g < 0:
|
|
300
|
+
raise _p('"access_group" should be zero or a positive number.')
|
|
301
|
+
if g > int(self._user.get("access_group") or 0):
|
|
302
|
+
raise _p("User has no access.")
|
|
303
|
+
body["access_group"] = g
|
|
304
|
+
res = self._call("get-feed", body, auth=True, fetch_options=fetch_options)
|
|
305
|
+
if isinstance(res, dict) and isinstance(res.get("list"), list):
|
|
306
|
+
res["list"] = [self._normalize_record(r) for r in res["list"]]
|
|
307
|
+
return res
|
|
308
|
+
|
|
309
|
+
# ---- tickets ------------------------------------------------------------------------------------
|
|
310
|
+
|
|
311
|
+
def get_tickets(self, params: Optional[Dict[str, Any]] = None, fetch_options: Optional[dict] = None) -> dict:
|
|
312
|
+
"""The project's tickets (or one, with {"ticket_id": ...}) as a signed-in user sees them."""
|
|
313
|
+
res = self._call("ticket", dict({"exec": "list"}, **(params or {})), auth=True, fetch_options=fetch_options)
|
|
314
|
+
if isinstance(res, dict) and isinstance(res.get("list"), list):
|
|
315
|
+
res["list"] = [map_ticket(r) for r in res["list"]]
|
|
316
|
+
return res
|
|
317
|
+
|
|
318
|
+
def get_consumed_tickets(self, params: Optional[Dict[str, Any]] = None, fetch_options: Optional[dict] = None) -> dict:
|
|
319
|
+
"""The signed-in user's own ticket calls (each with ticket_id, consume_id and timestamp)."""
|
|
320
|
+
res = self._call("ticket", dict({"exec": "consumed"}, **(params or {})), auth=True, fetch_options=fetch_options)
|
|
321
|
+
if isinstance(res, dict) and isinstance(res.get("list"), list):
|
|
322
|
+
res["list"] = [map_ticket(r) for r in res["list"]]
|
|
323
|
+
return res
|
skapi/_srp.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Cognito's SRP-6a password sign-in, ported from skapi-js (src/cognito/srp.ts), which is itself a
|
|
3
|
+
byte-for-byte port of amazon-cognito-identity-js. Every step, padHex in particular, must give the
|
|
4
|
+
same bytes: a wrong padding only fails a sign-in when a value starts with a high bit, about 1 in
|
|
5
|
+
256 attempts, so it is easy to miss.
|
|
6
|
+
|
|
7
|
+
The password never leaves the device: only A (g^a mod N) and a signature made with the derived key
|
|
8
|
+
are sent.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import hashlib
|
|
14
|
+
import hmac
|
|
15
|
+
import re
|
|
16
|
+
import secrets
|
|
17
|
+
from datetime import datetime, timezone
|
|
18
|
+
|
|
19
|
+
N_HEX = (
|
|
20
|
+
"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" "29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
|
|
21
|
+
"EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
|
|
22
|
+
"EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
|
|
23
|
+
"83655D23DCA3AD961C62F356208552BB9ED529077096966D" "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B"
|
|
24
|
+
"E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" "DE2BCBF6955817183995497CEA956AE515D2261898FA0510"
|
|
25
|
+
"15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7"
|
|
26
|
+
"ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C"
|
|
27
|
+
"BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" "43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF"
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
N = int(N_HEX, 16)
|
|
31
|
+
G = 2
|
|
32
|
+
|
|
33
|
+
_HEX_MSB = re.compile(r"^[89a-f]", re.IGNORECASE)
|
|
34
|
+
_INFO_BITS = b"Caldera Derived Key" + b"\x01"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def hex_to_int(hex_str: str) -> int:
|
|
38
|
+
"""Hex string to int, as `new BigInteger(hex, 16)` read it (an empty string is 0)."""
|
|
39
|
+
return int(hex_str, 16) if hex_str else 0
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def hex_to_bytes(hex_str: str) -> bytes:
|
|
43
|
+
"""Two characters at a time, stopping at the first pair that is not hex, like Buffer.from(hex, 'hex')."""
|
|
44
|
+
out = bytearray()
|
|
45
|
+
for i in range(0, len(hex_str) - 1, 2):
|
|
46
|
+
try:
|
|
47
|
+
out.append(int(hex_str[i:i + 2], 16))
|
|
48
|
+
except ValueError:
|
|
49
|
+
break
|
|
50
|
+
return bytes(out)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def pad_hex(value: int) -> str:
|
|
54
|
+
"""
|
|
55
|
+
Signed big-endian hex exactly as the library writes it: even length, a leading "00" when the top
|
|
56
|
+
bit is set (so the value stays positive), and two's complement for a negative value.
|
|
57
|
+
"""
|
|
58
|
+
is_negative = value < 0
|
|
59
|
+
hex_str = format(-value if is_negative else value, "x")
|
|
60
|
+
if len(hex_str) % 2:
|
|
61
|
+
hex_str = "0" + hex_str
|
|
62
|
+
if _HEX_MSB.match(hex_str):
|
|
63
|
+
hex_str = "00" + hex_str
|
|
64
|
+
if is_negative:
|
|
65
|
+
inverted = "".join("0123456789ABCDEF"[~int(c, 16) & 0xF] for c in hex_str)
|
|
66
|
+
hex_str = format(int(inverted, 16) + 1, "x")
|
|
67
|
+
if hex_str.upper().startswith("FF8"):
|
|
68
|
+
hex_str = hex_str[2:]
|
|
69
|
+
return hex_str
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _hash_hex(data: bytes) -> str:
|
|
73
|
+
return hashlib.sha256(data).hexdigest()
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _hex_hash(hex_str: str) -> str:
|
|
77
|
+
return _hash_hex(hex_to_bytes(hex_str))
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
K = hex_to_int(_hex_hash(pad_hex(N) + pad_hex(G)))
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def compute_hkdf(ikm: bytes, salt: bytes) -> bytes:
|
|
84
|
+
"""HKDF-SHA256 with Cognito's info string, first 16 bytes."""
|
|
85
|
+
prk = hmac.new(salt, ikm, hashlib.sha256).digest()
|
|
86
|
+
return hmac.new(prk, _INFO_BITS, hashlib.sha256).digest()[:16]
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class SrpHelper:
|
|
90
|
+
def __init__(self, pool_name: str, small_a: int | None = None):
|
|
91
|
+
"""
|
|
92
|
+
pool_name: the part of the user pool id after the underscore.
|
|
93
|
+
small_a: for the equivalence checks only, a fixed secret instead of 128 random bytes.
|
|
94
|
+
"""
|
|
95
|
+
self.pool_name = pool_name
|
|
96
|
+
# 128 random bytes read as a positive integer; no reduction needed, N is 3072 bits.
|
|
97
|
+
self.small_a = small_a if small_a is not None else int.from_bytes(secrets.token_bytes(128), "big")
|
|
98
|
+
self.large_a = pow(G, self.small_a, N)
|
|
99
|
+
if self.large_a % N == 0:
|
|
100
|
+
raise ValueError("Illegal paramater. A mod N cannot be 0.")
|
|
101
|
+
|
|
102
|
+
def get_password_authentication_key(self, username: str, password: str, server_b: int, salt: int) -> bytes:
|
|
103
|
+
"""The 16 byte key both sides derive; Cognito checks a signature made with it."""
|
|
104
|
+
if server_b % N == 0:
|
|
105
|
+
raise ValueError("B cannot be zero.")
|
|
106
|
+
u = hex_to_int(_hex_hash(pad_hex(self.large_a) + pad_hex(server_b)))
|
|
107
|
+
if u == 0:
|
|
108
|
+
raise ValueError("U cannot be zero.")
|
|
109
|
+
username_password_hash = _hash_hex(f"{self.pool_name}{username}:{password}".encode("utf-8"))
|
|
110
|
+
x = hex_to_int(_hex_hash(pad_hex(salt) + username_password_hash))
|
|
111
|
+
# S = (B - k * g^x) ^ (a + u * x) mod N. The base can be negative; Python's % gives the
|
|
112
|
+
# residue in [0, N), the same value the library's BigInteger used.
|
|
113
|
+
base = (server_b - K * pow(G, x, N)) % N
|
|
114
|
+
s = pow(base, self.small_a + u * x, N)
|
|
115
|
+
return compute_hkdf(hex_to_bytes(pad_hex(s)), hex_to_bytes(pad_hex(u)))
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
_WEEK = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
|
|
119
|
+
_MONTH = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def cognito_timestamp(now: datetime | None = None) -> str:
|
|
123
|
+
""""Sun Nov 15 16:52:00 UTC 2026": the day is not zero padded, the time is."""
|
|
124
|
+
now = now or datetime.now(timezone.utc)
|
|
125
|
+
return (f"{_WEEK[now.weekday()]} {_MONTH[now.month - 1]} {now.day} "
|
|
126
|
+
f"{now.hour:02d}:{now.minute:02d}:{now.second:02d} UTC {now.year}")
|