cradlewise-client 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,30 @@
1
+ # Extracted and decompiled APK files (large, regenerable)
2
+ xapk_extracted/
3
+ decompiled/
4
+ *.xapk
5
+ *.apk
6
+
7
+ # Rust build artifacts
8
+ target/
9
+
10
+ # macOS
11
+ .DS_Store
12
+
13
+ # Python
14
+ .venv/
15
+ __pycache__/
16
+ *.pyc
17
+
18
+ # Extracted certificates (sensitive!)
19
+ certs/
20
+
21
+ # Local service secrets
22
+ .env
23
+ .env.*
24
+ !.env.example
25
+
26
+ # Implementation plans
27
+ fharr/
28
+
29
+ # Local experiments
30
+ fetch_flipbook.py
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 caffeineflo
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,37 @@
1
+ Metadata-Version: 2.5
2
+ Name: cradlewise-client
3
+ Version: 0.1.0
4
+ Summary: Local-first Cradlewise state and control client
5
+ Project-URL: Homepage, https://github.com/caffeineflo/cradlewise-home-assistant
6
+ Project-URL: Issues, https://github.com/caffeineflo/cradlewise-home-assistant/issues
7
+ Project-URL: Source, https://github.com/caffeineflo/cradlewise-home-assistant/tree/main/packages/cradlewise-client
8
+ Author: caffeineflo
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Programming Language :: Python :: 3.14
18
+ Requires-Python: >=3.10
19
+ Requires-Dist: boto3<2.0.0,>=1.34.0
20
+ Requires-Dist: cryptography<51.0.0,>=42.0.0
21
+ Requires-Dist: paho-mqtt<3.0.0,>=2.0.0
22
+ Requires-Dist: pycognito<2025.0.0,>=2024.5.1
23
+ Requires-Dist: requests<3.0.0,>=2.31.0
24
+ Description-Content-Type: text/markdown
25
+
26
+ # cradlewise-client
27
+
28
+ `cradlewise-client` is the media-free protocol layer used by the Cradlewise
29
+ Home Assistant integration. It supports direct local MQTT, Cradlewise AWS IoT
30
+ MQTT, account discovery, certificate provisioning, local broker pinning,
31
+ state normalization, and validated control payloads.
32
+
33
+ The package is unofficial and based on interoperability research against the
34
+ Cradlewise Android app. It does not start WebRTC sessions, process nursery
35
+ audio or video, or require Home Assistant.
36
+
37
+ This package is pre-release. Its public API can change before 1.0.
@@ -0,0 +1,12 @@
1
+ # cradlewise-client
2
+
3
+ `cradlewise-client` is the media-free protocol layer used by the Cradlewise
4
+ Home Assistant integration. It supports direct local MQTT, Cradlewise AWS IoT
5
+ MQTT, account discovery, certificate provisioning, local broker pinning,
6
+ state normalization, and validated control payloads.
7
+
8
+ The package is unofficial and based on interoperability research against the
9
+ Cradlewise Android app. It does not start WebRTC sessions, process nursery
10
+ audio or video, or require Home Assistant.
11
+
12
+ This package is pre-release. Its public API can change before 1.0.
@@ -0,0 +1,37 @@
1
+ [project]
2
+ name = "cradlewise-client"
3
+ version = "0.1.0"
4
+ description = "Local-first Cradlewise state and control client"
5
+ readme = "README.md"
6
+ requires-python = ">=3.10"
7
+ license = "MIT"
8
+ license-files = ["LICENSE"]
9
+ authors = [{name = "caffeineflo"}]
10
+ classifiers = [
11
+ "Development Status :: 3 - Alpha",
12
+ "Programming Language :: Python :: 3",
13
+ "Programming Language :: Python :: 3.10",
14
+ "Programming Language :: Python :: 3.11",
15
+ "Programming Language :: Python :: 3.12",
16
+ "Programming Language :: Python :: 3.13",
17
+ "Programming Language :: Python :: 3.14",
18
+ ]
19
+ dependencies = [
20
+ "boto3>=1.34.0,<2.0.0",
21
+ "cryptography>=42.0.0,<51.0.0",
22
+ "paho-mqtt>=2.0.0,<3.0.0",
23
+ "pycognito>=2024.5.1,<2025.0.0",
24
+ "requests>=2.31.0,<3.0.0",
25
+ ]
26
+
27
+ [project.urls]
28
+ Homepage = "https://github.com/caffeineflo/cradlewise-home-assistant"
29
+ Issues = "https://github.com/caffeineflo/cradlewise-home-assistant/issues"
30
+ Source = "https://github.com/caffeineflo/cradlewise-home-assistant/tree/main/packages/cradlewise-client"
31
+
32
+ [build-system]
33
+ requires = ["hatchling"]
34
+ build-backend = "hatchling.build"
35
+
36
+ [tool.hatch.build.targets.wheel]
37
+ packages = ["src/cradlewise_client"]
@@ -0,0 +1,57 @@
1
+ """Lightweight clients for Cradlewise local and cloud transports."""
2
+
3
+ from .certificates import (
4
+ BrokerCertificateError,
5
+ materialize_credentials,
6
+ pin_server_ca,
7
+ validate_server_chain,
8
+ )
9
+ from .cloud import (
10
+ CloudAccountClient,
11
+ CloudApiError,
12
+ CloudAuthenticationError,
13
+ CloudProvisioningError,
14
+ CradleAccount,
15
+ ProvisionedCredentials,
16
+ )
17
+ from .commands import (
18
+ CommandError,
19
+ CommandUnavailable,
20
+ CradlewiseCommandHandler,
21
+ build_desired,
22
+ shadow_payload,
23
+ )
24
+ from .local import (
25
+ LocalConnectionError,
26
+ LocalCradleClient,
27
+ LocalCradleUpdate,
28
+ LocalCredentials,
29
+ )
30
+ from .remote import REMOTE_MQTT_ENDPOINT, RemoteCradleClient
31
+ from .state import CradlewiseStateStore, normalize_device_state
32
+
33
+ __all__ = [
34
+ "CommandError",
35
+ "CommandUnavailable",
36
+ "CloudAccountClient",
37
+ "CloudApiError",
38
+ "CloudAuthenticationError",
39
+ "CloudProvisioningError",
40
+ "BrokerCertificateError",
41
+ "CradleAccount",
42
+ "CradlewiseCommandHandler",
43
+ "LocalConnectionError",
44
+ "LocalCradleClient",
45
+ "LocalCradleUpdate",
46
+ "LocalCredentials",
47
+ "REMOTE_MQTT_ENDPOINT",
48
+ "RemoteCradleClient",
49
+ "ProvisionedCredentials",
50
+ "CradlewiseStateStore",
51
+ "normalize_device_state",
52
+ "materialize_credentials",
53
+ "pin_server_ca",
54
+ "build_desired",
55
+ "shadow_payload",
56
+ "validate_server_chain",
57
+ ]
@@ -0,0 +1,214 @@
1
+ """Safe broker certificate discovery and credential materialization."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ipaddress
6
+ import socket
7
+ import ssl
8
+ from datetime import datetime, timezone
9
+ from pathlib import Path
10
+
11
+ from cryptography import x509
12
+ from cryptography.exceptions import InvalidSignature
13
+ from cryptography.hazmat.primitives import serialization
14
+ from cryptography.x509.oid import NameOID
15
+
16
+ from .cloud import ProvisionedCredentials
17
+ from .local import MQTT_PORT, LocalCredentials
18
+
19
+ MQTT_BROKER_COMMON_NAME = "aws.greengrass.clientdevices.mqtt.Moquette"
20
+ MQTT_CA_COMMON_NAME = "Greengrass Core CA"
21
+
22
+
23
+ class BrokerCertificateError(RuntimeError):
24
+ """Raised when the local broker chain cannot be safely pinned."""
25
+
26
+
27
+ def fetch_server_chain(
28
+ host: str,
29
+ client_certificate_path: Path,
30
+ client_private_key_path: Path,
31
+ *,
32
+ port: int = MQTT_PORT,
33
+ ) -> list[bytes]:
34
+ """Fetch the untrusted broker chain using the provisioned client identity."""
35
+ context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
36
+ context.minimum_version = ssl.TLSVersion.TLSv1_2
37
+ context.check_hostname = False
38
+ context.verify_mode = ssl.CERT_NONE
39
+ context.load_cert_chain(client_certificate_path, client_private_key_path)
40
+ try:
41
+ with socket.create_connection((host, port), timeout=10) as raw_socket:
42
+ with context.wrap_socket(raw_socket, server_hostname=host) as tls_socket:
43
+ chain = _unverified_chain(tls_socket)
44
+ except BrokerCertificateError:
45
+ raise
46
+ except (OSError, ssl.SSLError) as exc:
47
+ raise BrokerCertificateError(
48
+ f"could not inspect local MQTT broker TLS: {exc}"
49
+ ) from exc
50
+ if len(chain) < 2:
51
+ raise BrokerCertificateError(
52
+ "local MQTT broker did not return a certificate chain"
53
+ )
54
+ return chain
55
+
56
+
57
+ def validate_server_chain(
58
+ certificate_data: list[bytes],
59
+ host: str,
60
+ *,
61
+ now: datetime | None = None,
62
+ ) -> x509.Certificate:
63
+ """Validate the expected Greengrass broker shape before trusting its CA."""
64
+ certificates = [_load_certificate(value) for value in certificate_data]
65
+ leaf = certificates[0]
66
+ issuers = [
67
+ certificate
68
+ for certificate in certificates[1:]
69
+ if certificate.subject == leaf.issuer
70
+ ]
71
+ if len(issuers) != 1:
72
+ raise BrokerCertificateError(
73
+ "local MQTT broker chain has no unique issuer for its leaf"
74
+ )
75
+ ca = issuers[0]
76
+ if _common_name(leaf) != MQTT_BROKER_COMMON_NAME:
77
+ raise BrokerCertificateError(
78
+ "local MQTT broker certificate has an unexpected common name"
79
+ )
80
+ if _common_name(ca) != MQTT_CA_COMMON_NAME or ca.subject != ca.issuer:
81
+ raise BrokerCertificateError(
82
+ "local MQTT broker issuer is not a self-issued Greengrass Core CA"
83
+ )
84
+ try:
85
+ constraints = ca.extensions.get_extension_for_class(x509.BasicConstraints)
86
+ except x509.ExtensionNotFound as exc:
87
+ raise BrokerCertificateError(
88
+ "Greengrass Core CA is missing basic constraints"
89
+ ) from exc
90
+ if not constraints.value.ca:
91
+ raise BrokerCertificateError(
92
+ "Greengrass Core CA certificate is not marked as a CA"
93
+ )
94
+
95
+ current = now or datetime.now(timezone.utc)
96
+ for certificate in (leaf, ca):
97
+ if not (
98
+ certificate.not_valid_before_utc
99
+ <= current
100
+ <= certificate.not_valid_after_utc
101
+ ):
102
+ raise BrokerCertificateError(
103
+ "local MQTT broker chain contains an expired or future certificate"
104
+ )
105
+ try:
106
+ leaf.verify_directly_issued_by(ca)
107
+ ca.verify_directly_issued_by(ca)
108
+ except (InvalidSignature, ValueError, TypeError) as exc:
109
+ raise BrokerCertificateError(
110
+ "local MQTT broker chain signature validation failed"
111
+ ) from exc
112
+
113
+ try:
114
+ alternative_names = leaf.extensions.get_extension_for_class(
115
+ x509.SubjectAlternativeName
116
+ ).value
117
+ except x509.ExtensionNotFound as exc:
118
+ raise BrokerCertificateError(
119
+ "local MQTT broker certificate has no subject alternative name"
120
+ ) from exc
121
+ try:
122
+ expected_ip = ipaddress.ip_address(host)
123
+ except ValueError:
124
+ valid_host = host in alternative_names.get_values_for_type(x509.DNSName)
125
+ else:
126
+ valid_host = expected_ip in alternative_names.get_values_for_type(
127
+ x509.IPAddress
128
+ )
129
+ if not valid_host:
130
+ raise BrokerCertificateError(
131
+ f"local MQTT broker certificate is not valid for {host}"
132
+ )
133
+ return ca
134
+
135
+
136
+ def pin_server_ca(
137
+ host: str,
138
+ client_certificate_path: Path,
139
+ client_private_key_path: Path,
140
+ ) -> str:
141
+ """Fetch, validate, and return the crib's current broker CA as PEM."""
142
+ chain = fetch_server_chain(
143
+ host,
144
+ client_certificate_path,
145
+ client_private_key_path,
146
+ )
147
+ ca = validate_server_chain(chain, host)
148
+ return ca.public_bytes(serialization.Encoding.PEM).decode("ascii")
149
+
150
+
151
+ def materialize_credentials(
152
+ directory: Path,
153
+ credentials: ProvisionedCredentials,
154
+ *,
155
+ server_ca_certificate: str | None = None,
156
+ ) -> LocalCredentials:
157
+ """Write one runtime-only credential bundle for Paho MQTT."""
158
+ directory.mkdir(parents=True, exist_ok=True)
159
+ directory.chmod(0o700)
160
+ values = {
161
+ "ca.pem": credentials.group_ca_certificate,
162
+ "client_cert.pem": credentials.client_certificate,
163
+ "client_key.pem": credentials.client_private_key,
164
+ "device_id": credentials.device_id,
165
+ }
166
+ if server_ca_certificate is not None:
167
+ values["server_ca.pem"] = server_ca_certificate
168
+ for name, value in values.items():
169
+ path = directory / name
170
+ path.write_text(value, encoding="utf-8")
171
+ path.chmod(0o600)
172
+ return LocalCredentials.from_directory(directory)
173
+
174
+
175
+ def _load_certificate(value: bytes) -> x509.Certificate:
176
+ if value.startswith(b"-----BEGIN"):
177
+ return x509.load_pem_x509_certificate(value)
178
+ return x509.load_der_x509_certificate(value)
179
+
180
+
181
+ def _unverified_chain(tls_socket: ssl.SSLSocket) -> list[bytes]:
182
+ """Return the peer chain across supported Python SSL API versions."""
183
+ get_chain = getattr(tls_socket, "get_unverified_chain", None)
184
+ if get_chain is None:
185
+ ssl_object = getattr(tls_socket, "_sslobj", None)
186
+ get_chain = getattr(ssl_object, "get_unverified_chain", None)
187
+ if get_chain is None:
188
+ raise BrokerCertificateError(
189
+ "Python does not support retrieving the broker chain"
190
+ )
191
+ return [_certificate_bytes(certificate) for certificate in get_chain()]
192
+
193
+
194
+ def _certificate_bytes(certificate: object) -> bytes:
195
+ if isinstance(certificate, bytes):
196
+ return certificate
197
+ public_bytes = getattr(certificate, "public_bytes", None)
198
+ if public_bytes is None:
199
+ raise BrokerCertificateError(
200
+ "Python returned an unsupported broker certificate object"
201
+ )
202
+ value = public_bytes()
203
+ if isinstance(value, str):
204
+ return value.encode("ascii")
205
+ if isinstance(value, bytes):
206
+ return value
207
+ raise BrokerCertificateError(
208
+ "Python returned an unsupported broker certificate encoding"
209
+ )
210
+
211
+
212
+ def _common_name(certificate: x509.Certificate) -> str | None:
213
+ values = certificate.subject.get_attributes_for_oid(NameOID.COMMON_NAME)
214
+ return values[0].value if values else None