pydanfoss-cloud 0.1.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.
- pydanfoss_cloud/README.md +44 -0
- pydanfoss_cloud/__init__.py +49 -0
- pydanfoss_cloud/_tuya/__init__.py +10 -0
- pydanfoss_cloud/_tuya/http.py +246 -0
- pydanfoss_cloud/_tuya/postdata.py +113 -0
- pydanfoss_cloud/_tuya/sign.py +80 -0
- pydanfoss_cloud/client.py +514 -0
- pydanfoss_cloud/const.py +76 -0
- pydanfoss_cloud/decode.py +236 -0
- pydanfoss_cloud/keys.py +49 -0
- pydanfoss_cloud/local/__init__.py +1 -0
- pydanfoss_cloud/local/manager.py +98 -0
- pydanfoss_cloud/local/tunnel.py +727 -0
- pydanfoss_cloud/rooms.py +70 -0
- pydanfoss_cloud/schedule.py +250 -0
- pydanfoss_cloud/writes.py +28 -0
- pydanfoss_cloud-0.1.0.dist-info/METADATA +71 -0
- pydanfoss_cloud-0.1.0.dist-info/RECORD +21 -0
- pydanfoss_cloud-0.1.0.dist-info/WHEEL +5 -0
- pydanfoss_cloud-0.1.0.dist-info/licenses/LICENSE +21 -0
- pydanfoss_cloud-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# pydanfoss-cloud
|
|
2
|
+
|
|
3
|
+
Bibliothèque d'accès à l'**API cloud non officielle Danfoss Ally** (voie 1a, celle de
|
|
4
|
+
l'application mobile — sans application développeur ni quota partagé), extraite de l'intégration
|
|
5
|
+
Home Assistant [`danfoss_ally_cloud`](https://github.com/aghulas/ha-danfoss-ally). **Sans dépendance
|
|
6
|
+
Home Assistant.**
|
|
7
|
+
|
|
8
|
+
Elle fournit :
|
|
9
|
+
|
|
10
|
+
- `CloudClient` — login email/mot de passe (+ secrets d'installation), liste des têtes, écritures
|
|
11
|
+
gardées (`tuya.m.custom.wkf.settings.change`), re-authentification robuste.
|
|
12
|
+
- `decode` / `DanfossDevice` — décodage des `dps` Tuya en un modèle normalisé (schéma produit
|
|
13
|
+
`03wvrwpv`), décodage des codes défaut E1–E15.
|
|
14
|
+
- `writes` — validation des valeurs avant envoi et garde-fou par modèle.
|
|
15
|
+
- `keys` — récupération des `localKey` + IP LAN des passerelles depuis le cloud.
|
|
16
|
+
- `local/` — tunnel Zigbee local (DP 198→199, tinytuya) : lecture/écriture d'attributs (pré-chauffage
|
|
17
|
+
0x0025), programme hebdomadaire.
|
|
18
|
+
|
|
19
|
+
## Statut d'extraction (roadmap v0.6)
|
|
20
|
+
|
|
21
|
+
Source **unique** : ce dossier (`custom_components/danfoss_ally_cloud/api/`). Il est packagé sous le
|
|
22
|
+
nom `pydanfoss_cloud` par le `pyproject.toml` du dépôt, **sans déplacement de fichiers** :
|
|
23
|
+
|
|
24
|
+
- l'intégration Home Assistant continue de « vendre » ce code (import relatif `from .api import …`),
|
|
25
|
+
ce qui garde l'installation HACS autonome ;
|
|
26
|
+
- le connecteur MCP (`danfoss-ally-mcp`) pourra en dépendre via `pip install pydanfoss-cloud` une
|
|
27
|
+
fois la bibliothèque **publiée sur PyPI**, puis l'intégration basculera vers une dépendance
|
|
28
|
+
`requirements` du `manifest.json`.
|
|
29
|
+
|
|
30
|
+
Installation en développement :
|
|
31
|
+
|
|
32
|
+
```
|
|
33
|
+
pip install -e . # expose le paquet pydanfoss_cloud
|
|
34
|
+
pip install -e '.[local]' # + tinytuya pour le tunnel local
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## Dépendances
|
|
38
|
+
|
|
39
|
+
`pycryptodome`, `requests` (cœur) ; `tinytuya` (extra `local`, tunnel Zigbee). Python ≥ 3.12.
|
|
40
|
+
|
|
41
|
+
## Avertissement
|
|
42
|
+
|
|
43
|
+
API non documentée, obtenue par observation du protocole de l'application : elle peut changer ou
|
|
44
|
+
être coupée. Secrets (jeton de session, `localKey`, identifiants) : jamais journalisés ni commités.
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Couche d'accès Danfoss Ally — bibliothèque réutilisable, sans dépendance Home Assistant.
|
|
2
|
+
|
|
3
|
+
Ce dossier EST la bibliothèque `pydanfoss-cloud` (cf. README.md ici) : le `pyproject.toml` du dépôt
|
|
4
|
+
le package sous le nom `pydanfoss_cloud` sans déplacer les fichiers. L'intégration le « vend » par
|
|
5
|
+
import relatif (`from .api import …`) pour rester autonome côté HACS ; le connecteur MCP pourra en
|
|
6
|
+
dépendre via PyPI une fois publié, puis l'intégration basculera vers manifest.json -> requirements.
|
|
7
|
+
|
|
8
|
+
Réutilisation (voir docs/reuse.md) :
|
|
9
|
+
- client et signature de l'application : ~/dev/danfoss-ally-signing-re
|
|
10
|
+
- récupération des clés, DP : ~/dev/danfoss-ally-mcp (tuya/pilote_tuya.py)
|
|
11
|
+
- tunnel Zigbee DP 198/199 : ~/dev/danfoss-ally-mcp (local.py)
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from . import schedule
|
|
17
|
+
from .client import (
|
|
18
|
+
CloudAuthError,
|
|
19
|
+
CloudClient,
|
|
20
|
+
CloudError,
|
|
21
|
+
CloudWriteError,
|
|
22
|
+
ScheduleValidationError,
|
|
23
|
+
UnknownTargetError,
|
|
24
|
+
)
|
|
25
|
+
from .decode import DanfossDevice, decoder, decoder_operation, etat_tete
|
|
26
|
+
from .keys import GatewayKey, async_fetch_gateway_keys
|
|
27
|
+
from .schedule import Schedule, count_transitions, validate_days
|
|
28
|
+
from .writes import ecriture_autorisee, encode_consigne
|
|
29
|
+
|
|
30
|
+
__all__ = [
|
|
31
|
+
"CloudAuthError",
|
|
32
|
+
"CloudClient",
|
|
33
|
+
"CloudError",
|
|
34
|
+
"CloudWriteError",
|
|
35
|
+
"DanfossDevice",
|
|
36
|
+
"GatewayKey",
|
|
37
|
+
"Schedule",
|
|
38
|
+
"ScheduleValidationError",
|
|
39
|
+
"UnknownTargetError",
|
|
40
|
+
"async_fetch_gateway_keys",
|
|
41
|
+
"count_transitions",
|
|
42
|
+
"decoder",
|
|
43
|
+
"decoder_operation",
|
|
44
|
+
"ecriture_autorisee",
|
|
45
|
+
"encode_consigne",
|
|
46
|
+
"etat_tete",
|
|
47
|
+
"schedule",
|
|
48
|
+
"validate_days",
|
|
49
|
+
]
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""Pile Tuya « voie 1a » vendue depuis danfoss-ally-mcp (reverse validé en réel).
|
|
2
|
+
|
|
3
|
+
Trois modules purs (stdlib + requests + pycryptodome), sans l'app ni frida :
|
|
4
|
+
- ``sign`` : signature HMAC-SHA256 du canonical.
|
|
5
|
+
- ``postdata`` : chiffrement AES-GCM du postData (requête et réponse).
|
|
6
|
+
- ``http`` : client HTTP bas niveau des méthodes ``m.*`` et flux de login.
|
|
7
|
+
|
|
8
|
+
À extraire à terme en bibliothèque partagée avec le connecteur MCP (roadmap v0.6).
|
|
9
|
+
Ne jamais logguer sign_key, sid, ecode ni chKey.
|
|
10
|
+
"""
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
"""Client HTTP bas niveau de l'API mobile Tuya (app Danfoss Ally), 100 % hors app.
|
|
2
|
+
|
|
3
|
+
S'appuie sur ``sign`` (HMAC-SHA256) + ``postdata`` (AES-GCM). Endpoint selon le datacenter
|
|
4
|
+
(EU/US/CN/IN). En-tête ``User-Agent: Thing-UA=...`` obligatoire. Matériel requis :
|
|
5
|
+
- SESSION : ``sid`` et ``ecode`` issus du login (stables tant que l'app reste connectée).
|
|
6
|
+
- INSTALLATION : ``sign_key``, ``deviceId``, ``chKey`` (capturés une fois, stables).
|
|
7
|
+
|
|
8
|
+
Reverse et flux de login validés en réel (voir danfoss-ally-mcp/tuya/client_http.py). Appels
|
|
9
|
+
synchrones (requests) : l'intégration HA les exécute dans l'executor.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import hashlib
|
|
15
|
+
import json
|
|
16
|
+
import time
|
|
17
|
+
import uuid
|
|
18
|
+
|
|
19
|
+
import requests
|
|
20
|
+
|
|
21
|
+
from .postdata import build_request_body, decrypt_response
|
|
22
|
+
|
|
23
|
+
ENDPOINT_EU = "https://a1.tuyaeu.com/api.json"
|
|
24
|
+
ENDPOINT_US = "https://a1.tuyaus.com/api.json"
|
|
25
|
+
ENDPOINT_CN = "https://a1.tuyacn.com/api.json"
|
|
26
|
+
ENDPOINT_IN = "https://a1.tuyain.com/api.json"
|
|
27
|
+
DEFAULT_ENDPOINT = ENDPOINT_EU
|
|
28
|
+
|
|
29
|
+
ENDPOINTS = {
|
|
30
|
+
"eu": ENDPOINT_EU,
|
|
31
|
+
"us": ENDPOINT_US,
|
|
32
|
+
"cn": ENDPOINT_CN,
|
|
33
|
+
"in": ENDPOINT_IN,
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
USER_AGENT = "Thing-UA=APP/Android/1.4.3/SDK/6.2.0"
|
|
37
|
+
DEFAULT_CLIENT_ID = "7kypwcaqcvw3uvr7u95a"
|
|
38
|
+
DEFAULT_TTID = "sdk_international@7kypwcaqcvw3uvr7u95a"
|
|
39
|
+
DEFAULT_APP_VERSION = "1.4.3"
|
|
40
|
+
DEFAULT_LANG = "en_US"
|
|
41
|
+
DEFAULT_OS = "Android"
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class TuyaApiError(RuntimeError):
|
|
45
|
+
"""Erreur renvoyée par le cloud (enveloppe success=false ou errorCode présent)."""
|
|
46
|
+
|
|
47
|
+
def __init__(self, code, msg, raw):
|
|
48
|
+
super().__init__(f"{code}: {msg}")
|
|
49
|
+
self.code = code
|
|
50
|
+
self.msg = msg
|
|
51
|
+
self.raw = raw
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class TuyaHttpClient:
|
|
55
|
+
"""Client bas niveau des méthodes ``m.*`` (lecture/écriture), 100 % hors app."""
|
|
56
|
+
|
|
57
|
+
def __init__(
|
|
58
|
+
self,
|
|
59
|
+
sign_key: str,
|
|
60
|
+
sid: str,
|
|
61
|
+
ecode: str,
|
|
62
|
+
ch_key: str,
|
|
63
|
+
device_id: str,
|
|
64
|
+
*,
|
|
65
|
+
endpoint: str = DEFAULT_ENDPOINT,
|
|
66
|
+
client_id: str = DEFAULT_CLIENT_ID,
|
|
67
|
+
ttid: str = DEFAULT_TTID,
|
|
68
|
+
app_version: str = DEFAULT_APP_VERSION,
|
|
69
|
+
lang: str = DEFAULT_LANG,
|
|
70
|
+
os_name: str = DEFAULT_OS,
|
|
71
|
+
timeout: float = 20.0,
|
|
72
|
+
):
|
|
73
|
+
self.sign_key = sign_key
|
|
74
|
+
self.sid = sid
|
|
75
|
+
self.ecode = ecode
|
|
76
|
+
self.ch_key = ch_key
|
|
77
|
+
self.device_id = device_id
|
|
78
|
+
self.endpoint = endpoint
|
|
79
|
+
self.client_id = client_id
|
|
80
|
+
self.ttid = ttid
|
|
81
|
+
self.app_version = app_version
|
|
82
|
+
self.lang = lang
|
|
83
|
+
self.os_name = os_name
|
|
84
|
+
self.timeout = timeout
|
|
85
|
+
self.http = requests.Session()
|
|
86
|
+
self.http.headers["User-Agent"] = USER_AGENT
|
|
87
|
+
|
|
88
|
+
def _base_params(self, api: str, version: str, et: str) -> dict:
|
|
89
|
+
return {
|
|
90
|
+
"a": api,
|
|
91
|
+
"v": version,
|
|
92
|
+
"et": et,
|
|
93
|
+
"os": self.os_name,
|
|
94
|
+
"lang": self.lang,
|
|
95
|
+
"clientId": self.client_id,
|
|
96
|
+
"ttid": self.ttid,
|
|
97
|
+
"appVersion": self.app_version,
|
|
98
|
+
"deviceId": self.device_id,
|
|
99
|
+
"sid": self.sid,
|
|
100
|
+
"chKey": self.ch_key,
|
|
101
|
+
"requestId": str(uuid.uuid4()),
|
|
102
|
+
"time": str(int(time.time())),
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
def request(
|
|
106
|
+
self,
|
|
107
|
+
api: str,
|
|
108
|
+
version: str,
|
|
109
|
+
body=None,
|
|
110
|
+
*,
|
|
111
|
+
et: str = "3",
|
|
112
|
+
raw: bool = False,
|
|
113
|
+
extra_params: dict | None = None,
|
|
114
|
+
):
|
|
115
|
+
"""Envoie une requête ``m.*`` signée+chiffrée et renvoie le ``result`` déchiffré.
|
|
116
|
+
|
|
117
|
+
`extra_params` : paramètres d'URL non signés (hors SIGN_WHITELIST), p.ex. ``gid``.
|
|
118
|
+
Lève TuyaApiError si le cloud renvoie une erreur.
|
|
119
|
+
"""
|
|
120
|
+
params = self._base_params(api, version, et)
|
|
121
|
+
if extra_params:
|
|
122
|
+
params.update({k: str(v) for k, v in extra_params.items()})
|
|
123
|
+
request_id = params["requestId"]
|
|
124
|
+
if body is not None and not isinstance(body, (str, bytes)):
|
|
125
|
+
body = json.dumps(body, separators=(",", ":"), ensure_ascii=False)
|
|
126
|
+
form = build_request_body(params, body, self.sign_key, self.ecode)
|
|
127
|
+
resp = self.http.post(self.endpoint, data=form, timeout=self.timeout)
|
|
128
|
+
resp.raise_for_status()
|
|
129
|
+
env = resp.json()
|
|
130
|
+
if env.get("errorCode") or env.get("success") is False:
|
|
131
|
+
raise TuyaApiError(env.get("errorCode"), env.get("errorMsg"), env)
|
|
132
|
+
result = env.get("result")
|
|
133
|
+
if isinstance(result, str): # et=3 : result chiffré -> déchiffrer + gunzip
|
|
134
|
+
inner = json.loads(decrypt_response(result, request_id, self.ecode, self.sign_key))
|
|
135
|
+
if inner.get("success") is False or inner.get("errorCode"):
|
|
136
|
+
raise TuyaApiError(inner.get("errorCode"), inner.get("errorMsg"), inner)
|
|
137
|
+
return inner if raw else inner.get("result", inner)
|
|
138
|
+
return env if raw else result
|
|
139
|
+
|
|
140
|
+
def close(self):
|
|
141
|
+
self.http.close()
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
# --- LOGIN / bootstrap de session -------------------------------------------------------------
|
|
145
|
+
# Flux e-mail + mot de passe, confirmé par capture. 3 requêtes et=3 SANS sid (pré-session) mais
|
|
146
|
+
# AVEC le chKey d'installation. chKey est du matériel d'INSTALLATION (stable), pas de session.
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def md5_as_base64(s: str) -> str:
|
|
150
|
+
"""MD5Util.md5AsBase64 — nom trompeur : renvoie en fait le MD5 en HEXADÉCIMAL (32 car.)."""
|
|
151
|
+
return hashlib.md5(s.encode("utf-8")).hexdigest()
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def encrypt_password(password: str, public_key_decimal: str, exponent: str) -> str:
|
|
155
|
+
"""passwd du login : HEX(RSA/ECB/PKCS1(md5_hex(password))). Clé publique = module en décimal."""
|
|
156
|
+
from Crypto.Cipher import PKCS1_v1_5
|
|
157
|
+
from Crypto.PublicKey import RSA
|
|
158
|
+
|
|
159
|
+
rsa_key = RSA.construct((int(public_key_decimal), int(exponent)))
|
|
160
|
+
ciph = PKCS1_v1_5.new(rsa_key).encrypt(md5_as_base64(password).encode("utf-8"))
|
|
161
|
+
return ciph.hex()
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def login(
|
|
165
|
+
email: str,
|
|
166
|
+
password: str,
|
|
167
|
+
country_code: str,
|
|
168
|
+
sign_key: str,
|
|
169
|
+
device_id: str,
|
|
170
|
+
ch_key: str,
|
|
171
|
+
*,
|
|
172
|
+
endpoint: str = DEFAULT_ENDPOINT,
|
|
173
|
+
client_id: str = DEFAULT_CLIENT_ID,
|
|
174
|
+
ttid: str = DEFAULT_TTID,
|
|
175
|
+
app_version: str = DEFAULT_APP_VERSION,
|
|
176
|
+
lang: str = DEFAULT_LANG,
|
|
177
|
+
timeout: float = 20.0,
|
|
178
|
+
) -> dict:
|
|
179
|
+
"""LOGIN e-mail/mot de passe (flux confirmé par capture).
|
|
180
|
+
|
|
181
|
+
Renvoie {sid, ecode, chKey, deviceId, uid}.
|
|
182
|
+
`ch_key`, `sign_key`, `device_id` = matériel d'installation (capturé une fois). Les identifiants
|
|
183
|
+
sont fournis à l'exécution et ne sont jamais stockés ni journalisés par cette fonction.
|
|
184
|
+
"""
|
|
185
|
+
http = requests.Session()
|
|
186
|
+
http.headers["User-Agent"] = USER_AGENT
|
|
187
|
+
|
|
188
|
+
def _send(api, version, post):
|
|
189
|
+
params = {
|
|
190
|
+
"a": api,
|
|
191
|
+
"v": version,
|
|
192
|
+
"et": "3",
|
|
193
|
+
"os": DEFAULT_OS,
|
|
194
|
+
"lang": lang,
|
|
195
|
+
"clientId": client_id,
|
|
196
|
+
"ttid": ttid,
|
|
197
|
+
"appVersion": app_version,
|
|
198
|
+
"deviceId": device_id,
|
|
199
|
+
"chKey": ch_key,
|
|
200
|
+
"requestId": str(uuid.uuid4()),
|
|
201
|
+
"time": str(int(time.time())),
|
|
202
|
+
}
|
|
203
|
+
request_id = params["requestId"]
|
|
204
|
+
body = json.dumps(post, separators=(",", ":"), ensure_ascii=False)
|
|
205
|
+
form = build_request_body(params, body, sign_key, "") # pré-login : ecode=""
|
|
206
|
+
r = http.post(endpoint, data=form, timeout=timeout)
|
|
207
|
+
r.raise_for_status()
|
|
208
|
+
env = r.json()
|
|
209
|
+
if env.get("errorCode") or env.get("success") is False:
|
|
210
|
+
raise TuyaApiError(env.get("errorCode"), env.get("errorMsg"), env)
|
|
211
|
+
result = env.get("result")
|
|
212
|
+
if isinstance(result, str):
|
|
213
|
+
inner = json.loads(decrypt_response(result, request_id, "", sign_key))
|
|
214
|
+
if inner.get("success") is False or inner.get("errorCode"):
|
|
215
|
+
raise TuyaApiError(inner.get("errorCode"), inner.get("errorMsg"), inner)
|
|
216
|
+
return inner.get("result", inner)
|
|
217
|
+
return result
|
|
218
|
+
|
|
219
|
+
token_bean = _send(
|
|
220
|
+
"thing.m.user.username.token.get",
|
|
221
|
+
"2.0",
|
|
222
|
+
{"countryCode": country_code, "isUid": False, "username": email},
|
|
223
|
+
)
|
|
224
|
+
token = token_bean["token"]
|
|
225
|
+
public_key = token_bean["publicKey"]
|
|
226
|
+
exponent = token_bean.get("exponent", "65537")
|
|
227
|
+
passwd = encrypt_password(password, public_key, exponent)
|
|
228
|
+
user = _send(
|
|
229
|
+
"thing.m.user.email.password.login",
|
|
230
|
+
"3.0",
|
|
231
|
+
{
|
|
232
|
+
"countryCode": country_code,
|
|
233
|
+
"email": email,
|
|
234
|
+
"passwd": passwd,
|
|
235
|
+
"options": '{"group": 1,"mfaCode": ""}',
|
|
236
|
+
"token": token,
|
|
237
|
+
"ifencrypt": 1,
|
|
238
|
+
},
|
|
239
|
+
)
|
|
240
|
+
return {
|
|
241
|
+
"sid": user.get("sid"),
|
|
242
|
+
"ecode": user.get("ecode"),
|
|
243
|
+
"chKey": ch_key,
|
|
244
|
+
"deviceId": device_id,
|
|
245
|
+
"uid": user.get("uid"),
|
|
246
|
+
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""Chiffrement du champ `postData` de l'API mobile Tuya (Danfoss Ally) — reversé et validé.
|
|
2
|
+
|
|
3
|
+
Pour les requêtes `m.*` (et=3), le postData n'est pas en clair :
|
|
4
|
+
1. SIGNATURE : champ `postData` du canonical = ``swap_sign_string(md5_hex(corps))``.
|
|
5
|
+
2. FIL : ``postData`` = Base64(nonce(12) ∥ AES-128-GCM(clé).encrypt(corps) ∥ tag(16)).
|
|
6
|
+
|
|
7
|
+
Clé AES = HMAC_SHA256(requestId, sign_key + "_" + ecode).hexdigest()[:16] (ecode vide en pré-login).
|
|
8
|
+
La réponse (et=3) est chiffrée avec la même clé puis gzip. sign_key et ecode sont des SECRETS.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import base64
|
|
14
|
+
import gzip
|
|
15
|
+
import hashlib
|
|
16
|
+
import hmac as _hmac
|
|
17
|
+
import os
|
|
18
|
+
|
|
19
|
+
from Crypto.Cipher import AES
|
|
20
|
+
|
|
21
|
+
GCM_NONCE_LEN = 12
|
|
22
|
+
GCM_TAG_LEN = 16
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def swap_sign_string(s: str) -> str:
|
|
26
|
+
"""Permutation des blocs de 8 hex d'un md5 : B0 B1 B2 B3 -> B1 B0 B3 B2 (involution)."""
|
|
27
|
+
b0, b1, b2, b3 = s[0:8], s[8:16], s[16:24], s[24:32]
|
|
28
|
+
return b1 + b0 + b3 + b2
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def post_data_md5(body: str | bytes) -> str:
|
|
32
|
+
"""Valeur du champ `postData` dans le canonical signé = swap_sign_string(md5_hex(corps))."""
|
|
33
|
+
if isinstance(body, str):
|
|
34
|
+
body = body.encode("utf-8")
|
|
35
|
+
return swap_sign_string(hashlib.md5(body).hexdigest())
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def derive_encrypto_key(request_id: str, ecode: str, sign_key: str) -> bytes:
|
|
39
|
+
"""Clé AES-128 (16 o ASCII) : HMAC_SHA256(requestId, sign_key[+ "_" + ecode])[:16].
|
|
40
|
+
|
|
41
|
+
En pré-login (ecode vide/None), le message haché est le sign_key seul.
|
|
42
|
+
"""
|
|
43
|
+
msg = (sign_key if not ecode else sign_key + "_" + ecode).encode("utf-8")
|
|
44
|
+
full = _hmac.new(request_id.encode("utf-8"), msg, hashlib.sha256).hexdigest()
|
|
45
|
+
return full[:16].encode("ascii")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def encrypt_post_data(
|
|
49
|
+
body: str | bytes, request_id: str, ecode: str, sign_key: str, nonce: bytes | None = None
|
|
50
|
+
) -> str:
|
|
51
|
+
"""Chiffre le corps en clair -> valeur `postData` envoyée (Base64 de nonce∥ciphertext∥tag)."""
|
|
52
|
+
if isinstance(body, str):
|
|
53
|
+
body = body.encode("utf-8")
|
|
54
|
+
if nonce is None:
|
|
55
|
+
nonce = os.urandom(GCM_NONCE_LEN)
|
|
56
|
+
if len(nonce) != GCM_NONCE_LEN:
|
|
57
|
+
raise ValueError("nonce doit faire 12 octets")
|
|
58
|
+
key = derive_encrypto_key(request_id, ecode, sign_key)
|
|
59
|
+
cipher = AES.new(key, AES.MODE_GCM, nonce=nonce, mac_len=GCM_TAG_LEN)
|
|
60
|
+
ciphertext, tag = cipher.encrypt_and_digest(body)
|
|
61
|
+
return base64.b64encode(nonce + ciphertext + tag).decode("ascii")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def decrypt_post_data(b64: str, request_id: str, ecode: str, sign_key: str) -> bytes:
|
|
65
|
+
"""Inverse de encrypt_post_data : Base64(nonce∥ct∥tag) -> corps en clair (octets)."""
|
|
66
|
+
blob = base64.b64decode(b64)
|
|
67
|
+
nonce = blob[:GCM_NONCE_LEN]
|
|
68
|
+
tag = blob[-GCM_TAG_LEN:]
|
|
69
|
+
ciphertext = blob[GCM_NONCE_LEN:-GCM_TAG_LEN]
|
|
70
|
+
key = derive_encrypto_key(request_id, ecode, sign_key)
|
|
71
|
+
cipher = AES.new(key, AES.MODE_GCM, nonce=nonce, mac_len=GCM_TAG_LEN)
|
|
72
|
+
return cipher.decrypt_and_verify(ciphertext, tag)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def build_request_body(
|
|
76
|
+
url_params: dict,
|
|
77
|
+
body: str | bytes | None,
|
|
78
|
+
sign_key: str,
|
|
79
|
+
ecode: str,
|
|
80
|
+
nonce: bytes | None = None,
|
|
81
|
+
) -> dict:
|
|
82
|
+
"""Assemble le corps POST (form-urlencoded) d'une requête m.* (et=3), 100 % hors ligne.
|
|
83
|
+
|
|
84
|
+
Renvoie url_params + postData chiffré (si corps) + sign. La signature porte sur le postData
|
|
85
|
+
tel qu'envoyé (ciphertext), pas sur le corps en clair.
|
|
86
|
+
"""
|
|
87
|
+
from .sign import canonical_from_request, sign_canonical
|
|
88
|
+
|
|
89
|
+
params = {k: v for k, v in url_params.items() if v is not None}
|
|
90
|
+
request_id = params.get("requestId")
|
|
91
|
+
if not request_id:
|
|
92
|
+
raise ValueError("url_params doit contenir 'requestId'")
|
|
93
|
+
out = dict(params)
|
|
94
|
+
wire = None
|
|
95
|
+
if body is not None and body != "" and body != b"":
|
|
96
|
+
wire = encrypt_post_data(body, request_id, ecode, sign_key, nonce=nonce)
|
|
97
|
+
out["postData"] = wire
|
|
98
|
+
canonical = canonical_from_request(params, wire)
|
|
99
|
+
out["sign"] = sign_canonical(canonical, sign_key)
|
|
100
|
+
return out
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def decrypt_response(
|
|
104
|
+
b64_result: str, request_id: str, ecode: str, sign_key: str, gzipped: bool = True
|
|
105
|
+
) -> bytes:
|
|
106
|
+
"""Déchiffre le champ `result` d'une réponse chiffrée (et=3) : GCM puis gunzip."""
|
|
107
|
+
raw = decrypt_post_data(b64_result, request_id, ecode, sign_key)
|
|
108
|
+
if gzipped:
|
|
109
|
+
try:
|
|
110
|
+
return gzip.decompress(raw)
|
|
111
|
+
except (OSError, EOFError):
|
|
112
|
+
return raw
|
|
113
|
+
return raw
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""Signature de l'API mobile Tuya (Danfoss Ally) — reversé et validé (voir danfoss-ally-mcp).
|
|
2
|
+
|
|
3
|
+
sign = HMAC_SHA256(key, canonical) (hex, 64 car.)
|
|
4
|
+
canonical = "||".join("<k>=<v>" for k in sorted(params)) # clés triées
|
|
5
|
+
postData (dans le canonical) = post_data_md5(valeur du fil) # pas le corps en clair
|
|
6
|
+
|
|
7
|
+
La clé HMAC est composée : "com.danfoss.ally_<deviceId hex-colon>_<appSecret1>_<appSecret2>".
|
|
8
|
+
Ce sont des SECRETS : fournis à l'exécution, jamais codés en dur ni journalisés.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import hashlib
|
|
14
|
+
import hmac as _hmac
|
|
15
|
+
|
|
16
|
+
# Clés retenues dans le canonical signé (liste autoritative du SDK décompilé).
|
|
17
|
+
SIGN_WHITELIST = frozenset(
|
|
18
|
+
(
|
|
19
|
+
"a",
|
|
20
|
+
"v",
|
|
21
|
+
"lat",
|
|
22
|
+
"lon",
|
|
23
|
+
"lang",
|
|
24
|
+
"deviceId",
|
|
25
|
+
"appVersion",
|
|
26
|
+
"ttid",
|
|
27
|
+
"isH5",
|
|
28
|
+
"h5Token",
|
|
29
|
+
"os",
|
|
30
|
+
"clientId",
|
|
31
|
+
"postData",
|
|
32
|
+
"time",
|
|
33
|
+
"requestId",
|
|
34
|
+
"et",
|
|
35
|
+
"n4h5",
|
|
36
|
+
"sid",
|
|
37
|
+
"chKey",
|
|
38
|
+
"sp",
|
|
39
|
+
)
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def canonical_string(params: dict) -> str:
|
|
44
|
+
"""Chaîne canonique : `clé=valeur` triées, jointes par `||`, limitée à SIGN_WHITELIST.
|
|
45
|
+
|
|
46
|
+
Le champ ``postData`` doit DÉJÀ contenir ``post_data_md5(corps)``, pas le corps brut.
|
|
47
|
+
"""
|
|
48
|
+
return "||".join(
|
|
49
|
+
f"{k}={params[k]}"
|
|
50
|
+
for k in sorted(params)
|
|
51
|
+
if k in SIGN_WHITELIST and params[k] is not None and params[k] != ""
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def canonical_from_request(params: dict, post_data_wire: str | bytes | None) -> str:
|
|
56
|
+
"""Canonical à signer à partir des paramètres d'URL et de la valeur `postData` du fil.
|
|
57
|
+
|
|
58
|
+
Règle (et=3 inclus) : ``postData = post_data_md5(<valeur postData du fil>)``. Pour et=3,
|
|
59
|
+
la valeur du fil est le blob chiffré, donc PAS le md5 du corps en clair.
|
|
60
|
+
"""
|
|
61
|
+
from .postdata import post_data_md5 # import local : évite tout cycle
|
|
62
|
+
|
|
63
|
+
p = dict(params)
|
|
64
|
+
if post_data_wire is not None and post_data_wire != "" and post_data_wire != b"":
|
|
65
|
+
p["postData"] = post_data_md5(post_data_wire)
|
|
66
|
+
else:
|
|
67
|
+
p.pop("postData", None)
|
|
68
|
+
return canonical_string(p)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def sign_canonical(canonical: str, key: str) -> str:
|
|
72
|
+
"""HMAC-SHA256(key, canonical) en hexadécimal — le cœur de l'algorithme."""
|
|
73
|
+
return _hmac.new(key.encode("utf-8"), canonical.encode("utf-8"), hashlib.sha256).hexdigest()
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def build_key(
|
|
77
|
+
device_id_colon: str, app_secret1: str, app_secret2: str, package: str = "com.danfoss.ally"
|
|
78
|
+
) -> str:
|
|
79
|
+
"""Reconstruit la clé HMAC à partir de ses composants (deviceId hex-colon + 2 appSecrets)."""
|
|
80
|
+
return "_".join([package, device_id_colon, app_secret1, app_secret2])
|