zeekr-ev-api 0.1.0__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.
@@ -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.0
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,3 @@
1
+ # zeekr_ev_api
2
+
3
+ API for interacting with Zeekr EVs
@@ -0,0 +1,24 @@
1
+ [project]
2
+ name = "zeekr_ev_api"
3
+ version = "0.1.0"
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,7 @@
1
+ """
2
+ A Python client for the Zeekr EV API.
3
+ """
4
+
5
+ from .client import ZeekrClient, ZeekrException, AuthException
6
+
7
+ __all__ = ["ZeekrClient", "ZeekrException", "AuthException"]
@@ -0,0 +1,365 @@
1
+ """
2
+ Zeekr EV API Client
3
+ """
4
+ import base64
5
+ import json
6
+ from typing import Any
7
+
8
+ import requests
9
+ from Crypto.Cipher import PKCS1_v1_5
10
+ from Crypto.PublicKey import RSA
11
+
12
+ from . import const, network, zeekr_app_sig, zeekr_hmac
13
+
14
+
15
+ class ZeekrException(Exception):
16
+ """Base exception for the library."""
17
+
18
+
19
+ class AuthException(ZeekrException):
20
+ """Exception for authentication errors."""
21
+
22
+
23
+ class ZeekrClient:
24
+ """
25
+ A client for the Zeekr EV API.
26
+ """
27
+
28
+ def __init__(self,
29
+ username: str | None = None,
30
+ password: str | None = None,
31
+ country_code: str = "AU",
32
+ session_data: dict | None = None) -> None:
33
+ """
34
+ Initializes the client.
35
+ """
36
+ self.session: requests.Session = requests.Session()
37
+ self.password: str | None = password
38
+ if session_data:
39
+ self.load_session(session_data)
40
+ else:
41
+ if not username or not password:
42
+ raise ValueError(
43
+ "Username and password are required for a new session.")
44
+ self.username: str = username
45
+ self.country_code: str = country_code
46
+ self.logged_in: bool = False
47
+ self.auth_token: str | None = None
48
+ self.bearer_token: str | None = None
49
+ self.user_info: dict = {}
50
+ self.vin: str | None = None
51
+ self.vehicles: list['Vehicle'] = []
52
+
53
+ # These will be populated during login
54
+ self.app_server_host: str = const.APP_SERVER_HOST
55
+ self.usercenter_host: str = const.USERCENTER_HOST
56
+ self.message_host: str = const.MESSAGE_HOST
57
+ self.region_code: str = const.REGION_CODE
58
+ self.region_login_server: str | None = None
59
+
60
+ def load_session(self, session_data: dict) -> None:
61
+ """Loads a session from a dictionary."""
62
+ self.username = session_data.get("username")
63
+ self.country_code = session_data.get("country_code", "AU")
64
+ self.auth_token = session_data.get("auth_token")
65
+ self.bearer_token = session_data.get("bearer_token")
66
+ self.user_info = session_data.get("user_info", {})
67
+ self.app_server_host = session_data.get("app_server_host")
68
+ self.usercenter_host = session_data.get("usercenter_host")
69
+ self.message_host = session_data.get("message_host")
70
+ self.region_code = session_data.get("region_code")
71
+ self.region_login_server = session_data.get("region_login_server")
72
+ self.vehicles: list['Vehicle'] = []
73
+
74
+ if self.bearer_token:
75
+ self.logged_in = True
76
+ const.LOGGED_IN_HEADERS["authorization"] = self.bearer_token
77
+ if self.auth_token:
78
+ self.session.headers["authorization"] = self.auth_token
79
+ else:
80
+ self.logged_in = False
81
+
82
+ def export_session(self) -> dict:
83
+ """Exports the current session to a dictionary."""
84
+ if not self.logged_in:
85
+ return {}
86
+
87
+ return {
88
+ "username": self.username,
89
+ "country_code": self.country_code,
90
+ "auth_token": self.auth_token,
91
+ "bearer_token": self.bearer_token,
92
+ "user_info": self.user_info,
93
+ "app_server_host": self.app_server_host,
94
+ "usercenter_host": self.usercenter_host,
95
+ "message_host": self.message_host,
96
+ "region_code": self.region_code,
97
+ "region_login_server": self.region_login_server,
98
+ }
99
+
100
+ def _rsa_encrypt_password(self) -> str:
101
+ """
102
+ Encrypts the password using RSA.
103
+ """
104
+ key_bytes = base64.b64decode(const.PASSWORD_PUBLIC_KEY)
105
+ public_key = RSA.import_key(key_bytes)
106
+ cipher = PKCS1_v1_5.new(public_key)
107
+ password_bytes = self.password.encode("utf-8")
108
+ encrypted_bytes = cipher.encrypt(password_bytes)
109
+ return base64.b64encode(encrypted_bytes).decode("utf-8")
110
+
111
+ def login(self) -> None:
112
+ """
113
+ Logs in to the Zeekr API.
114
+ """
115
+ self._get_urls()
116
+ self._check_user()
117
+ self._do_login_request()
118
+ self._get_user_info()
119
+ self._get_protocol()
120
+ self._check_inbox()
121
+ tsp_code, _ = self._get_tsp_code()
122
+ self._update_language()
123
+ # self._sycn_push(login_id) # Disabled for now
124
+ self._bearer_login(tsp_code)
125
+ self.logged_in = True
126
+
127
+ def _get_urls(self) -> None:
128
+ """
129
+ Fetches the regional API URLs.
130
+ """
131
+ urls = network.customGet(self.session,
132
+ f"{const.APP_SERVER_HOST}{const.URL_URL}")
133
+ if not urls.get("success", False):
134
+ raise ZeekrException("Unable to fetch URL data")
135
+
136
+ url_data = urls.get("data", [])
137
+ found = False
138
+ for url_block in url_data:
139
+ if url_block.get("countryCode",
140
+ "").lower() == self.country_code.lower():
141
+ self.app_server_host = url_block.get("url", {}).get(
142
+ "appServerUrl", "")
143
+ self.usercenter_host = url_block.get("url", {}).get(
144
+ "userCenterUrl", "")
145
+ self.message_host = url_block.get("url", {}).get(
146
+ "messageCoreUrl", "")
147
+ self.region_code = url_block.get("regionCode", "SEA")
148
+ found = True
149
+ break
150
+ if not found:
151
+ raise ZeekrException(
152
+ f"Unable to find URLs for country code: {self.country_code}")
153
+
154
+ if not self.app_server_host or not self.usercenter_host or not self.message_host:
155
+ raise ZeekrException(
156
+ "One or more API URLs are blank after fetching.")
157
+
158
+ self.region_login_server = const.REGION_LOGIN_SERVERS.get(
159
+ self.region_code)
160
+ if not self.region_login_server:
161
+ raise ZeekrException(
162
+ f"No login server for region: {self.region_code}")
163
+
164
+ def _check_user(self) -> None:
165
+ """
166
+ Checks if the user exists.
167
+ """
168
+ user_code = network.customPost(
169
+ self.session,
170
+ f"{self.usercenter_host}{const.CHECKUSER_URL}",
171
+ {
172
+ "email": self.username,
173
+ "checkType": "1"
174
+ },
175
+ )
176
+ if not user_code.get("success", False):
177
+ raise AuthException("User check failed")
178
+
179
+ def _do_login_request(self) -> None:
180
+ """
181
+ Performs the main login request.
182
+ """
183
+ encrypted_password = self._rsa_encrypt_password()
184
+ if not encrypted_password:
185
+ raise AuthException("Password encryption failed")
186
+
187
+ request_data = {
188
+ "code": "",
189
+ "codeId": "",
190
+ "email": self.username,
191
+ "password": encrypted_password,
192
+ }
193
+
194
+ req = requests.Request(
195
+ "POST",
196
+ f"{self.usercenter_host}{const.LOGIN_URL}",
197
+ headers=const.DEFAULT_HEADERS,
198
+ json=request_data,
199
+ )
200
+ new_req = zeekr_hmac.generateHMAC(req, const.HMAC_ACCESS_KEY,
201
+ const.HMAC_SECRET_KEY)
202
+ prepped = self.session.prepare_request(new_req)
203
+ resp = self.session.send(prepped)
204
+ login_data = resp.json()
205
+
206
+ if not login_data or not login_data.get("success", False):
207
+ raise AuthException(f"Login failed: {login_data}")
208
+
209
+ login_token = login_data.get("data", {})
210
+ if login_token.get("tokenName", "") != "Authorization":
211
+ raise AuthException(f"Unknown login token type: {login_token}")
212
+
213
+ self.auth_token = login_token.get("tokenValue")
214
+ if not self.auth_token:
215
+ raise AuthException("No auth token supplied in login response")
216
+
217
+ self.session.headers["authorization"] = self.auth_token
218
+
219
+ def _get_user_info(self) -> None:
220
+ """
221
+ Fetches user information.
222
+ """
223
+ user_info_resp = network.customPost(
224
+ self.session, f"{self.usercenter_host}{const.USERINFO_URL}")
225
+ if user_info_resp.get("success", False):
226
+ self.user_info = user_info_resp.get("data", {})
227
+
228
+ def _get_protocol(self) -> None:
229
+ """
230
+ Fetches the protocol.
231
+ """
232
+ network.customPost(
233
+ self.session,
234
+ f"{self.app_server_host}{const.PROTOCOL_URL}",
235
+ {"country": self.country_code},
236
+ )
237
+
238
+ def _check_inbox(self) -> None:
239
+ """
240
+ Checks the inbox.
241
+ """
242
+ network.customGet(self.session,
243
+ f"{self.app_server_host}{const.INBOX_URL}")
244
+
245
+ def _get_tsp_code(self) -> tuple[str, str]:
246
+ """
247
+ Gets the TSP code.
248
+ """
249
+ tsp_code_block = network.customGet(
250
+ self.session,
251
+ f"{self.usercenter_host}{const.TSPCODE_URL}?tspClientId={const.DEFAULT_HEADERS.get('client-id', '')}",
252
+ )
253
+ if not tsp_code_block.get("success", False):
254
+ raise ZeekrException(f"Unable to fetch TSP Code: {tsp_code_block}")
255
+
256
+ tsp_code = tsp_code_block.get("data", {}).get("code")
257
+ login_id = tsp_code_block.get("data", {}).get("loginId")
258
+ if not tsp_code:
259
+ raise ZeekrException(f"No TSP code in response: {tsp_code_block}")
260
+
261
+ return tsp_code, login_id
262
+
263
+ def _update_language(self, language: str = "en") -> None:
264
+ """
265
+ Updates the language.
266
+ """
267
+ network.customGet(
268
+ self.session,
269
+ f"{self.usercenter_host}{const.UPDATELANGUAGE_URL}?language={language}"
270
+ )
271
+
272
+ def _bearer_login(self, tsp_code: str) -> None:
273
+ """
274
+ Performs the bearer token login.
275
+ """
276
+ bearer_body = {
277
+ "identifier": tsp_code,
278
+ "identityType": 10,
279
+ "loginDeviceId": "google-sdk_gphone64_x86_64-36-16",
280
+ "loginDeviceJgId": "",
281
+ "loginDeviceType": 1,
282
+ "loginPhoneBrand": "google",
283
+ "loginPhoneModel": "sdk_gphone64_x86_64",
284
+ "loginSystem": "Android",
285
+ }
286
+
287
+ bearer_login_block = network.appSignedPost(
288
+ self.session,
289
+ f"{self.region_login_server}{const.BEARERLOGIN_URL}",
290
+ json.dumps(bearer_body, separators=(",", ":")),
291
+ )
292
+ if not bearer_login_block.get("success", False):
293
+ raise AuthException(f"Bearer login failed: {bearer_login_block}")
294
+
295
+ bearer_login_data = bearer_login_block.get("data", {})
296
+ self.bearer_token = bearer_login_data.get("accessToken")
297
+ if not self.bearer_token:
298
+ raise AuthException(
299
+ f"No bearer token in response: {bearer_login_data}")
300
+
301
+ const.LOGGED_IN_HEADERS["authorization"] = self.bearer_token
302
+
303
+ def get_vehicle_list(self) -> list['Vehicle']:
304
+ """
305
+ Fetches the list of vehicles.
306
+ """
307
+ if not self.logged_in:
308
+ raise ZeekrException("Not logged in")
309
+
310
+ vehicle_list_block = network.appSignedGet(
311
+ self.session,
312
+ f"{self.region_login_server}{const.VEHLIST_URL}?needSharedCar=true",
313
+ )
314
+ if not vehicle_list_block.get("success", False):
315
+ raise ZeekrException(
316
+ f"Failed to get vehicle list: {vehicle_list_block}")
317
+
318
+ self.vehicles = [
319
+ Vehicle(self, v.get('vin'), v)
320
+ for v in vehicle_list_block.get("data", [])
321
+ ]
322
+ return self.vehicles
323
+
324
+ def get_vehicle_status(self, vin: str) -> Any:
325
+ """
326
+ Fetches the status for a specific vehicle.
327
+ """
328
+ if not self.logged_in:
329
+ raise ZeekrException("Not logged in")
330
+
331
+ encrypted_vin = zeekr_app_sig.aes_encrypt(vin, const.VIN_KEY,
332
+ const.VIN_IV)
333
+
334
+ headers = const.LOGGED_IN_HEADERS.copy()
335
+ headers["X-VIN"] = encrypted_vin
336
+
337
+ vehicle_status_block = network.appSignedGet(
338
+ self.session,
339
+ f"{self.region_login_server}{const.VEHICLESTATUS_URL}?latest=false&target=new",
340
+ headers=headers)
341
+ if not vehicle_status_block.get("success", False):
342
+ raise ZeekrException(
343
+ f"Failed to get vehicle status: {vehicle_status_block}")
344
+
345
+ return vehicle_status_block.get("data", {})
346
+
347
+
348
+ class Vehicle:
349
+ """
350
+ Represents a Zeekr vehicle.
351
+ """
352
+
353
+ def __init__(self, client: "ZeekrClient", vin: str, data: dict) -> None:
354
+ self._client = client
355
+ self.vin = vin
356
+ self.data = data
357
+
358
+ def __repr__(self) -> str:
359
+ return f"<Vehicle {self.vin}>"
360
+
361
+ def get_status(self) -> Any:
362
+ """
363
+ Fetches the vehicle status.
364
+ """
365
+ return self._client.get_vehicle_status(self.vin)
@@ -0,0 +1,82 @@
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
+
23
+ COUNTRY_CODE = "AU"
24
+ REGION_CODE = "SEA"
25
+
26
+ REGION_LOGIN_SERVERS = {
27
+ "SEA": "https://sea-snc-tsp-api-gw.zeekrlife.com/",
28
+ "UAE": "https://me-snc-tsp-api-gw.zeekrlife.com/",
29
+ "LA": "https://la-snc-tsp-api-gw.zeekrlife.com/",
30
+ "EU": "https://eu-snc-tsp-api-gw.zeekrlife.com/",
31
+ }
32
+
33
+ # Secrets
34
+ HMAC_ACCESS_KEY = ""
35
+ HMAC_SECRET_KEY = ""
36
+ PASSWORD_PUBLIC_KEY = ""
37
+ PROD_SECRET = ""
38
+
39
+ DEFAULT_HEADERS = {
40
+ "accept-encoding": "gzip",
41
+ "accept-language": "en-AU",
42
+ "app-authorization": "1003",
43
+ "app-code": "32816dbd-ff17-47b7-e250-5dae7d9f8cd4",
44
+ "appcode": "eu-app",
45
+ "appid": "TSP",
46
+ "appsecret": "zeekr_tis",
47
+ "appversion": "1.4.1",
48
+ "call-source": "android",
49
+ "client-id": "1JwLroFkFFIpgFGdTRrm4_nzkkwDkfHj7RxJQb7J8tc",
50
+ "Content-Type": "application/json; charset=UTF-8",
51
+ "country": COUNTRY_CODE,
52
+ "device-name": "sdk_gphone64_x86_64",
53
+ "device-type": "app",
54
+ "language": "en",
55
+ "msgappid": "11002",
56
+ "msgclientid": "1003",
57
+ "registcountry": COUNTRY_CODE,
58
+ "tmp-tenant-code": "3300743799505195008",
59
+ "user-agent": "Device/GoogleAppName/com.zeekr.globalAppVersion/1.4.1Platform/androidOSVersion/16Ditto/true",
60
+ }
61
+
62
+ LOGGED_IN_HEADERS = {
63
+ "Accept-Encoding": "gzip",
64
+ "ACCEPT-LANGUAGE": "en-AU",
65
+ "AppId": "ONEX97FB91F061405",
66
+ "authorization": "",
67
+ "Content-Type": "application/json; charset=UTF-8",
68
+ "user-agent": "okhttp/4.12.0",
69
+ "X-API-SIGNATURE-VERSION": "2.0",
70
+ "X-APP-ID": "ZEEKRCNCH001M0001",
71
+ "x-app-os-version": "",
72
+ "x-device-id": str(uuid.uuid4()),
73
+ "x-p": "Android",
74
+ "X-PLATFORM": "APP",
75
+ "X-PROJECT-ID": "ZEEKR_SEA",
76
+ }
77
+
78
+ # Car Details
79
+ CAR_MODELS = {}
80
+ VIN = ""
81
+ VIN_KEY = ""
82
+ VIN_IV = ""
@@ -0,0 +1,81 @@
1
+ import logging
2
+ from typing import Any
3
+
4
+ from requests import Request, Session
5
+ from . import const, zeekr_app_sig, zeekr_hmac
6
+
7
+ log = logging.getLogger(__name__)
8
+
9
+
10
+ def customPost(s: Session, url: str, body: dict | None = None) -> Any:
11
+ """ Sends a signed POST request with HMAC authentication. """
12
+ req = Request("POST", url, headers=const.DEFAULT_HEADERS, json=body)
13
+ req = zeekr_hmac.generateHMAC(req, const.HMAC_ACCESS_KEY,
14
+ const.HMAC_SECRET_KEY)
15
+
16
+ prepped = s.prepare_request(req)
17
+ resp = s.send(prepped)
18
+ log.debug("------ HEADERS ------")
19
+ log.debug(resp.headers)
20
+ log.debug("------ RESPONSE ------")
21
+ log.debug(resp.text)
22
+
23
+ return resp.json()
24
+
25
+
26
+ def customGet(s: Session, url: str) -> Any:
27
+ """ Sends a signed GET request with HMAC authentication. """
28
+ req = Request("GET", url, headers=const.DEFAULT_HEADERS)
29
+ req = zeekr_hmac.generateHMAC(req, const.HMAC_ACCESS_KEY,
30
+ const.HMAC_SECRET_KEY)
31
+
32
+ prepped = s.prepare_request(req)
33
+ resp = s.send(prepped)
34
+ log.debug("------ HEADERS ------")
35
+ log.debug(resp.headers)
36
+ log.debug("------ RESPONSE ------")
37
+ log.debug(resp.text)
38
+
39
+ return resp.json()
40
+
41
+
42
+ def appSignedPost(s: Session, url: str, body: str | None = None) -> Any:
43
+ """ Sends a signed POST request with an app signature. """
44
+ req = Request("POST", url, headers=const.LOGGED_IN_HEADERS, data=body)
45
+ prepped = s.prepare_request(req)
46
+
47
+ final = zeekr_app_sig.sign_request(prepped, const.PROD_SECRET)
48
+
49
+ log.debug("--- Signed Request Details ---")
50
+ log.debug(f"Method: {final.method}")
51
+ log.debug(f"URL: {final.url}")
52
+ log.debug("Headers:")
53
+ for k, v in final.headers.items():
54
+ log.debug(f" {k}: {v}")
55
+ log.debug(f"Body: {final.body or ''}")
56
+ log.debug(f"\nX-SIGNATURE: {final.headers['X-SIGNATURE']}")
57
+
58
+ resp = s.send(final)
59
+ log.debug("------ HEADERS ------")
60
+ log.debug(resp.headers)
61
+ log.debug("------ RESPONSE ------")
62
+ log.debug(resp.text)
63
+
64
+ return resp.json()
65
+
66
+
67
+ def appSignedGet(s: Session, url: str, headers: dict | None = None) -> Any:
68
+ """ Sends a signed GET request with an app signature. """
69
+ req = Request("GET", url, headers=const.LOGGED_IN_HEADERS)
70
+ if headers:
71
+ req.headers.update(headers)
72
+ prepped = s.prepare_request(req)
73
+
74
+ final = zeekr_app_sig.sign_request(prepped, const.PROD_SECRET)
75
+ resp = s.send(final)
76
+ log.debug("------ HEADERS ------")
77
+ log.debug(resp.headers)
78
+ log.debug("------ RESPONSE ------")
79
+ log.debug(resp.text)
80
+
81
+ return resp.json()
@@ -0,0 +1,252 @@
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"),
58
+ AES.MODE_CBC,
59
+ iv=iv_hex.encode("utf-8"))
60
+
61
+ # Apply PKCS7 Padding (PyCryptodome's `pad` function defaults to PKCS7,
62
+ # which is equivalent to PKCS5 for AES's 16-byte block size).
63
+ # block_size is 16 bytes (128 bits) for AES.
64
+ padded_data = pad(plain_text_bytes, AES.block_size)
65
+
66
+ # Encrypt the padded data
67
+ ciphertext_bytes = cipher.encrypt(padded_data)
68
+
69
+ # Encode the resulting bytes to Base64 (equivalent to Java's th.b.e())
70
+ return base64.b64encode(ciphertext_bytes).decode("utf-8")
71
+
72
+
73
+ def validate_header(key: str, value: str) -> bool:
74
+ """
75
+ Validates if a given header should be included in the signature calculation.
76
+
77
+ Args:
78
+ key: The header key.
79
+ value: The header value.
80
+
81
+ Returns:
82
+ True if the header is valid, False otherwise.
83
+ """
84
+ lower_key = key.lower()
85
+
86
+ # 1. Check if key is allowed
87
+ if lower_key not in ALLOWED_HEADERS:
88
+ return False
89
+
90
+ # 2. Check x-vin (must be non-empty)
91
+ if lower_key == X_VIN_HEADER:
92
+ return bool(value) # returns true if value is not empty
93
+
94
+ # 3. Check authorization (must be non-empty)
95
+ return (lower_key != AUTH_HEADER) or bool(value)
96
+
97
+
98
+ def map_entry_to_dict_string(key: str, value: str, sb_list: list[str]) -> None:
99
+ """Builds the Header part of the signature string."""
100
+ lower_key = key.lower()
101
+ sb_list.append(f"{lower_key}:{value}\n")
102
+
103
+
104
+ def map_entry_to_query_string(key: str, value: str,
105
+ sb_list: list[str]) -> None:
106
+ """Builds the Query part of the signature string."""
107
+ encoded_value = value.replace("%2F", "/").replace("%3F",
108
+ "?").replace("*", "%2A")
109
+
110
+ if sb_list:
111
+ sb_list.append("&")
112
+ sb_list.append(f"{key}={encoded_value}")
113
+
114
+
115
+ # --- Core Logic ---
116
+ def calculate_sig(request: PreparedRequest, secret: str) -> str:
117
+ """ Calculates the signature for the given request using the provided secret. """
118
+ # 1. Get request components
119
+ method = request.method
120
+ url_obj = urlparse(request.url)
121
+ headers = request.headers
122
+
123
+ # 2. Build the Canonical Headers String
124
+ # The headers must be filtered, sorted by key, and formatted as 'key:value\n'
125
+ canonical_headers: List[str] = []
126
+ if headers:
127
+ # Filter and sort headers
128
+ filtered_headers = sorted(
129
+ [(k.lower(), v)
130
+ for k, v in headers.items() if validate_header(k, v)],
131
+ key=lambda item: item[0],
132
+ )
133
+
134
+ for key, value in filtered_headers:
135
+ map_entry_to_dict_string(key, value, canonical_headers)
136
+
137
+ header_string = "".join(canonical_headers)
138
+
139
+ # 3. Build the Canonical Query String
140
+ # Query parameters are extracted, sorted by key, and formatted as 'key=value&...'
141
+ canonical_query: list[str] = []
142
+ if url_obj.query:
143
+ # parse_qs returns a dict of lists; we need to flatten it, assume single values
144
+ query_params = parse_qs(url_obj.query, keep_blank_values=True)
145
+
146
+ # Sort keys and then flatten (assuming no multi-value parameters for simplicity)
147
+ sorted_query_params = sorted(query_params.items())
148
+
149
+ for key, values in sorted_query_params:
150
+ # Assuming single value per key for simplicity
151
+ value = values[0] if values else ""
152
+ map_entry_to_query_string(key, value, canonical_query)
153
+
154
+ query_string = "".join(canonical_query)
155
+
156
+ # 4. Process Body (MD5 Hash for JSON body)
157
+ body_hash_b64 = ""
158
+ # The Java code checks for content-type: application/json
159
+ if "application/json" in headers.get("Content-Type", "").lower():
160
+ # Note: In OkHttp, RequestBody is a stream. In requests, it's usually bytes or a string.
161
+ # We assume the request has a JSON body string/bytes.
162
+ request_body = request.body
163
+
164
+ if request_body:
165
+ try:
166
+ # Parse and canonicalize JSON (Java uses Gson().toJson(JsonObject))
167
+ # Python equivalent: normalize the JSON structure (e.g., sort keys)
168
+ if isinstance(request_body, (str, bytes)):
169
+ body_data = json.loads(request_body)
170
+ # Canonicalize by dumping with sorted keys and no separators/indent
171
+ canonical_json = json.dumps(body_data,
172
+ sort_keys=True,
173
+ separators=(",", ":"))
174
+ else:
175
+ # Fallback for unexpected body type
176
+ canonical_json = str(request_body)
177
+
178
+ # Calculate MD5 hash
179
+ md5_hash = hashlib.md5(canonical_json.encode("utf-8")).digest()
180
+ body_hash_b64 = base64.b64encode(md5_hash).decode("utf-8")
181
+ except Exception:
182
+ # Catch exceptions during body processing (e.g., non-JSON body despite header)
183
+ pass
184
+
185
+ # 5. Build the Signature Base String
186
+ sig_base_list = []
187
+
188
+ # Append canonical headers string
189
+ if header_string:
190
+ sig_base_list.append(header_string)
191
+
192
+ # Append canonical query string + newline
193
+ if query_string:
194
+ sig_base_list.append(query_string)
195
+ sig_base_list.append("\n")
196
+
197
+ # Append MD5 body hash + newline
198
+ if body_hash_b64:
199
+ sig_base_list.append(body_hash_b64)
200
+ sig_base_list.append("\n")
201
+
202
+ # Append HTTP Method + newline
203
+ assert method is not None
204
+ sig_base_list.append(method.upper())
205
+ sig_base_list.append("\n")
206
+
207
+ sig_base_list.append(url_obj.path.rstrip())
208
+
209
+ signature_base_string = "".join(sig_base_list)
210
+
211
+ log.debug("--- DEBUG: SIGNATURE BASE STRING ---")
212
+ log.debug(signature_base_string)
213
+ log.debug("-----------------------------------")
214
+
215
+ # 6. Calculate HMAC-SHA256
216
+ h = hmac.new(
217
+ secret.encode("utf-8"),
218
+ signature_base_string.encode("utf-8"),
219
+ hashlib.sha256,
220
+ )
221
+
222
+ hmac_digest = h.digest()
223
+
224
+ # 7. Base64 Encode the HMAC digest
225
+ signature = base64.b64encode(hmac_digest).decode("utf-8")
226
+
227
+ return signature
228
+
229
+
230
+ # --- Intercept Logic (Python Integration) ---
231
+ def sign_request(request: PreparedRequest, secret: str) -> PreparedRequest:
232
+ """
233
+ Adds the calculated signature to the request headers.
234
+ """
235
+ # Remove existing signature (though not strictly necessary in requests)
236
+ # Note: requests.Request/PreparedRequest headers are case-insensitive dicts
237
+ if "X-SIGNATURE" in request.headers:
238
+ del request.headers["X-SIGNATURE"]
239
+
240
+ if ("x-api-signature-nonce" not in request.headers
241
+ or "X-API-SIGNATURE-NONCE" not in request.headers):
242
+ request.headers["X-API-SIGNATURE-NONCE"] = str(uuid.uuid4())
243
+ if "X-TIMESTAMP" not in request.headers or "x-timestamp" not in request.headers:
244
+ request.headers["X-TIMESTAMP"] = str(time.time_ns() // 1000000)
245
+
246
+ # Calculate and add new signature
247
+ signature = calculate_sig(request, secret)
248
+ request.headers["X-SIGNATURE"] = signature
249
+
250
+ log.debug(f"Request Headers: {request.headers}")
251
+
252
+ 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