aioayla-lan 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,14 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ .mypy_cache/
5
+ .ruff_cache/
6
+ .pytest_cache/
7
+ .coverage
8
+ coverage.xml
9
+ dist/
10
+ build/
11
+ *.egg-info/
12
+
13
+ # Per-device secret: grants full local control of the unit.
14
+ lanip_key.json
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Dr-Blank
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,42 @@
1
+ Metadata-Version: 2.5
2
+ Name: aioayla-lan
3
+ Version: 0.1.0
4
+ Summary: Async local control of Ayla Networks IoT modules over Ayla LAN mode
5
+ Project-URL: Homepage, https://github.com/Dr-Blank/aioayla-lan
6
+ Project-URL: Repository, https://github.com/Dr-Blank/aioayla-lan
7
+ Project-URL: Issues, https://github.com/Dr-Blank/aioayla-lan/issues
8
+ Author-email: Dr-Blank <64108942+Dr-Blank@users.noreply.github.com>
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: ayla,ayla networks,home assistant,lan mode,local control
12
+ Classifier: Development Status :: 2 - Pre-Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: Home Automation
16
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
17
+ Classifier: Typing :: Typed
18
+ Requires-Python: >=3.12
19
+ Requires-Dist: aiohttp>=3.9
20
+ Requires-Dist: cryptography>=42
21
+ Description-Content-Type: text/markdown
22
+
23
+ # aioayla-lan
24
+
25
+ Async local control of Ayla Networks IoT modules over **Ayla LAN mode**: no cloud after a one-time LAN key fetch.
26
+
27
+ The module is the HTTP client. You register with it, it dials back to your callback address, performs a key exchange, then fetches commands and pushes property values. This library handles the registration heartbeat, the session crypto, the command queue and the callback endpoints, as framework-agnostic handlers you mount on any HTTP server under `/local_lan/`.
28
+
29
+ Values are passed through uninterpreted. What a property means is up to the caller.
30
+
31
+ ## Behaviour worth knowing
32
+
33
+ - **Return the status `AylaLanServer.handle` gives you.** It answers 206 Partial Content while commands are queued, which makes the module fetch the next one at once instead of waiting for another notify. A queue of 50 reads drains in about 2 s.
34
+ - **Writes are acknowledged.** `await device.async_set_property(name, value, base_type)` returns once the module acks, about a second after it collects the write. It raises `WriteRejectedError` when no ack comes (modules drop unknown names and out-of-range values silently) and `WriteExpiredError` when the module does not collect the write within 30 s. `set_property` queues without waiting.
35
+ - **Read back after a write.** Modules do not reliably echo what they were sent, nor what a write changed elsewhere.
36
+ - **One command per payload.** A module may ignore a batched `cmds` array and re-key.
37
+ - **Queue semantics.** Writes go before reads. A newer write to a queued name replaces it, and a repeated read is asked once.
38
+ - **Session.** Heartbeat every 10 s, a third of the module's `keep_alive`. One failed heartbeat does not drop the session; 30 s without contact does. A module that accepts notifies but stops dialling back for 30 s is registered afresh, which makes it key-exchange again.
39
+ - **One LAN client at a time, and no cloud client writing `refresh`.** A cloud-side `refresh` makes some modules push their whole catalogue for minutes, during which they collect no commands.
40
+ - **Expect malformed requests on the callback port.** Some firmware leaks its cloud echo onto the LAN socket; the server rejecting it loses the ack of the write before it, though the write was applied.
41
+
42
+ Status: pre-alpha, tested against Fujitsu General (FGLair) air conditioners only.
@@ -0,0 +1,20 @@
1
+ # aioayla-lan
2
+
3
+ Async local control of Ayla Networks IoT modules over **Ayla LAN mode**: no cloud after a one-time LAN key fetch.
4
+
5
+ The module is the HTTP client. You register with it, it dials back to your callback address, performs a key exchange, then fetches commands and pushes property values. This library handles the registration heartbeat, the session crypto, the command queue and the callback endpoints, as framework-agnostic handlers you mount on any HTTP server under `/local_lan/`.
6
+
7
+ Values are passed through uninterpreted. What a property means is up to the caller.
8
+
9
+ ## Behaviour worth knowing
10
+
11
+ - **Return the status `AylaLanServer.handle` gives you.** It answers 206 Partial Content while commands are queued, which makes the module fetch the next one at once instead of waiting for another notify. A queue of 50 reads drains in about 2 s.
12
+ - **Writes are acknowledged.** `await device.async_set_property(name, value, base_type)` returns once the module acks, about a second after it collects the write. It raises `WriteRejectedError` when no ack comes (modules drop unknown names and out-of-range values silently) and `WriteExpiredError` when the module does not collect the write within 30 s. `set_property` queues without waiting.
13
+ - **Read back after a write.** Modules do not reliably echo what they were sent, nor what a write changed elsewhere.
14
+ - **One command per payload.** A module may ignore a batched `cmds` array and re-key.
15
+ - **Queue semantics.** Writes go before reads. A newer write to a queued name replaces it, and a repeated read is asked once.
16
+ - **Session.** Heartbeat every 10 s, a third of the module's `keep_alive`. One failed heartbeat does not drop the session; 30 s without contact does. A module that accepts notifies but stops dialling back for 30 s is registered afresh, which makes it key-exchange again.
17
+ - **One LAN client at a time, and no cloud client writing `refresh`.** A cloud-side `refresh` makes some modules push their whole catalogue for minutes, during which they collect no commands.
18
+ - **Expect malformed requests on the callback port.** Some firmware leaks its cloud echo onto the LAN socket; the server rejecting it loses the ack of the write before it, though the write was applied.
19
+
20
+ Status: pre-alpha, tested against Fujitsu General (FGLair) air conditioners only.
@@ -0,0 +1,55 @@
1
+ [project]
2
+ name = "aioayla-lan"
3
+ version = "0.1.0"
4
+ description = "Async local control of Ayla Networks IoT modules over Ayla LAN mode"
5
+ authors = [
6
+ { name = "Dr-Blank", email = "64108942+Dr-Blank@users.noreply.github.com" },
7
+ ]
8
+ requires-python = ">=3.12"
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ keywords = ["ayla", "ayla networks", "lan mode", "local control", "home assistant"]
12
+ classifiers = [
13
+ "Development Status :: 2 - Pre-Alpha",
14
+ "Intended Audience :: Developers",
15
+ "Programming Language :: Python :: 3",
16
+ "Topic :: Home Automation",
17
+ "Topic :: Software Development :: Libraries :: Python Modules",
18
+ "Typing :: Typed",
19
+ ]
20
+ dependencies = ["aiohttp>=3.9", "cryptography>=42"]
21
+
22
+ [project.urls]
23
+ Homepage = "https://github.com/Dr-Blank/aioayla-lan"
24
+ Repository = "https://github.com/Dr-Blank/aioayla-lan"
25
+ Issues = "https://github.com/Dr-Blank/aioayla-lan/issues"
26
+
27
+ [dependency-groups]
28
+ dev = [
29
+ "pytest",
30
+ "pytest-asyncio",
31
+ "ruff",
32
+ "mypy",
33
+ "prek",
34
+ ]
35
+
36
+ [build-system]
37
+ requires = ["hatchling"]
38
+ build-backend = "hatchling.build"
39
+
40
+ [tool.hatch.build.targets.wheel]
41
+ packages = ["src/aioayla_lan"]
42
+
43
+ [tool.hatch.build.targets.sdist]
44
+ include = ["src/aioayla_lan", "tests", "README.md", "LICENSE"]
45
+
46
+ [tool.ruff]
47
+ line-length = 88
48
+ target-version = "py312"
49
+
50
+ [tool.mypy]
51
+ strict = true
52
+
53
+ [tool.pytest.ini_options]
54
+ testpaths = ["tests"]
55
+ asyncio_mode = "auto"
@@ -0,0 +1,48 @@
1
+ """Async local control of Ayla Networks IoT modules over Ayla LAN mode."""
2
+
3
+ from .cloud import REGIONS, AylaCloud, CloudDevice
4
+ from .crypto import SessionCrypto
5
+ from .device import LAN_URI, AylaLanDevice, fetch_dsn
6
+ from .exceptions import (
7
+ AylaLanError,
8
+ CallbackRejectedError,
9
+ CannotConnectError,
10
+ CloudAuthError,
11
+ CloudError,
12
+ InvalidKeyError,
13
+ KeyIdMismatchError,
14
+ NoCallbackError,
15
+ NoSessionError,
16
+ SignatureError,
17
+ WriteError,
18
+ WriteExpiredError,
19
+ WriteRejectedError,
20
+ )
21
+ from .models import Datapoint, LanKey
22
+ from .server import AylaLanServer
23
+
24
+ __all__ = [
25
+ "LAN_URI",
26
+ "REGIONS",
27
+ "AylaCloud",
28
+ "AylaLanDevice",
29
+ "AylaLanError",
30
+ "AylaLanServer",
31
+ "CallbackRejectedError",
32
+ "CannotConnectError",
33
+ "CloudAuthError",
34
+ "CloudDevice",
35
+ "CloudError",
36
+ "Datapoint",
37
+ "InvalidKeyError",
38
+ "KeyIdMismatchError",
39
+ "LanKey",
40
+ "NoCallbackError",
41
+ "NoSessionError",
42
+ "SessionCrypto",
43
+ "SignatureError",
44
+ "WriteError",
45
+ "WriteExpiredError",
46
+ "WriteRejectedError",
47
+ "fetch_dsn",
48
+ ]
@@ -0,0 +1,114 @@
1
+ """One-time fetch of a device's LAN key from the Ayla cloud.
2
+
3
+ The app ID and secret identify the vendor's mobile app and are supplied by the
4
+ caller. After this, local control needs no internet.
5
+ """
6
+
7
+ from dataclasses import dataclass
8
+ from typing import Any
9
+
10
+ import aiohttp
11
+
12
+ from .exceptions import CloudAuthError, CloudError
13
+ from .models import LanKey
14
+
15
+ REGIONS: dict[str, tuple[str, str]] = {
16
+ "us": ("user-field.aylanetworks.com", "ads-field.aylanetworks.com"),
17
+ "eu": ("user-field-eu.aylanetworks.com", "ads-eu.aylanetworks.com"),
18
+ "cn": ("user-field.ayla.com.cn", "ads-field.ayla.com.cn"),
19
+ }
20
+ _TIMEOUT = aiohttp.ClientTimeout(total=20)
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class CloudDevice:
25
+ """A device listed on the account."""
26
+
27
+ dsn: str
28
+ product_name: str | None
29
+ lan_ip: str | None
30
+ lan_enabled: bool
31
+
32
+
33
+ class AylaCloud:
34
+ """Minimal Ayla cloud client: sign in, list devices, fetch LAN keys."""
35
+
36
+ def __init__(
37
+ self,
38
+ session: aiohttp.ClientSession,
39
+ app_id: str,
40
+ app_secret: str,
41
+ region: str = "us",
42
+ ) -> None:
43
+ """Initialise for one region."""
44
+ self._http = session
45
+ self._app_id = app_id
46
+ self._app_secret = app_secret
47
+ self._user_host, self._ads_host = REGIONS[region]
48
+ self._token: str | None = None
49
+
50
+ async def sign_in(self, email: str, password: str) -> None:
51
+ """Sign in. Raises :exc:`CloudAuthError` on bad credentials."""
52
+ payload = {
53
+ "user": {
54
+ "email": email,
55
+ "password": password,
56
+ "application": {
57
+ "app_id": self._app_id,
58
+ "app_secret": self._app_secret,
59
+ },
60
+ }
61
+ }
62
+ try:
63
+ async with self._http.post(
64
+ f"https://{self._user_host}/users/sign_in.json",
65
+ json=payload,
66
+ timeout=_TIMEOUT,
67
+ ) as resp:
68
+ if resp.status in (401, 403, 404):
69
+ raise CloudAuthError(f"sign-in rejected: HTTP {resp.status}")
70
+ resp.raise_for_status()
71
+ auth = await resp.json()
72
+ except (aiohttp.ClientError, TimeoutError) as err:
73
+ raise CloudError(err) from err
74
+ if not isinstance(auth, dict) or not isinstance(
75
+ token := auth.get("access_token"), str
76
+ ):
77
+ raise CloudError("sign-in reply has no access token")
78
+ self._token = token
79
+
80
+ async def _get(self, path: str) -> Any:
81
+ if self._token is None:
82
+ raise CloudError("not signed in")
83
+ try:
84
+ async with self._http.get(
85
+ f"https://{self._ads_host}{path}",
86
+ headers={"Authorization": f"auth_token {self._token}"},
87
+ timeout=_TIMEOUT,
88
+ ) as resp:
89
+ resp.raise_for_status()
90
+ return await resp.json()
91
+ except (aiohttp.ClientError, TimeoutError) as err:
92
+ raise CloudError(err) from err
93
+
94
+ async def list_devices(self) -> list[CloudDevice]:
95
+ """List devices on the account."""
96
+ return [
97
+ CloudDevice(
98
+ dsn=dev["dsn"],
99
+ product_name=dev.get("product_name"),
100
+ lan_ip=dev.get("lan_ip"),
101
+ lan_enabled=bool(dev.get("lan_enabled")),
102
+ )
103
+ for entry in await self._get("/apiv1/devices.json")
104
+ if (dev := entry.get("device"))
105
+ ]
106
+
107
+ async def get_lan_key(self, dsn: str) -> LanKey:
108
+ """Fetch the LAN key for one device."""
109
+ reply = await self._get(f"/apiv1/dsns/{dsn}/lan.json")
110
+ try:
111
+ lan = reply["lanip"]
112
+ return LanKey(key=lan["lanip_key"], key_id=lan["lanip_key_id"])
113
+ except (KeyError, TypeError) as err:
114
+ raise CloudError(f"no LAN key for {dsn}") from err
@@ -0,0 +1,121 @@
1
+ """Ayla LAN mode session crypto.
2
+
3
+ msg_app = random_1 + random_2 + time_1 + time_2
4
+ msg_dev = random_2 + random_1 + time_2 + time_1
5
+ build(k, m) = HMAC(k, HMAC(k, m) + m)
6
+ sign_key = build(lanip_key, msg + b"0")
7
+ crypto_key = build(lanip_key, msg + b"1")
8
+ iv = build(lanip_key, msg + b"2")[:16]
9
+
10
+ AES-256-CBC with zero padding. CBC chaining carries across messages for the
11
+ whole session, so a cipher reset to the initial IV breaks every message after
12
+ the first. `sign` is an HMAC over the plaintext.
13
+ """
14
+
15
+ import base64
16
+ import binascii
17
+ import hashlib
18
+ import hmac
19
+ import json
20
+ from typing import Any
21
+
22
+ from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
23
+
24
+ from .exceptions import SignatureError
25
+
26
+ _BLOCK = 16
27
+
28
+
29
+ def _hmac(key: bytes, msg: bytes) -> bytes:
30
+ return hmac.new(key, msg, hashlib.sha256).digest()
31
+
32
+
33
+ def build_key(lanip_key: bytes, msg: bytes) -> bytes:
34
+ """Derive a session key the way the Ayla SDK does (double HMAC)."""
35
+ return _hmac(lanip_key, _hmac(lanip_key, msg) + msg)
36
+
37
+
38
+ def zero_pad(data: bytes) -> bytes:
39
+ """Pad to the AES block size with zero bytes, not PKCS#7."""
40
+ return data + b"\0" * (-len(data) % _BLOCK)
41
+
42
+
43
+ def zero_unpad(data: bytes) -> bytes:
44
+ """Strip zero padding."""
45
+ return data.rstrip(b"\0")
46
+
47
+
48
+ class _Direction:
49
+ """Keys and chaining state for one direction of a session."""
50
+
51
+ def __init__(self, lanip_key: bytes, msg: bytes) -> None:
52
+ self.sign_key = build_key(lanip_key, msg + b"0")
53
+ self._crypto_key = build_key(lanip_key, msg + b"1")
54
+ self._iv = build_key(lanip_key, msg + b"2")[:_BLOCK]
55
+ self.encryptor = Cipher(
56
+ algorithms.AES(self._crypto_key), modes.CBC(self._iv)
57
+ ).encryptor()
58
+
59
+ def decrypt(self, data: bytes) -> tuple[bytes, bytes]:
60
+ """Decrypt without advancing the chain. Returns (plaintext, next IV).
61
+
62
+ Equivalent to a session-long decryptor, but a payload that later fails
63
+ its signature check cannot desync the chain.
64
+ """
65
+ if not data or len(data) % _BLOCK:
66
+ raise SignatureError("ciphertext is not a whole number of blocks")
67
+ decryptor = Cipher(
68
+ algorithms.AES(self._crypto_key), modes.CBC(self._iv)
69
+ ).decryptor()
70
+ return decryptor.update(data), data[-_BLOCK:]
71
+
72
+ def advance(self, iv: bytes) -> None:
73
+ """Commit the chain state after a payload was accepted."""
74
+ self._iv = iv
75
+
76
+
77
+ class SessionCrypto:
78
+ """Encrypts what we send and decrypts what the device sends."""
79
+
80
+ def __init__(
81
+ self,
82
+ lanip_key: str,
83
+ random_1: str,
84
+ time_1: int,
85
+ random_2: str,
86
+ time_2: int,
87
+ ) -> None:
88
+ key = lanip_key.encode()
89
+ r1, r2 = random_1.encode(), random_2.encode()
90
+ t1, t2 = str(time_1).encode(), str(time_2).encode()
91
+ self._app = _Direction(key, r1 + r2 + t1 + t2)
92
+ self._dev = _Direction(key, r2 + r1 + t2 + t1)
93
+
94
+ def encrypt_and_sign(self, obj: Any) -> dict[str, str]:
95
+ """Encrypt a JSON document for the device."""
96
+ text = json.dumps(obj).encode()
97
+ enc = self._app.encryptor.update(zero_pad(text))
98
+ return {
99
+ "enc": base64.b64encode(enc).decode(),
100
+ "sign": base64.b64encode(_hmac(self._app.sign_key, text)).decode(),
101
+ }
102
+
103
+ def decrypt_and_validate(self, doc: dict[str, Any]) -> Any:
104
+ """Decrypt a device payload, verifying its signature before parsing.
105
+
106
+ Raises :exc:`SignatureError` for any payload that fails validation, leaving
107
+ the session usable.
108
+ """
109
+ enc, sign = doc["enc"], doc["sign"]
110
+ if not isinstance(enc, str) or not isinstance(sign, str):
111
+ raise SignatureError("enc and sign must be strings")
112
+ try:
113
+ data, signature = base64.b64decode(enc), base64.b64decode(sign)
114
+ except binascii.Error as err:
115
+ raise SignatureError("invalid base64") from err
116
+ padded, next_iv = self._dev.decrypt(data)
117
+ text = zero_unpad(padded)
118
+ if not hmac.compare_digest(_hmac(self._dev.sign_key, text), signature):
119
+ raise SignatureError("signature mismatch")
120
+ self._dev.advance(next_iv)
121
+ return json.loads(text)