itd-chatbot-sdk 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.
- itd_bot/__init__.py +17 -0
- itd_bot/auth.py +254 -0
- itd_bot/client.py +825 -0
- itd_bot/dispatcher.py +197 -0
- itd_bot/errors.py +62 -0
- itd_bot/formatting.py +73 -0
- itd_bot/rate_limits.py +119 -0
- itd_chatbot_sdk-1.0.0.dist-info/METADATA +123 -0
- itd_chatbot_sdk-1.0.0.dist-info/RECORD +12 -0
- itd_chatbot_sdk-1.0.0.dist-info/WHEEL +5 -0
- itd_chatbot_sdk-1.0.0.dist-info/licenses/LICENSE +23 -0
- itd_chatbot_sdk-1.0.0.dist-info/top_level.txt +1 -0
itd_bot/__init__.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
from .client import Bot, APIError, ProtocolError, ResetRequired
|
|
2
|
+
from .dispatcher import CommandContext, Dispatcher
|
|
3
|
+
from .errors import RateLimitError, SessionStorageError
|
|
4
|
+
from .formatting import Text, utf16_length
|
|
5
|
+
|
|
6
|
+
__all__ = [
|
|
7
|
+
"Bot",
|
|
8
|
+
"APIError",
|
|
9
|
+
"RateLimitError",
|
|
10
|
+
"ProtocolError",
|
|
11
|
+
"ResetRequired",
|
|
12
|
+
"SessionStorageError",
|
|
13
|
+
"CommandContext",
|
|
14
|
+
"Dispatcher",
|
|
15
|
+
"Text",
|
|
16
|
+
"utf16_length",
|
|
17
|
+
]
|
itd_bot/auth.py
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import base64
|
|
4
|
+
import hashlib
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import tempfile
|
|
9
|
+
import threading
|
|
10
|
+
import time
|
|
11
|
+
import uuid
|
|
12
|
+
from http.cookies import SimpleCookie
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from urllib.parse import urlsplit
|
|
15
|
+
|
|
16
|
+
import httpx
|
|
17
|
+
|
|
18
|
+
from .errors import APIError, ProtocolError, SessionStorageError
|
|
19
|
+
from .rate_limits import RateLimitState
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _validate_refresh(value: str) -> str:
|
|
23
|
+
if (
|
|
24
|
+
not isinstance(value, str)
|
|
25
|
+
or not value
|
|
26
|
+
or len(value) > 8192
|
|
27
|
+
or not re.fullmatch(r"[\x21\x23-\x2b\x2d-\x3a\x3c-\x5b\x5d-\x7e]+", value)
|
|
28
|
+
):
|
|
29
|
+
raise ValueError("refresh token must be a single cookie value")
|
|
30
|
+
return value
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _claims(token: str) -> dict:
|
|
34
|
+
try:
|
|
35
|
+
part = token.split(".")[1]
|
|
36
|
+
if len(part) > 16384:
|
|
37
|
+
return {}
|
|
38
|
+
result = json.loads(base64.urlsafe_b64decode(part + "=" * (-len(part) % 4)))
|
|
39
|
+
return result if isinstance(result, dict) else {}
|
|
40
|
+
except (IndexError, ValueError, UnicodeDecodeError):
|
|
41
|
+
return {}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class RefreshSession:
|
|
45
|
+
"""Refresh a browser cookie session; serialize rotations inside this instance."""
|
|
46
|
+
|
|
47
|
+
def __init__(
|
|
48
|
+
self,
|
|
49
|
+
refresh_token: str,
|
|
50
|
+
*,
|
|
51
|
+
client: httpx.Client,
|
|
52
|
+
base_url: str,
|
|
53
|
+
session_path: str | os.PathLike | None,
|
|
54
|
+
access_token: str | None = None,
|
|
55
|
+
rate_limits: RateLimitState | None = None,
|
|
56
|
+
):
|
|
57
|
+
seed = _validate_refresh(refresh_token)
|
|
58
|
+
self._seed_fingerprint = hashlib.sha256(seed.encode("ascii")).hexdigest()
|
|
59
|
+
self._client = client
|
|
60
|
+
self._rate_limits = rate_limits if rate_limits is not None else RateLimitState()
|
|
61
|
+
self._base_url = base_url.rstrip("/")
|
|
62
|
+
self._path = Path(session_path) if session_path is not None else None
|
|
63
|
+
self._lock = threading.RLock()
|
|
64
|
+
self._access_token = access_token
|
|
65
|
+
self._refresh_count = 0
|
|
66
|
+
self._generation = 0
|
|
67
|
+
self._subject = _claims(access_token).get("sub") if access_token else None
|
|
68
|
+
self._device_id = str(uuid.uuid4())
|
|
69
|
+
self._refresh_token = seed
|
|
70
|
+
self._storage_dirty = False
|
|
71
|
+
if self._path is not None:
|
|
72
|
+
if self._path.exists():
|
|
73
|
+
self._load()
|
|
74
|
+
else:
|
|
75
|
+
self._save()
|
|
76
|
+
|
|
77
|
+
def _load(self) -> None:
|
|
78
|
+
try:
|
|
79
|
+
state = json.loads(self._path.read_text(encoding="utf-8"))
|
|
80
|
+
if (
|
|
81
|
+
not isinstance(state, dict)
|
|
82
|
+
or state.get("version") != 1
|
|
83
|
+
or state.get("seed_fingerprint") != self._seed_fingerprint
|
|
84
|
+
or state.get("base_url") != self._base_url
|
|
85
|
+
):
|
|
86
|
+
raise ValueError("session belongs to a different initial token")
|
|
87
|
+
self._refresh_token = _validate_refresh(state["refresh_token"])
|
|
88
|
+
stored_subject = state.get("subject")
|
|
89
|
+
if stored_subject is not None and not isinstance(stored_subject, str):
|
|
90
|
+
raise ValueError("invalid stored account")
|
|
91
|
+
if self._subject and stored_subject and self._subject != stored_subject:
|
|
92
|
+
raise ValueError("session belongs to a different account")
|
|
93
|
+
self._subject = stored_subject or self._subject
|
|
94
|
+
except (OSError, ValueError, KeyError, TypeError) as exc:
|
|
95
|
+
raise SessionStorageError(
|
|
96
|
+
"Cannot read refresh session or initial token does not match"
|
|
97
|
+
) from exc
|
|
98
|
+
|
|
99
|
+
def _save(self) -> None:
|
|
100
|
+
if self._path is None:
|
|
101
|
+
return
|
|
102
|
+
state = {
|
|
103
|
+
"version": 1,
|
|
104
|
+
"seed_fingerprint": self._seed_fingerprint,
|
|
105
|
+
"base_url": self._base_url,
|
|
106
|
+
"refresh_token": self._refresh_token,
|
|
107
|
+
"subject": self._subject,
|
|
108
|
+
}
|
|
109
|
+
tmp_name = None
|
|
110
|
+
try:
|
|
111
|
+
fd, tmp_name = tempfile.mkstemp(
|
|
112
|
+
prefix=".itd-session-", dir=self._path.parent
|
|
113
|
+
)
|
|
114
|
+
with os.fdopen(fd, "w", encoding="utf-8") as stream:
|
|
115
|
+
json.dump(state, stream, separators=(",", ":"))
|
|
116
|
+
stream.flush()
|
|
117
|
+
os.fsync(stream.fileno())
|
|
118
|
+
os.replace(tmp_name, self._path)
|
|
119
|
+
except OSError as exc:
|
|
120
|
+
if tmp_name is not None:
|
|
121
|
+
try:
|
|
122
|
+
os.unlink(tmp_name)
|
|
123
|
+
except OSError:
|
|
124
|
+
pass
|
|
125
|
+
raise SessionStorageError("Cannot save refresh session") from exc
|
|
126
|
+
|
|
127
|
+
def set_access_token(self, token: str) -> None:
|
|
128
|
+
with self._lock:
|
|
129
|
+
subject = _claims(token).get("sub")
|
|
130
|
+
if self._subject and subject != self._subject:
|
|
131
|
+
raise ProtocolError("Access token belongs to a different account")
|
|
132
|
+
if not self._subject and isinstance(subject, str) and subject:
|
|
133
|
+
self._subject = subject
|
|
134
|
+
self._storage_dirty = True
|
|
135
|
+
self._save()
|
|
136
|
+
self._storage_dirty = False
|
|
137
|
+
self._access_token = token
|
|
138
|
+
self._generation += 1
|
|
139
|
+
|
|
140
|
+
@property
|
|
141
|
+
def refresh_count(self) -> int:
|
|
142
|
+
with self._lock:
|
|
143
|
+
return self._refresh_count
|
|
144
|
+
|
|
145
|
+
def get_access_token(self) -> str:
|
|
146
|
+
with self._lock:
|
|
147
|
+
if self._storage_dirty:
|
|
148
|
+
self._save()
|
|
149
|
+
self._storage_dirty = False
|
|
150
|
+
claims = _claims(self._access_token) if self._access_token else {}
|
|
151
|
+
expiry = claims.get("exp")
|
|
152
|
+
if not self._access_token or (
|
|
153
|
+
isinstance(expiry, (int, float))
|
|
154
|
+
and not isinstance(expiry, bool)
|
|
155
|
+
and expiry <= time.time() + 30
|
|
156
|
+
):
|
|
157
|
+
self._refresh()
|
|
158
|
+
return self._access_token
|
|
159
|
+
|
|
160
|
+
def get_access_state(self) -> tuple[str, int]:
|
|
161
|
+
with self._lock:
|
|
162
|
+
return self.get_access_token(), self._generation
|
|
163
|
+
|
|
164
|
+
def refresh_after_401(self, rejected_token: str, generation: int) -> str:
|
|
165
|
+
with self._lock:
|
|
166
|
+
if self._storage_dirty:
|
|
167
|
+
self._save()
|
|
168
|
+
self._storage_dirty = False
|
|
169
|
+
if self._access_token and (
|
|
170
|
+
self._generation != generation or self._access_token != rejected_token
|
|
171
|
+
):
|
|
172
|
+
return self._access_token
|
|
173
|
+
self._refresh()
|
|
174
|
+
return self._access_token
|
|
175
|
+
|
|
176
|
+
def _refresh(self) -> None:
|
|
177
|
+
if self._storage_dirty:
|
|
178
|
+
self._save()
|
|
179
|
+
self._storage_dirty = False
|
|
180
|
+
origin = urlsplit(self._base_url)
|
|
181
|
+
headers = {
|
|
182
|
+
"Cookie": "refresh_token=" + self._refresh_token,
|
|
183
|
+
"Origin": f"{origin.scheme}://{origin.netloc}",
|
|
184
|
+
"X-Requested-With": "XMLHttpRequest",
|
|
185
|
+
"Content-Type": "application/json",
|
|
186
|
+
"X-Device-Id": self._device_id,
|
|
187
|
+
}
|
|
188
|
+
if self._access_token:
|
|
189
|
+
headers["Authorization"] = "Bearer " + self._access_token
|
|
190
|
+
self._rate_limits.check("POST", "/api/v1/auth/refresh")
|
|
191
|
+
response = self._client.post(
|
|
192
|
+
self._base_url + "/api/v1/auth/refresh",
|
|
193
|
+
headers=headers,
|
|
194
|
+
follow_redirects=False,
|
|
195
|
+
)
|
|
196
|
+
self._rate_limits.observe(response, "POST", "/api/v1/auth/refresh")
|
|
197
|
+
if not response.is_success:
|
|
198
|
+
try:
|
|
199
|
+
payload = response.json()
|
|
200
|
+
except ValueError:
|
|
201
|
+
payload = {}
|
|
202
|
+
detail = payload.get("error", payload) if isinstance(payload, dict) else {}
|
|
203
|
+
if not isinstance(detail, dict):
|
|
204
|
+
detail = {}
|
|
205
|
+
raise APIError(
|
|
206
|
+
response.status_code,
|
|
207
|
+
"Session refresh failed",
|
|
208
|
+
code=detail.get("code"),
|
|
209
|
+
errors=detail.get("errors"),
|
|
210
|
+
retry_after=response.headers.get("Retry-After"),
|
|
211
|
+
)
|
|
212
|
+
new_values = []
|
|
213
|
+
removed = False
|
|
214
|
+
for header in response.headers.get_list("set-cookie"):
|
|
215
|
+
cookie = SimpleCookie()
|
|
216
|
+
try:
|
|
217
|
+
cookie.load(header)
|
|
218
|
+
except Exception as exc:
|
|
219
|
+
raise ProtocolError("Invalid refresh cookie response") from exc
|
|
220
|
+
morsel = cookie.get("refresh_token")
|
|
221
|
+
if morsel is not None and (not morsel.value or morsel["max-age"] == "0"):
|
|
222
|
+
removed = True
|
|
223
|
+
if morsel is not None and morsel.value and morsel["max-age"] != "0":
|
|
224
|
+
try:
|
|
225
|
+
new_values.append(_validate_refresh(morsel.value))
|
|
226
|
+
except ValueError as exc:
|
|
227
|
+
raise ProtocolError("Invalid refresh cookie response") from exc
|
|
228
|
+
if len(set(new_values)) > 1:
|
|
229
|
+
raise ProtocolError("Conflicting refresh cookies in response")
|
|
230
|
+
if removed and not new_values:
|
|
231
|
+
raise ProtocolError("Server removed the refresh cookie")
|
|
232
|
+
if new_values and new_values[0] != self._refresh_token:
|
|
233
|
+
self._refresh_token = new_values[0]
|
|
234
|
+
self._storage_dirty = True
|
|
235
|
+
self._save()
|
|
236
|
+
self._storage_dirty = False
|
|
237
|
+
try:
|
|
238
|
+
payload = response.json()
|
|
239
|
+
except ValueError as exc:
|
|
240
|
+
raise ProtocolError("Invalid refresh response") from exc
|
|
241
|
+
token = payload.get("accessToken") if isinstance(payload, dict) else None
|
|
242
|
+
if not isinstance(token, str) or not token or "\n" in token or "\r" in token:
|
|
243
|
+
raise ProtocolError("Refresh response has no valid accessToken")
|
|
244
|
+
subject = _claims(token).get("sub")
|
|
245
|
+
if self._subject and subject != self._subject:
|
|
246
|
+
raise ProtocolError("Refreshed session belongs to a different account")
|
|
247
|
+
if not self._subject and isinstance(subject, str) and subject:
|
|
248
|
+
self._subject = subject
|
|
249
|
+
self._storage_dirty = True
|
|
250
|
+
self._save()
|
|
251
|
+
self._storage_dirty = False
|
|
252
|
+
self._access_token = token
|
|
253
|
+
self._refresh_count += 1
|
|
254
|
+
self._generation += 1
|