zeekr-ev-api 0.1.5__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.
- zeekr_ev_api-0.1.5/LICENSE +21 -0
- zeekr_ev_api-0.1.5/PKG-INFO +22 -0
- zeekr_ev_api-0.1.5/README.md +3 -0
- zeekr_ev_api-0.1.5/pyproject.toml +24 -0
- zeekr_ev_api-0.1.5/src/zeekr_ev_api/__init__.py +7 -0
- zeekr_ev_api-0.1.5/src/zeekr_ev_api/client.py +479 -0
- zeekr_ev_api-0.1.5/src/zeekr_ev_api/const.py +81 -0
- zeekr_ev_api-0.1.5/src/zeekr_ev_api/network.py +97 -0
- zeekr_ev_api-0.1.5/src/zeekr_ev_api/zeekr_app_sig.py +249 -0
- zeekr_ev_api-0.1.5/src/zeekr_ev_api/zeekr_hmac.py +121 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Fryyyyy
|
|
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.
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: zeekr_ev_api
|
|
3
|
+
Version: 0.1.5
|
|
4
|
+
Summary:
|
|
5
|
+
License-File: LICENSE
|
|
6
|
+
Author: Fry
|
|
7
|
+
Author-email: fryx0r@gmail.com
|
|
8
|
+
Requires-Python: >=3.10
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
15
|
+
Requires-Dist: pycryptodome (>=3.23.0,<4.0.0)
|
|
16
|
+
Requires-Dist: requests (>=2.32.5,<3.0.0)
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
|
|
19
|
+
# zeekr_ev_api
|
|
20
|
+
|
|
21
|
+
API for interacting with Zeekr EVs
|
|
22
|
+
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "zeekr_ev_api"
|
|
3
|
+
version = "0.1.5"
|
|
4
|
+
description = ""
|
|
5
|
+
authors = [
|
|
6
|
+
{name = "Fry",email = "fryx0r@gmail.com"}
|
|
7
|
+
]
|
|
8
|
+
readme = "README.md"
|
|
9
|
+
requires-python = ">=3.10"
|
|
10
|
+
dependencies = [
|
|
11
|
+
"pycryptodome (>=3.23.0,<4.0.0)",
|
|
12
|
+
"requests (>=2.32.5,<3.0.0)"
|
|
13
|
+
]
|
|
14
|
+
|
|
15
|
+
[tool.poetry]
|
|
16
|
+
packages = [{include = "zeekr_ev_api", from = "src"}]
|
|
17
|
+
|
|
18
|
+
[build-system]
|
|
19
|
+
requires = ["poetry-core>=2.0.0,<3.0.0"]
|
|
20
|
+
build-backend = "poetry.core.masonry.api"
|
|
21
|
+
|
|
22
|
+
[tool.poetry.group.dev.dependencies]
|
|
23
|
+
pytest = "^8.2.2"
|
|
24
|
+
pytest-mock = "^3.14.0"
|
|
@@ -0,0 +1,479 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Zeekr EV API Client
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import json
|
|
7
|
+
import logging
|
|
8
|
+
from typing import Any, Dict
|
|
9
|
+
|
|
10
|
+
import requests
|
|
11
|
+
from Crypto.Cipher import PKCS1_v1_5
|
|
12
|
+
from Crypto.PublicKey import RSA
|
|
13
|
+
|
|
14
|
+
from . import const, network, zeekr_app_sig, zeekr_hmac
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class ZeekrException(Exception):
|
|
18
|
+
"""Base exception for the library."""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class AuthException(ZeekrException):
|
|
22
|
+
"""Exception for authentication errors."""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class ZeekrClient:
|
|
26
|
+
"""
|
|
27
|
+
A client for the Zeekr EV API.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
def __init__(
|
|
31
|
+
self,
|
|
32
|
+
username: str | None = None,
|
|
33
|
+
password: str | None = None,
|
|
34
|
+
country_code: str = "AU",
|
|
35
|
+
hmac_access_key: str = "",
|
|
36
|
+
hmac_secret_key: str = "",
|
|
37
|
+
password_public_key: str = "",
|
|
38
|
+
prod_secret: str = "",
|
|
39
|
+
vin_key: str = "",
|
|
40
|
+
vin_iv: str = "",
|
|
41
|
+
session_data: dict | None = None,
|
|
42
|
+
logger: logging.Logger | None = None,
|
|
43
|
+
) -> None:
|
|
44
|
+
"""
|
|
45
|
+
Initializes the client.
|
|
46
|
+
"""
|
|
47
|
+
self.session: requests.Session = requests.Session()
|
|
48
|
+
self.password: str | None = password
|
|
49
|
+
|
|
50
|
+
# Logger for this client (allows caller to inject their logger)
|
|
51
|
+
self.logger = logger or logging.getLogger(__name__)
|
|
52
|
+
|
|
53
|
+
# Store secrets on instance instead of mutating global const
|
|
54
|
+
self.hmac_access_key = hmac_access_key or const.HMAC_ACCESS_KEY
|
|
55
|
+
self.hmac_secret_key = hmac_secret_key or const.HMAC_SECRET_KEY
|
|
56
|
+
self.password_public_key = password_public_key or const.PASSWORD_PUBLIC_KEY
|
|
57
|
+
self.prod_secret = prod_secret or const.PROD_SECRET
|
|
58
|
+
self.vin_key = vin_key or const.VIN_KEY
|
|
59
|
+
self.vin_iv = vin_iv or const.VIN_IV
|
|
60
|
+
|
|
61
|
+
if session_data:
|
|
62
|
+
self.load_session(session_data)
|
|
63
|
+
else:
|
|
64
|
+
if not username or not password:
|
|
65
|
+
raise ValueError(
|
|
66
|
+
"Username and password are required for a new session."
|
|
67
|
+
)
|
|
68
|
+
self.username: str = username
|
|
69
|
+
self.country_code: str = country_code
|
|
70
|
+
self.logged_in: bool = False
|
|
71
|
+
self.auth_token: str | None = None
|
|
72
|
+
self.bearer_token: str | None = None
|
|
73
|
+
self.user_info: dict = {}
|
|
74
|
+
self.vin: str | None = None
|
|
75
|
+
self.vehicles: list["Vehicle"] = []
|
|
76
|
+
|
|
77
|
+
# These will be populated during login
|
|
78
|
+
self.app_server_host: str = const.APP_SERVER_HOST
|
|
79
|
+
self.usercenter_host: str = const.USERCENTER_HOST
|
|
80
|
+
self.message_host: str = const.MESSAGE_HOST
|
|
81
|
+
self.region_code: str = const.REGION_CODE
|
|
82
|
+
self.region_login_server: str | None = None
|
|
83
|
+
|
|
84
|
+
def load_session(self, session_data: dict) -> None:
|
|
85
|
+
"""Loads a session from a dictionary."""
|
|
86
|
+
self.username = session_data.get("username", "")
|
|
87
|
+
self.country_code = session_data.get("country_code", "AU")
|
|
88
|
+
self.auth_token = session_data.get("auth_token")
|
|
89
|
+
self.bearer_token = session_data.get("bearer_token")
|
|
90
|
+
self.user_info = session_data.get("user_info", {})
|
|
91
|
+
self.app_server_host = session_data.get("app_server_host", "")
|
|
92
|
+
self.usercenter_host = session_data.get("usercenter_host", "")
|
|
93
|
+
self.message_host = session_data.get("message_host", "")
|
|
94
|
+
self.region_code = session_data.get("region_code", "")
|
|
95
|
+
self.region_login_server = session_data.get("region_login_server")
|
|
96
|
+
self.vehicles: list["Vehicle"] = []
|
|
97
|
+
|
|
98
|
+
if self.bearer_token:
|
|
99
|
+
self.logged_in = True
|
|
100
|
+
const.LOGGED_IN_HEADERS["authorization"] = self.bearer_token
|
|
101
|
+
if self.auth_token:
|
|
102
|
+
self.session.headers["authorization"] = self.auth_token
|
|
103
|
+
else:
|
|
104
|
+
self.logged_in = False
|
|
105
|
+
|
|
106
|
+
def export_session(self) -> dict:
|
|
107
|
+
"""Exports the current session to a dictionary."""
|
|
108
|
+
if not self.logged_in:
|
|
109
|
+
return {}
|
|
110
|
+
|
|
111
|
+
return {
|
|
112
|
+
"username": self.username,
|
|
113
|
+
"country_code": self.country_code,
|
|
114
|
+
"auth_token": self.auth_token,
|
|
115
|
+
"bearer_token": self.bearer_token,
|
|
116
|
+
"user_info": self.user_info,
|
|
117
|
+
"app_server_host": self.app_server_host,
|
|
118
|
+
"usercenter_host": self.usercenter_host,
|
|
119
|
+
"message_host": self.message_host,
|
|
120
|
+
"region_code": self.region_code,
|
|
121
|
+
"region_login_server": self.region_login_server,
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
def _rsa_encrypt_password(self) -> str:
|
|
125
|
+
"""
|
|
126
|
+
Encrypts the password using RSA.
|
|
127
|
+
"""
|
|
128
|
+
if not self.password:
|
|
129
|
+
raise ValueError("Password is not set for encryption.")
|
|
130
|
+
|
|
131
|
+
key_bytes = base64.b64decode(self.password_public_key)
|
|
132
|
+
public_key = RSA.import_key(key_bytes)
|
|
133
|
+
cipher = PKCS1_v1_5.new(public_key)
|
|
134
|
+
password_bytes = self.password.encode("utf-8")
|
|
135
|
+
encrypted_bytes = cipher.encrypt(password_bytes)
|
|
136
|
+
return base64.b64encode(encrypted_bytes).decode("utf-8")
|
|
137
|
+
|
|
138
|
+
def login(self, relogin: bool = False) -> None:
|
|
139
|
+
"""
|
|
140
|
+
Logs in to the Zeekr API.
|
|
141
|
+
"""
|
|
142
|
+
if self.logged_in and not relogin:
|
|
143
|
+
return
|
|
144
|
+
self._get_urls()
|
|
145
|
+
self._check_user()
|
|
146
|
+
self._do_login_request()
|
|
147
|
+
self._get_user_info()
|
|
148
|
+
self._get_protocol()
|
|
149
|
+
self._check_inbox()
|
|
150
|
+
tsp_code, _ = self._get_tsp_code()
|
|
151
|
+
self._update_language()
|
|
152
|
+
# self._sycn_push(login_id) # Disabled for now
|
|
153
|
+
self._bearer_login(tsp_code)
|
|
154
|
+
self.logged_in = True
|
|
155
|
+
|
|
156
|
+
def _get_urls(self) -> None:
|
|
157
|
+
"""
|
|
158
|
+
Fetches the regional API URLs.
|
|
159
|
+
"""
|
|
160
|
+
urls = network.customGet(self, f"{const.APP_SERVER_HOST}{const.URL_URL}")
|
|
161
|
+
if not urls.get("success", False):
|
|
162
|
+
raise ZeekrException("Unable to fetch URL data")
|
|
163
|
+
|
|
164
|
+
url_data = urls.get("data", [])
|
|
165
|
+
found = False
|
|
166
|
+
for url_block in url_data:
|
|
167
|
+
if url_block.get("countryCode", "").lower() == self.country_code.lower():
|
|
168
|
+
self.app_server_host = url_block.get("url", {}).get("appServerUrl", "")
|
|
169
|
+
self.usercenter_host = url_block.get("url", {}).get("userCenterUrl", "")
|
|
170
|
+
self.message_host = url_block.get("url", {}).get("messageCoreUrl", "")
|
|
171
|
+
self.region_code = url_block.get("regionCode", "SEA")
|
|
172
|
+
found = True
|
|
173
|
+
break
|
|
174
|
+
if not found:
|
|
175
|
+
raise ZeekrException(
|
|
176
|
+
f"Unable to find URLs for country code: {self.country_code}"
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
if (
|
|
180
|
+
not self.app_server_host
|
|
181
|
+
or not self.usercenter_host
|
|
182
|
+
or not self.message_host
|
|
183
|
+
):
|
|
184
|
+
raise ZeekrException("One or more API URLs are blank after fetching.")
|
|
185
|
+
|
|
186
|
+
self.region_login_server = const.REGION_LOGIN_SERVERS.get(self.region_code)
|
|
187
|
+
if not self.region_login_server:
|
|
188
|
+
raise ZeekrException(f"No login server for region: {self.region_code}")
|
|
189
|
+
|
|
190
|
+
def _check_user(self) -> None:
|
|
191
|
+
"""
|
|
192
|
+
Checks if the user exists.
|
|
193
|
+
"""
|
|
194
|
+
user_code = network.customPost(
|
|
195
|
+
self,
|
|
196
|
+
f"{self.usercenter_host}{const.CHECKUSER_URL}",
|
|
197
|
+
{"email": self.username, "checkType": "1"},
|
|
198
|
+
)
|
|
199
|
+
if not user_code.get("success", False):
|
|
200
|
+
raise AuthException("User check failed")
|
|
201
|
+
|
|
202
|
+
def _do_login_request(self) -> None:
|
|
203
|
+
"""
|
|
204
|
+
Performs the main login request.
|
|
205
|
+
"""
|
|
206
|
+
encrypted_password = self._rsa_encrypt_password()
|
|
207
|
+
if not encrypted_password:
|
|
208
|
+
raise AuthException("Password encryption failed")
|
|
209
|
+
|
|
210
|
+
request_data = {
|
|
211
|
+
"code": "",
|
|
212
|
+
"codeId": "",
|
|
213
|
+
"email": self.username,
|
|
214
|
+
"password": encrypted_password,
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
req = requests.Request(
|
|
218
|
+
"POST",
|
|
219
|
+
f"{self.usercenter_host}{const.LOGIN_URL}",
|
|
220
|
+
headers=const.DEFAULT_HEADERS,
|
|
221
|
+
json=request_data,
|
|
222
|
+
)
|
|
223
|
+
new_req = zeekr_hmac.generateHMAC(
|
|
224
|
+
req, self.hmac_access_key, self.hmac_secret_key
|
|
225
|
+
)
|
|
226
|
+
prepped = self.session.prepare_request(new_req)
|
|
227
|
+
resp = self.session.send(prepped)
|
|
228
|
+
login_data = resp.json()
|
|
229
|
+
|
|
230
|
+
if not login_data or not login_data.get("success", False):
|
|
231
|
+
raise AuthException(f"Login failed: {login_data}")
|
|
232
|
+
|
|
233
|
+
login_token = login_data.get("data", {})
|
|
234
|
+
if login_token.get("tokenName", "") != "Authorization":
|
|
235
|
+
raise AuthException(f"Unknown login token type: {login_token}")
|
|
236
|
+
|
|
237
|
+
self.auth_token = login_token.get("tokenValue")
|
|
238
|
+
if not self.auth_token:
|
|
239
|
+
raise AuthException("No auth token supplied in login response")
|
|
240
|
+
|
|
241
|
+
self.session.headers["authorization"] = self.auth_token
|
|
242
|
+
|
|
243
|
+
def _get_user_info(self) -> None:
|
|
244
|
+
"""
|
|
245
|
+
Fetches user information.
|
|
246
|
+
"""
|
|
247
|
+
user_info_resp = network.customPost(
|
|
248
|
+
self, f"{self.usercenter_host}{const.USERINFO_URL}"
|
|
249
|
+
)
|
|
250
|
+
if user_info_resp.get("success", False):
|
|
251
|
+
self.user_info = user_info_resp.get("data", {})
|
|
252
|
+
|
|
253
|
+
def _get_protocol(self) -> None:
|
|
254
|
+
"""
|
|
255
|
+
Fetches the protocol.
|
|
256
|
+
"""
|
|
257
|
+
network.customPost(
|
|
258
|
+
self,
|
|
259
|
+
f"{self.app_server_host}{const.PROTOCOL_URL}",
|
|
260
|
+
{"country": self.country_code},
|
|
261
|
+
)
|
|
262
|
+
|
|
263
|
+
def _check_inbox(self) -> None:
|
|
264
|
+
"""
|
|
265
|
+
Checks the inbox.
|
|
266
|
+
"""
|
|
267
|
+
network.customGet(self, f"{self.app_server_host}{const.INBOX_URL}")
|
|
268
|
+
|
|
269
|
+
def _get_tsp_code(self) -> tuple[str, str]:
|
|
270
|
+
"""
|
|
271
|
+
Gets the TSP code.
|
|
272
|
+
"""
|
|
273
|
+
tsp_code_block = network.customGet(
|
|
274
|
+
self,
|
|
275
|
+
f"{self.usercenter_host}{const.TSPCODE_URL}?tspClientId={const.DEFAULT_HEADERS.get('client-id', '')}",
|
|
276
|
+
)
|
|
277
|
+
if not tsp_code_block.get("success", False):
|
|
278
|
+
raise ZeekrException(f"Unable to fetch TSP Code: {tsp_code_block}")
|
|
279
|
+
|
|
280
|
+
tsp_code = tsp_code_block.get("data", {}).get("code")
|
|
281
|
+
login_id = tsp_code_block.get("data", {}).get("loginId")
|
|
282
|
+
if not tsp_code:
|
|
283
|
+
raise ZeekrException(f"No TSP code in response: {tsp_code_block}")
|
|
284
|
+
|
|
285
|
+
return tsp_code, login_id
|
|
286
|
+
|
|
287
|
+
def _update_language(self, language: str = "en") -> None:
|
|
288
|
+
"""
|
|
289
|
+
Updates the language.
|
|
290
|
+
"""
|
|
291
|
+
network.customGet(
|
|
292
|
+
self,
|
|
293
|
+
f"{self.usercenter_host}{const.UPDATELANGUAGE_URL}?language={language}",
|
|
294
|
+
)
|
|
295
|
+
|
|
296
|
+
def _bearer_login(self, tsp_code: str) -> None:
|
|
297
|
+
"""
|
|
298
|
+
Performs the bearer token login.
|
|
299
|
+
"""
|
|
300
|
+
bearer_body = {
|
|
301
|
+
"identifier": tsp_code,
|
|
302
|
+
"identityType": 10,
|
|
303
|
+
"loginDeviceId": "google-sdk_gphone64_x86_64-36-16",
|
|
304
|
+
"loginDeviceJgId": "",
|
|
305
|
+
"loginDeviceType": 1,
|
|
306
|
+
"loginPhoneBrand": "google",
|
|
307
|
+
"loginPhoneModel": "sdk_gphone64_x86_64",
|
|
308
|
+
"loginSystem": "Android",
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
bearer_login_block = network.appSignedPost(
|
|
312
|
+
self,
|
|
313
|
+
f"{self.region_login_server}{const.BEARERLOGIN_URL}",
|
|
314
|
+
json.dumps(bearer_body, separators=(",", ":")),
|
|
315
|
+
)
|
|
316
|
+
if not bearer_login_block.get("success", False):
|
|
317
|
+
raise AuthException(f"Bearer login failed: {bearer_login_block}")
|
|
318
|
+
|
|
319
|
+
bearer_login_data = bearer_login_block.get("data", {})
|
|
320
|
+
self.bearer_token = bearer_login_data.get("accessToken")
|
|
321
|
+
if not self.bearer_token:
|
|
322
|
+
raise AuthException(f"No bearer token in response: {bearer_login_data}")
|
|
323
|
+
|
|
324
|
+
const.LOGGED_IN_HEADERS["authorization"] = self.bearer_token
|
|
325
|
+
|
|
326
|
+
def get_vehicle_list(self) -> list["Vehicle"]:
|
|
327
|
+
"""
|
|
328
|
+
Fetches the list of vehicles.
|
|
329
|
+
"""
|
|
330
|
+
if not self.logged_in:
|
|
331
|
+
raise ZeekrException("Not logged in")
|
|
332
|
+
|
|
333
|
+
vehicle_list_block = network.appSignedGet(
|
|
334
|
+
self,
|
|
335
|
+
f"{self.region_login_server}{const.VEHLIST_URL}?needSharedCar=true",
|
|
336
|
+
)
|
|
337
|
+
if not vehicle_list_block.get("success", False):
|
|
338
|
+
raise ZeekrException(f"Failed to get vehicle list: {vehicle_list_block}")
|
|
339
|
+
|
|
340
|
+
self.vehicles = [
|
|
341
|
+
Vehicle(self, v.get("vin"), v) for v in vehicle_list_block.get("data", [])
|
|
342
|
+
]
|
|
343
|
+
return self.vehicles
|
|
344
|
+
|
|
345
|
+
def get_vehicle_status(self, vin: str) -> Dict[str, Any]:
|
|
346
|
+
"""
|
|
347
|
+
Fetches the status for a specific vehicle.
|
|
348
|
+
"""
|
|
349
|
+
if not self.logged_in:
|
|
350
|
+
raise ZeekrException("Not logged in")
|
|
351
|
+
|
|
352
|
+
encrypted_vin = zeekr_app_sig.aes_encrypt(vin, self.vin_key, self.vin_iv)
|
|
353
|
+
|
|
354
|
+
headers = const.LOGGED_IN_HEADERS.copy()
|
|
355
|
+
headers["X-VIN"] = encrypted_vin
|
|
356
|
+
|
|
357
|
+
vehicle_status_block = network.appSignedGet(
|
|
358
|
+
self,
|
|
359
|
+
f"{self.region_login_server}{const.VEHICLESTATUS_URL}?latest=false&target=new",
|
|
360
|
+
headers=headers,
|
|
361
|
+
)
|
|
362
|
+
if not vehicle_status_block.get("success", False):
|
|
363
|
+
raise ZeekrException(
|
|
364
|
+
f"Failed to get vehicle status: {vehicle_status_block}"
|
|
365
|
+
)
|
|
366
|
+
|
|
367
|
+
return vehicle_status_block.get("data", {})
|
|
368
|
+
|
|
369
|
+
def get_vehicle_charging_status(self, vin: str) -> Dict[str, Any]:
|
|
370
|
+
"""
|
|
371
|
+
Fetches the charging status for a specific vehicle.
|
|
372
|
+
"""
|
|
373
|
+
if not self.logged_in:
|
|
374
|
+
raise ZeekrException("Not logged in")
|
|
375
|
+
|
|
376
|
+
encrypted_vin = zeekr_app_sig.aes_encrypt(vin, self.vin_key, self.vin_iv)
|
|
377
|
+
|
|
378
|
+
headers = const.LOGGED_IN_HEADERS.copy()
|
|
379
|
+
headers["X-VIN"] = encrypted_vin
|
|
380
|
+
|
|
381
|
+
vehicle_charging_status_block = network.appSignedGet(
|
|
382
|
+
self,
|
|
383
|
+
f"{self.region_login_server}{const.VEHICLECHARGINGSTATUS_URL}",
|
|
384
|
+
headers=headers,
|
|
385
|
+
)
|
|
386
|
+
if not vehicle_charging_status_block.get("success", False):
|
|
387
|
+
raise ZeekrException(
|
|
388
|
+
f"Failed to get vehicle charging status: {vehicle_charging_status_block}"
|
|
389
|
+
)
|
|
390
|
+
|
|
391
|
+
return vehicle_charging_status_block.get("data", {})
|
|
392
|
+
|
|
393
|
+
def get_vehicle_state(self, vin: str) -> dict[str, Any]:
|
|
394
|
+
"""
|
|
395
|
+
Fetches the remote control state of a vehicle.
|
|
396
|
+
"""
|
|
397
|
+
if not self.logged_in:
|
|
398
|
+
raise ZeekrException("Not logged in")
|
|
399
|
+
|
|
400
|
+
encrypted_vin = zeekr_app_sig.aes_encrypt(vin, self.vin_key, self.vin_iv)
|
|
401
|
+
|
|
402
|
+
headers = const.LOGGED_IN_HEADERS.copy()
|
|
403
|
+
headers["X-VIN"] = encrypted_vin
|
|
404
|
+
|
|
405
|
+
vehicle_status_block = network.appSignedGet(
|
|
406
|
+
self,
|
|
407
|
+
f"{self.region_login_server}{const.REMOTECONTROLSTATE_URL}",
|
|
408
|
+
headers=headers,
|
|
409
|
+
)
|
|
410
|
+
if not vehicle_status_block.get("success", False):
|
|
411
|
+
raise ZeekrException(
|
|
412
|
+
f"Failed to get vehicle status: {vehicle_status_block}"
|
|
413
|
+
)
|
|
414
|
+
|
|
415
|
+
return vehicle_status_block.get("data", {})
|
|
416
|
+
|
|
417
|
+
def do_remote_control(
|
|
418
|
+
self, vin: str, command: str, serviceID: str, setting: Dict[str, Any]
|
|
419
|
+
) -> bool:
|
|
420
|
+
"""
|
|
421
|
+
Performs a remote control action on the vehicle.
|
|
422
|
+
"""
|
|
423
|
+
if not self.logged_in:
|
|
424
|
+
raise ZeekrException("Not logged in")
|
|
425
|
+
|
|
426
|
+
extra_header = {}
|
|
427
|
+
extra_header["X-VIN"] = zeekr_app_sig.aes_encrypt(
|
|
428
|
+
vin, self.vin_key, self.vin_iv
|
|
429
|
+
)
|
|
430
|
+
|
|
431
|
+
body = {"command": command, "serviceID": serviceID, "setting": setting}
|
|
432
|
+
|
|
433
|
+
remote_control_block = network.appSignedPost(
|
|
434
|
+
self,
|
|
435
|
+
f"{self.region_login_server}{const.REMOTECONTROL_URL}",
|
|
436
|
+
json.dumps(body, separators=(",", ":")),
|
|
437
|
+
extra_headers=extra_header,
|
|
438
|
+
)
|
|
439
|
+
return remote_control_block.get("success", False)
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
class Vehicle:
|
|
443
|
+
"""
|
|
444
|
+
Represents a Zeekr vehicle.
|
|
445
|
+
"""
|
|
446
|
+
|
|
447
|
+
def __init__(self, client: "ZeekrClient", vin: str, data: dict) -> None:
|
|
448
|
+
self._client = client
|
|
449
|
+
self.vin = vin
|
|
450
|
+
self.data = data
|
|
451
|
+
|
|
452
|
+
def __repr__(self) -> str:
|
|
453
|
+
return f"<Vehicle {self.vin}>"
|
|
454
|
+
|
|
455
|
+
def get_status(self) -> Any:
|
|
456
|
+
"""
|
|
457
|
+
Fetches the vehicle status.
|
|
458
|
+
"""
|
|
459
|
+
return self._client.get_vehicle_status(self.vin)
|
|
460
|
+
|
|
461
|
+
def get_charging_status(self) -> Any:
|
|
462
|
+
"""
|
|
463
|
+
Fetches the vehicle charging status.
|
|
464
|
+
"""
|
|
465
|
+
return self._client.get_vehicle_charging_status(self.vin)
|
|
466
|
+
|
|
467
|
+
def get_remote_control_state(self) -> Any:
|
|
468
|
+
"""
|
|
469
|
+
Fetches the vehicle remote control state.
|
|
470
|
+
"""
|
|
471
|
+
return self._client.get_vehicle_state(self.vin)
|
|
472
|
+
|
|
473
|
+
def do_remote_control(
|
|
474
|
+
self, command: str, serviceID: str, setting: Dict[str, Any]
|
|
475
|
+
) -> bool:
|
|
476
|
+
"""
|
|
477
|
+
Performs a remote control action on the vehicle.
|
|
478
|
+
"""
|
|
479
|
+
return self._client.do_remote_control(self.vin, command, serviceID, setting)
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import uuid
|
|
2
|
+
|
|
3
|
+
# Hosts (set to SEA by default)
|
|
4
|
+
APP_SERVER_HOST = "https://gateway-pub-hw-em-sg.zeekrlife.com/overseas-app/"
|
|
5
|
+
USERCENTER_HOST = "https://gateway-pub-hw-em-sg.zeekrlife.com/zeekr-cuc-idaas-sea/"
|
|
6
|
+
MESSAGE_HOST = "https://gateway-pub-hw-em-sg.zeekrlife.com/sea-message-core/"
|
|
7
|
+
|
|
8
|
+
# URLs
|
|
9
|
+
LOGIN_URL = "auth/loginByEmailEncrypt"
|
|
10
|
+
PROTOCOL_URL = "protocol/service/getProtocol"
|
|
11
|
+
SERVICE_URL = "classification/service/type/V2"
|
|
12
|
+
URL_URL = "region/url"
|
|
13
|
+
CHECKUSER_URL = "auth/checkUserV2"
|
|
14
|
+
USERINFO_URL = "user/info"
|
|
15
|
+
TSPCODE_URL = "user/tspCode"
|
|
16
|
+
BEARERLOGIN_URL = "ms-user-auth/v1.0/auth/login"
|
|
17
|
+
VEHLIST_URL = "ms-app-bff/api/v4.0/veh/vehicle-list"
|
|
18
|
+
INBOX_URL = "member/inbox/home"
|
|
19
|
+
UPDATELANGUAGE_URL = "user/updateLanguage"
|
|
20
|
+
SYCN_URL = "open-api/v1/mcs/notice/receiver/equipment/relation/sycn"
|
|
21
|
+
VEHICLESTATUS_URL = "ms-vehicle-status/api/v1.0/vehicle/status/latest"
|
|
22
|
+
VEHICLECHARGINGSTATUS_URL = "ms-vehicle-status/api/v1.0/vehicle/status/qrvs"
|
|
23
|
+
REMOTECONTROLSTATE_URL = "ms-app-bff/api/v1.0/remoteControl/getVehicleState"
|
|
24
|
+
REMOTECONTROL_URL = "ms-remote-control/v1.0/remoteControl/control"
|
|
25
|
+
|
|
26
|
+
COUNTRY_CODE = "AU"
|
|
27
|
+
REGION_CODE = "SEA"
|
|
28
|
+
|
|
29
|
+
REGION_LOGIN_SERVERS = {
|
|
30
|
+
"SEA": "https://sea-snc-tsp-api-gw.zeekrlife.com/",
|
|
31
|
+
"UAE": "https://me-snc-tsp-api-gw.zeekrlife.com/",
|
|
32
|
+
"LA": "https://la-snc-tsp-api-gw.zeekrlife.com/",
|
|
33
|
+
"EU": "https://eu-snc-tsp-api-gw.zeekrlife.com/",
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
# Secrets
|
|
37
|
+
HMAC_ACCESS_KEY = ""
|
|
38
|
+
HMAC_SECRET_KEY = ""
|
|
39
|
+
PASSWORD_PUBLIC_KEY = ""
|
|
40
|
+
PROD_SECRET = ""
|
|
41
|
+
VIN_KEY = ""
|
|
42
|
+
VIN_IV = ""
|
|
43
|
+
|
|
44
|
+
DEFAULT_HEADERS = {
|
|
45
|
+
"accept-encoding": "gzip",
|
|
46
|
+
"accept-language": "en-AU",
|
|
47
|
+
"app-authorization": "1003",
|
|
48
|
+
"app-code": "32816dbd-ff17-47b7-e250-5dae7d9f8cd4",
|
|
49
|
+
"appcode": "eu-app",
|
|
50
|
+
"appid": "TSP",
|
|
51
|
+
"appsecret": "zeekr_tis",
|
|
52
|
+
"appversion": "1.4.1",
|
|
53
|
+
"call-source": "android",
|
|
54
|
+
"client-id": "1JwLroFkFFIpgFGdTRrm4_nzkkwDkfHj7RxJQb7J8tc",
|
|
55
|
+
"Content-Type": "application/json; charset=UTF-8",
|
|
56
|
+
"country": COUNTRY_CODE,
|
|
57
|
+
"device-name": "sdk_gphone64_x86_64",
|
|
58
|
+
"device-type": "app",
|
|
59
|
+
"language": "en",
|
|
60
|
+
"msgappid": "11002",
|
|
61
|
+
"msgclientid": "1003",
|
|
62
|
+
"registcountry": COUNTRY_CODE,
|
|
63
|
+
"tmp-tenant-code": "3300743799505195008",
|
|
64
|
+
"user-agent": "Device/GoogleAppName/com.zeekr.globalAppVersion/1.4.1Platform/androidOSVersion/16Ditto/true",
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
LOGGED_IN_HEADERS = {
|
|
68
|
+
"Accept-Encoding": "gzip",
|
|
69
|
+
"ACCEPT-LANGUAGE": "en-AU",
|
|
70
|
+
"AppId": "ONEX97FB91F061405",
|
|
71
|
+
"authorization": "",
|
|
72
|
+
"Content-Type": "application/json; charset=UTF-8",
|
|
73
|
+
"user-agent": "okhttp/4.12.0",
|
|
74
|
+
"X-API-SIGNATURE-VERSION": "2.0",
|
|
75
|
+
"X-APP-ID": "ZEEKRCNCH001M0001",
|
|
76
|
+
"x-app-os-version": "",
|
|
77
|
+
"x-device-id": str(uuid.uuid4()),
|
|
78
|
+
"x-p": "Android",
|
|
79
|
+
"X-PLATFORM": "APP",
|
|
80
|
+
"X-PROJECT-ID": "ZEEKR_SEA",
|
|
81
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from typing import Any, TYPE_CHECKING
|
|
3
|
+
|
|
4
|
+
from requests import Request
|
|
5
|
+
from . import const, zeekr_app_sig, zeekr_hmac
|
|
6
|
+
|
|
7
|
+
if TYPE_CHECKING:
|
|
8
|
+
from .client import ZeekrClient
|
|
9
|
+
|
|
10
|
+
log = logging.getLogger(__name__)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def customPost(client: "ZeekrClient", url: str, body: dict | None = None) -> Any:
|
|
14
|
+
"""Sends a signed POST request with HMAC authentication."""
|
|
15
|
+
logger = getattr(client, "logger", log)
|
|
16
|
+
req = Request("POST", url, headers=const.DEFAULT_HEADERS, json=body)
|
|
17
|
+
req = zeekr_hmac.generateHMAC(req, client.hmac_access_key, client.hmac_secret_key)
|
|
18
|
+
|
|
19
|
+
prepped = client.session.prepare_request(req)
|
|
20
|
+
resp = client.session.send(prepped)
|
|
21
|
+
logger.debug("------ HEADERS ------")
|
|
22
|
+
logger.debug(resp.headers)
|
|
23
|
+
logger.debug("------ RESPONSE ------")
|
|
24
|
+
logger.debug(resp.text)
|
|
25
|
+
|
|
26
|
+
return resp.json()
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def customGet(client: "ZeekrClient", url: str) -> Any:
|
|
30
|
+
"""Sends a signed GET request with HMAC authentication."""
|
|
31
|
+
logger = getattr(client, "logger", log)
|
|
32
|
+
req = Request("GET", url, headers=const.DEFAULT_HEADERS)
|
|
33
|
+
req = zeekr_hmac.generateHMAC(req, client.hmac_access_key, client.hmac_secret_key)
|
|
34
|
+
|
|
35
|
+
prepped = client.session.prepare_request(req)
|
|
36
|
+
resp = client.session.send(prepped)
|
|
37
|
+
logger.debug("------ HEADERS ------")
|
|
38
|
+
logger.debug(resp.headers)
|
|
39
|
+
logger.debug("------ RESPONSE ------")
|
|
40
|
+
logger.debug(resp.text)
|
|
41
|
+
|
|
42
|
+
return resp.json()
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def appSignedPost(
|
|
46
|
+
client: "ZeekrClient",
|
|
47
|
+
url: str,
|
|
48
|
+
body: str | None = None,
|
|
49
|
+
extra_headers: dict | None = None,
|
|
50
|
+
) -> Any:
|
|
51
|
+
"""Sends a signed POST request with an app signature."""
|
|
52
|
+
logger = getattr(client, "logger", log)
|
|
53
|
+
req = Request("POST", url, headers=const.LOGGED_IN_HEADERS, data=body)
|
|
54
|
+
if extra_headers:
|
|
55
|
+
req.headers.update(extra_headers)
|
|
56
|
+
prepped = client.session.prepare_request(req)
|
|
57
|
+
|
|
58
|
+
final = zeekr_app_sig.sign_request(prepped, client.prod_secret)
|
|
59
|
+
|
|
60
|
+
logger.debug("--- Signed Request Details ---")
|
|
61
|
+
logger.debug(f"Method: {final.method}")
|
|
62
|
+
logger.debug(f"URL: {final.url}")
|
|
63
|
+
logger.debug("Headers:")
|
|
64
|
+
for k, v in final.headers.items():
|
|
65
|
+
logger.debug(f" {k}: {v}")
|
|
66
|
+
logger.debug(f"Body: {final.body or ''}")
|
|
67
|
+
logger.debug(f"\nX-SIGNATURE: {final.headers['X-SIGNATURE']}")
|
|
68
|
+
|
|
69
|
+
resp = client.session.send(final)
|
|
70
|
+
logger.debug("------ HEADERS ------")
|
|
71
|
+
logger.debug(resp.headers)
|
|
72
|
+
logger.debug("------ RESPONSE ------")
|
|
73
|
+
logger.debug(resp.text)
|
|
74
|
+
|
|
75
|
+
return resp.json()
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def appSignedGet(client: "ZeekrClient", url: str, headers: dict | None = None) -> Any:
|
|
79
|
+
"""Sends a signed GET request with an app signature."""
|
|
80
|
+
if not client.bearer_token:
|
|
81
|
+
raise Exception("Client is not logged in.")
|
|
82
|
+
if not const.LOGGED_IN_HEADERS["authorization"]:
|
|
83
|
+
const.LOGGED_IN_HEADERS["authorization"] = client.bearer_token
|
|
84
|
+
logger = getattr(client, "logger", log)
|
|
85
|
+
req = Request("GET", url, headers=const.LOGGED_IN_HEADERS)
|
|
86
|
+
if headers:
|
|
87
|
+
req.headers.update(headers)
|
|
88
|
+
prepped = client.session.prepare_request(req)
|
|
89
|
+
|
|
90
|
+
final = zeekr_app_sig.sign_request(prepped, client.prod_secret)
|
|
91
|
+
resp = client.session.send(final)
|
|
92
|
+
logger.debug("------ HEADERS ------")
|
|
93
|
+
logger.debug(resp.headers)
|
|
94
|
+
logger.debug("------ RESPONSE ------")
|
|
95
|
+
logger.debug(resp.text)
|
|
96
|
+
|
|
97
|
+
return resp.json()
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
import base64
|
|
2
|
+
import hashlib
|
|
3
|
+
import hmac
|
|
4
|
+
import json
|
|
5
|
+
import logging
|
|
6
|
+
import time
|
|
7
|
+
import uuid
|
|
8
|
+
|
|
9
|
+
from typing import List
|
|
10
|
+
|
|
11
|
+
from urllib.parse import urlparse, parse_qs
|
|
12
|
+
|
|
13
|
+
from Crypto.Cipher import AES
|
|
14
|
+
from Crypto.Util.Padding import pad
|
|
15
|
+
|
|
16
|
+
from requests import PreparedRequest # For type hinting and structure
|
|
17
|
+
|
|
18
|
+
log = logging.getLogger(__name__)
|
|
19
|
+
|
|
20
|
+
ALLOWED_HEADERS: list[str] = [
|
|
21
|
+
"x-app-id",
|
|
22
|
+
"content-type",
|
|
23
|
+
"x-api-signature-nonce",
|
|
24
|
+
"x-timestamp",
|
|
25
|
+
"x-api-signature-version",
|
|
26
|
+
"x-project-id",
|
|
27
|
+
"authorization",
|
|
28
|
+
"accept-language",
|
|
29
|
+
"x-vin",
|
|
30
|
+
"x-device-id",
|
|
31
|
+
"x-platform",
|
|
32
|
+
]
|
|
33
|
+
|
|
34
|
+
# Keys with special validation requirements
|
|
35
|
+
X_VIN_HEADER: str = "x-vin" # Must have a non-empty value
|
|
36
|
+
AUTH_HEADER: str = "authorization" # Must have a non-empty value
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def aes_encrypt(plain_text: str, key_hex: str, iv_hex: str) -> str:
|
|
40
|
+
"""
|
|
41
|
+
Encrypts a string using AES/CBC/PKCS5Padding
|
|
42
|
+
and returns a Base64 encoded string.
|
|
43
|
+
|
|
44
|
+
Args:
|
|
45
|
+
plain_text: The string to be encrypted.
|
|
46
|
+
key_hex: The 16-byte key as a hexadecimal string.
|
|
47
|
+
iv_hex: The 16-byte IV as a hexadecimal string.
|
|
48
|
+
|
|
49
|
+
Returns:
|
|
50
|
+
The Base64 encoded ciphertext string.
|
|
51
|
+
"""
|
|
52
|
+
# Convert PlainText to bytes (Java uses StandardCharsets.UTF_8)
|
|
53
|
+
plain_text_bytes = plain_text.encode("utf-8")
|
|
54
|
+
|
|
55
|
+
# Create the AES cipher object in CBC mode
|
|
56
|
+
# IV is passed as the `iv` parameter.
|
|
57
|
+
cipher = AES.new(key_hex.encode("utf-8"), AES.MODE_CBC, iv=iv_hex.encode("utf-8"))
|
|
58
|
+
|
|
59
|
+
# Apply PKCS7 Padding (PyCryptodome's `pad` function defaults to PKCS7,
|
|
60
|
+
# which is equivalent to PKCS5 for AES's 16-byte block size).
|
|
61
|
+
# block_size is 16 bytes (128 bits) for AES.
|
|
62
|
+
padded_data = pad(plain_text_bytes, AES.block_size)
|
|
63
|
+
|
|
64
|
+
# Encrypt the padded data
|
|
65
|
+
ciphertext_bytes = cipher.encrypt(padded_data)
|
|
66
|
+
|
|
67
|
+
# Encode the resulting bytes to Base64 (equivalent to Java's th.b.e())
|
|
68
|
+
return base64.b64encode(ciphertext_bytes).decode("utf-8")
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def validate_header(key: str, value: str) -> bool:
|
|
72
|
+
"""
|
|
73
|
+
Validates if a given header should be included in the signature calculation.
|
|
74
|
+
|
|
75
|
+
Args:
|
|
76
|
+
key: The header key.
|
|
77
|
+
value: The header value.
|
|
78
|
+
|
|
79
|
+
Returns:
|
|
80
|
+
True if the header is valid, False otherwise.
|
|
81
|
+
"""
|
|
82
|
+
lower_key = key.lower()
|
|
83
|
+
|
|
84
|
+
# 1. Check if key is allowed
|
|
85
|
+
if lower_key not in ALLOWED_HEADERS:
|
|
86
|
+
return False
|
|
87
|
+
|
|
88
|
+
# 2. Check x-vin (must be non-empty)
|
|
89
|
+
if lower_key == X_VIN_HEADER:
|
|
90
|
+
return bool(value) # returns true if value is not empty
|
|
91
|
+
|
|
92
|
+
# 3. Check authorization (must be non-empty)
|
|
93
|
+
return (lower_key != AUTH_HEADER) or bool(value)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def map_entry_to_dict_string(key: str, value: str, sb_list: list[str]) -> None:
|
|
97
|
+
"""Builds the Header part of the signature string."""
|
|
98
|
+
lower_key = key.lower()
|
|
99
|
+
sb_list.append(f"{lower_key}:{value}\n")
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def map_entry_to_query_string(key: str, value: str, sb_list: list[str]) -> None:
|
|
103
|
+
"""Builds the Query part of the signature string."""
|
|
104
|
+
encoded_value = value.replace("%2F", "/").replace("%3F", "?").replace("*", "%2A")
|
|
105
|
+
|
|
106
|
+
if sb_list:
|
|
107
|
+
sb_list.append("&")
|
|
108
|
+
sb_list.append(f"{key}={encoded_value}")
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
# --- Core Logic ---
|
|
112
|
+
def calculate_sig(request: PreparedRequest, secret: str) -> str:
|
|
113
|
+
"""Calculates the signature for the given request using the provided secret."""
|
|
114
|
+
# 1. Get request components
|
|
115
|
+
method = request.method
|
|
116
|
+
url_obj = urlparse(request.url)
|
|
117
|
+
headers = request.headers
|
|
118
|
+
|
|
119
|
+
# 2. Build the Canonical Headers String
|
|
120
|
+
# The headers must be filtered, sorted by key, and formatted as 'key:value\n'
|
|
121
|
+
canonical_headers: List[str] = []
|
|
122
|
+
if headers:
|
|
123
|
+
# Filter and sort headers
|
|
124
|
+
filtered_headers = sorted(
|
|
125
|
+
[(k.lower(), v) for k, v in headers.items() if validate_header(k, v)],
|
|
126
|
+
key=lambda item: item[0],
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
for key, value in filtered_headers:
|
|
130
|
+
map_entry_to_dict_string(key, value, canonical_headers)
|
|
131
|
+
|
|
132
|
+
header_string = "".join(canonical_headers)
|
|
133
|
+
|
|
134
|
+
# 3. Build the Canonical Query String
|
|
135
|
+
# Query parameters are extracted, sorted by key, and formatted as 'key=value&...'
|
|
136
|
+
canonical_query: list[str] = []
|
|
137
|
+
if url_obj.query:
|
|
138
|
+
# parse_qs returns a dict of lists; we need to flatten it, assume single values
|
|
139
|
+
query_params = parse_qs(url_obj.query, keep_blank_values=True)
|
|
140
|
+
|
|
141
|
+
# Sort keys and then flatten (assuming no multi-value parameters for simplicity)
|
|
142
|
+
sorted_query_params = sorted(query_params.items())
|
|
143
|
+
|
|
144
|
+
for key, values in sorted_query_params:
|
|
145
|
+
# Assuming single value per key for simplicity
|
|
146
|
+
value = values[0] if values else ""
|
|
147
|
+
map_entry_to_query_string(key, value, canonical_query)
|
|
148
|
+
|
|
149
|
+
query_string = "".join(canonical_query)
|
|
150
|
+
|
|
151
|
+
# 4. Process Body (MD5 Hash for JSON body)
|
|
152
|
+
body_hash_b64 = ""
|
|
153
|
+
# The Java code checks for content-type: application/json
|
|
154
|
+
if "application/json" in headers.get("Content-Type", "").lower():
|
|
155
|
+
# Note: In OkHttp, RequestBody is a stream. In requests, it's usually bytes or a string.
|
|
156
|
+
# We assume the request has a JSON body string/bytes.
|
|
157
|
+
request_body = request.body
|
|
158
|
+
|
|
159
|
+
if request_body:
|
|
160
|
+
try:
|
|
161
|
+
# Parse and canonicalize JSON (Java uses Gson().toJson(JsonObject))
|
|
162
|
+
# Python equivalent: normalize the JSON structure (e.g., sort keys)
|
|
163
|
+
if isinstance(request_body, (str, bytes)):
|
|
164
|
+
body_data = json.loads(request_body)
|
|
165
|
+
# Canonicalize by dumping with sorted keys and no separators/indent
|
|
166
|
+
canonical_json = json.dumps(
|
|
167
|
+
body_data, sort_keys=True, separators=(",", ":")
|
|
168
|
+
)
|
|
169
|
+
else:
|
|
170
|
+
# Fallback for unexpected body type
|
|
171
|
+
canonical_json = str(request_body)
|
|
172
|
+
|
|
173
|
+
# Calculate MD5 hash
|
|
174
|
+
md5_hash = hashlib.md5(canonical_json.encode("utf-8")).digest()
|
|
175
|
+
body_hash_b64 = base64.b64encode(md5_hash).decode("utf-8")
|
|
176
|
+
except Exception:
|
|
177
|
+
# Catch exceptions during body processing (e.g., non-JSON body despite header)
|
|
178
|
+
pass
|
|
179
|
+
|
|
180
|
+
# 5. Build the Signature Base String
|
|
181
|
+
sig_base_list = []
|
|
182
|
+
|
|
183
|
+
# Append canonical headers string
|
|
184
|
+
if header_string:
|
|
185
|
+
sig_base_list.append(header_string)
|
|
186
|
+
|
|
187
|
+
# Append canonical query string + newline
|
|
188
|
+
if query_string:
|
|
189
|
+
sig_base_list.append(query_string)
|
|
190
|
+
sig_base_list.append("\n")
|
|
191
|
+
|
|
192
|
+
# Append MD5 body hash + newline
|
|
193
|
+
if body_hash_b64:
|
|
194
|
+
sig_base_list.append(body_hash_b64)
|
|
195
|
+
sig_base_list.append("\n")
|
|
196
|
+
|
|
197
|
+
# Append HTTP Method + newline
|
|
198
|
+
assert method is not None
|
|
199
|
+
sig_base_list.append(method.upper())
|
|
200
|
+
sig_base_list.append("\n")
|
|
201
|
+
|
|
202
|
+
sig_base_list.append(url_obj.path.rstrip())
|
|
203
|
+
|
|
204
|
+
signature_base_string = "".join(sig_base_list)
|
|
205
|
+
|
|
206
|
+
log.debug("--- DEBUG: SIGNATURE BASE STRING ---")
|
|
207
|
+
log.debug(signature_base_string)
|
|
208
|
+
log.debug("-----------------------------------")
|
|
209
|
+
|
|
210
|
+
# 6. Calculate HMAC-SHA256
|
|
211
|
+
h = hmac.new(
|
|
212
|
+
secret.encode("utf-8"),
|
|
213
|
+
signature_base_string.encode("utf-8"),
|
|
214
|
+
hashlib.sha256,
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
hmac_digest = h.digest()
|
|
218
|
+
|
|
219
|
+
# 7. Base64 Encode the HMAC digest
|
|
220
|
+
signature = base64.b64encode(hmac_digest).decode("utf-8")
|
|
221
|
+
|
|
222
|
+
return signature
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
# --- Intercept Logic (Python Integration) ---
|
|
226
|
+
def sign_request(request: PreparedRequest, secret: str) -> PreparedRequest:
|
|
227
|
+
"""
|
|
228
|
+
Adds the calculated signature to the request headers.
|
|
229
|
+
"""
|
|
230
|
+
# Remove existing signature (though not strictly necessary in requests)
|
|
231
|
+
# Note: requests.Request/PreparedRequest headers are case-insensitive dicts
|
|
232
|
+
if "X-SIGNATURE" in request.headers:
|
|
233
|
+
del request.headers["X-SIGNATURE"]
|
|
234
|
+
|
|
235
|
+
if (
|
|
236
|
+
"x-api-signature-nonce" not in request.headers
|
|
237
|
+
or "X-API-SIGNATURE-NONCE" not in request.headers
|
|
238
|
+
):
|
|
239
|
+
request.headers["X-API-SIGNATURE-NONCE"] = str(uuid.uuid4())
|
|
240
|
+
if "X-TIMESTAMP" not in request.headers or "x-timestamp" not in request.headers:
|
|
241
|
+
request.headers["X-TIMESTAMP"] = str(time.time_ns() // 1000000)
|
|
242
|
+
|
|
243
|
+
# Calculate and add new signature
|
|
244
|
+
signature = calculate_sig(request, secret)
|
|
245
|
+
request.headers["X-SIGNATURE"] = signature
|
|
246
|
+
|
|
247
|
+
log.debug(f"Request Headers: {request.headers}")
|
|
248
|
+
|
|
249
|
+
return request
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import base64
|
|
2
|
+
import datetime
|
|
3
|
+
import hashlib
|
|
4
|
+
import hmac
|
|
5
|
+
import logging
|
|
6
|
+
from typing import Dict
|
|
7
|
+
|
|
8
|
+
from urllib.parse import urlparse
|
|
9
|
+
|
|
10
|
+
from requests import Request
|
|
11
|
+
|
|
12
|
+
log = logging.getLogger(__name__)
|
|
13
|
+
|
|
14
|
+
# EEEE, dd MMM yyyy HH:mm:ss 'GMT'
|
|
15
|
+
DATE_FORMAT = "%a, %d %b %Y %H:%M:%S GMT"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _get_gmt_date() -> str:
|
|
19
|
+
"""Generates the GMT date string for X-DATE and the signature string."""
|
|
20
|
+
now = datetime.datetime.now(datetime.timezone.utc)
|
|
21
|
+
return now.strftime(DATE_FORMAT)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def hmac_sha256_base64(data: str, key: str) -> str:
|
|
25
|
+
"""Calculates Base64(HMAC-SHA256(key, data))"""
|
|
26
|
+
h = hmac.new(key.encode("utf-8"), data.encode("utf-8"), hashlib.sha256)
|
|
27
|
+
return base64.b64encode(h.digest()).decode("utf-8")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def get_canonical_path(path_segments: list[str]) -> str:
|
|
31
|
+
"""Combines path segments into a canonical path, returning '/' if empty."""
|
|
32
|
+
if not path_segments:
|
|
33
|
+
return "/"
|
|
34
|
+
return "/" + "/".join(segment for segment in path_segments if segment)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def parse_query_params(query_string: str) -> Dict[str, str]:
|
|
38
|
+
"""Parses a query string (e.g., 'a=1&b=2') into a dictionary."""
|
|
39
|
+
params: Dict[str, str] = {}
|
|
40
|
+
if not query_string:
|
|
41
|
+
return params
|
|
42
|
+
|
|
43
|
+
pairs = query_string.split("&")
|
|
44
|
+
for pair in pairs:
|
|
45
|
+
parts = pair.split("=", 1) # Split only on the first '='
|
|
46
|
+
if len(parts) == 2:
|
|
47
|
+
key, value = parts
|
|
48
|
+
params[key] = value
|
|
49
|
+
|
|
50
|
+
return params
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def get_canonical_query_string(query_map: Dict[str, str]) -> str:
|
|
54
|
+
"""
|
|
55
|
+
Sorts query parameters case-insensitively by key and formats them
|
|
56
|
+
as 'key1=value1&key2=value2...'.
|
|
57
|
+
"""
|
|
58
|
+
if not query_map:
|
|
59
|
+
return ""
|
|
60
|
+
|
|
61
|
+
# Custom comparator for case-insensitive sort
|
|
62
|
+
# sorted() with a key allows for case-insensitive sorting
|
|
63
|
+
sorted_keys = sorted(query_map.keys(), key=lambda k: k.lower())
|
|
64
|
+
|
|
65
|
+
parts = []
|
|
66
|
+
for key in sorted_keys:
|
|
67
|
+
value = str(query_map.get(key, ""))
|
|
68
|
+
parts.append(f"{key}={value}")
|
|
69
|
+
|
|
70
|
+
return "&".join(parts)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def get_request_body_content(body: str | bytes | None) -> str:
|
|
74
|
+
"""Reads the request body content as a UTF-8 string."""
|
|
75
|
+
if body is None:
|
|
76
|
+
return ""
|
|
77
|
+
|
|
78
|
+
if isinstance(body, bytes):
|
|
79
|
+
return body.decode("utf-8", errors="ignore")
|
|
80
|
+
elif isinstance(body, str):
|
|
81
|
+
return body
|
|
82
|
+
else:
|
|
83
|
+
# Handle other types like files or MultipartBody (which the Java code skips)
|
|
84
|
+
return ""
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def generateHMAC(request: Request, access_key: str,
|
|
88
|
+
secret_key: str) -> Request:
|
|
89
|
+
parsed_url = urlparse(request.url)
|
|
90
|
+
gmt_date = _get_gmt_date()
|
|
91
|
+
|
|
92
|
+
path_segments = (parsed_url.path.strip("/").split("/")
|
|
93
|
+
if parsed_url.path.strip("/") else [])
|
|
94
|
+
canonical_path = get_canonical_path(path_segments)
|
|
95
|
+
|
|
96
|
+
query_map = parse_query_params(parsed_url.query)
|
|
97
|
+
canonical_query = get_canonical_query_string(query_map)
|
|
98
|
+
|
|
99
|
+
sign_string_components = [
|
|
100
|
+
request.method.upper(), # HTTP Method
|
|
101
|
+
canonical_path, # Canonical Path
|
|
102
|
+
canonical_query, # Canonical Query Parameters
|
|
103
|
+
access_key, # Access Key
|
|
104
|
+
gmt_date, # GMT Date
|
|
105
|
+
]
|
|
106
|
+
sign_string = "\n".join(sign_string_components)
|
|
107
|
+
|
|
108
|
+
signature = hmac_sha256_base64(sign_string + "\n", secret_key)
|
|
109
|
+
|
|
110
|
+
request_body_content = get_request_body_content(request.data)
|
|
111
|
+
body_digest = hmac_sha256_base64(request_body_content, secret_key)
|
|
112
|
+
|
|
113
|
+
request.headers["X-HMAC-ALGORITHM"] = "hmac-sha256"
|
|
114
|
+
request.headers["X-HMAC-SIGNATURE"] = signature
|
|
115
|
+
request.headers["X-HMAC-ACCESS-KEY"] = access_key
|
|
116
|
+
request.headers["X-HMAC-DIGEST"] = body_digest
|
|
117
|
+
request.headers["X-DATE"] = gmt_date
|
|
118
|
+
|
|
119
|
+
log.debug(f"Request Headers: {request.headers}")
|
|
120
|
+
|
|
121
|
+
return request
|