203 lines
9.0 KiB
Python
203 lines
9.0 KiB
Python
"""Bounded Home Assistant REST client with validated, pinned destinations."""
|
|
import base64
|
|
import hashlib
|
|
import http.client
|
|
import ipaddress
|
|
import json
|
|
import socket
|
|
import ssl
|
|
from urllib.parse import urlsplit, urlunsplit
|
|
|
|
from cryptography.fernet import Fernet, InvalidToken
|
|
from django.conf import settings
|
|
|
|
|
|
class ConnectionError(ValueError):
|
|
pass
|
|
|
|
|
|
def _cipher():
|
|
# Derive a distinct encryption key from Django's deployment secret.
|
|
key = hashlib.sha256(b'tasksnest-home-assistant-token-v1:' + settings.SECRET_KEY.encode()).digest()
|
|
return Fernet(base64.urlsafe_b64encode(key))
|
|
|
|
|
|
def encrypt_token(token):
|
|
return _cipher().encrypt(token.encode()).decode()
|
|
|
|
|
|
def decrypt_token(value):
|
|
try:
|
|
return _cipher().decrypt(value.encode()).decode()
|
|
except (InvalidToken, UnicodeError):
|
|
raise ConnectionError('The saved Home Assistant token could not be read. Replace it in Settings.') from None
|
|
|
|
|
|
def _addresses(host, port):
|
|
addresses = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM)
|
|
if not addresses:
|
|
raise ValueError
|
|
ips = [ipaddress.ip_address(entry[4][0]) for entry in addresses]
|
|
if any(ip.is_loopback or ip.is_link_local or ip.is_multicast or ip.is_unspecified or ip.is_reserved for ip in ips):
|
|
raise ValueError
|
|
return ips
|
|
|
|
|
|
def normalize_url(raw):
|
|
try:
|
|
parts = urlsplit(raw.strip())
|
|
if parts.scheme not in {'http', 'https'} or not parts.hostname or parts.username or parts.password:
|
|
raise ValueError
|
|
if parts.path not in {'', '/'} or parts.query or parts.fragment:
|
|
raise ValueError
|
|
port = parts.port
|
|
ips = _addresses(parts.hostname, port or (443 if parts.scheme == 'https' else 80))
|
|
if parts.scheme == 'http' and not all(ip.is_private for ip in ips):
|
|
raise ConnectionError('HTTP is allowed only for private network addresses. Use HTTPS for public servers.')
|
|
return urlunsplit((parts.scheme, parts.netloc.lower(), '', '', ''))
|
|
except ConnectionError:
|
|
raise
|
|
except (ValueError, OverflowError, socket.gaierror):
|
|
raise ConnectionError('Enter a reachable Home Assistant URL without a path, query, or credentials.') from None
|
|
|
|
|
|
def _request_json(base_url, token, path, payload=None):
|
|
# Connect to the validated IP while retaining the hostname for Host and TLS SNI.
|
|
# This prevents a second DNS lookup from redirecting the socket to another address.
|
|
base_url = normalize_url(base_url)
|
|
parts = urlsplit(base_url)
|
|
port = parts.port or (443 if parts.scheme == 'https' else 80)
|
|
try:
|
|
ips = _addresses(parts.hostname, port)
|
|
if parts.scheme == 'http' and not all(address.is_private for address in ips):
|
|
raise ValueError
|
|
ip = str(ips[0])
|
|
except (ValueError, socket.gaierror):
|
|
raise ConnectionError('Home Assistant could not be reached.') from None
|
|
connection_type = http.client.HTTPSConnection if parts.scheme == 'https' else http.client.HTTPConnection
|
|
kwargs = {'timeout': 5}
|
|
if parts.scheme == 'https':
|
|
kwargs['context'] = ssl.create_default_context()
|
|
connection = connection_type(parts.hostname, port, **kwargs)
|
|
connection._create_connection = lambda _address, timeout, source_address=None: socket.create_connection(
|
|
(ip, port), timeout, source_address)
|
|
try:
|
|
body = json.dumps(payload).encode() if payload is not None else None
|
|
headers = {'Authorization': 'Bearer ' + token, 'Accept': 'application/json', 'Host': parts.netloc}
|
|
if body is not None:
|
|
headers['Content-Type'] = 'application/json'
|
|
connection.request('POST' if body is not None else 'GET', path, body=body, headers=headers)
|
|
response = connection.getresponse()
|
|
if response.status == 401:
|
|
raise ConnectionError('Token rejected (401). Check the long-lived access token.') from None
|
|
if response.status in {301, 302, 303, 307, 308}:
|
|
raise ConnectionError('The server redirected the request. Enter its final URL instead.')
|
|
if response.status != 200:
|
|
error_body = response.read(4096).decode('utf-8', 'replace').lower()
|
|
if response.status >= 500 and 'did not match any entities' in error_body:
|
|
raise ConnectionError(
|
|
'The selected Home Assistant to-do list is unavailable. Refresh the discovered lists '
|
|
'and choose an available list in Home Assistant settings.'
|
|
) from None
|
|
raise ConnectionError(f'Home Assistant returned HTTP {response.status}.')
|
|
response_body = response.read(1024 * 1024 + 1)
|
|
if len(response_body) > 1024 * 1024:
|
|
raise ConnectionError('Home Assistant returned too much data.')
|
|
return json.loads(response_body)
|
|
except (TimeoutError, OSError, ssl.SSLError) as exc:
|
|
reason = str(exc).lower()
|
|
if 'certificate' in reason or 'ssl' in reason:
|
|
raise ConnectionError('TLS certificate verification failed.') from None
|
|
if 'timed out' in reason:
|
|
raise ConnectionError('Connection timed out after five seconds.') from None
|
|
raise ConnectionError('Home Assistant could not be reached.') from None
|
|
except ConnectionError:
|
|
raise
|
|
except (ValueError, UnicodeError):
|
|
raise ConnectionError('Home Assistant returned invalid JSON.') from None
|
|
finally:
|
|
connection.close()
|
|
|
|
|
|
def _get_json(base_url, token, path):
|
|
return _request_json(base_url, token, path)
|
|
|
|
|
|
def test_connection(base_url, token):
|
|
data = _get_json(base_url, token, '/api/config')
|
|
if not isinstance(data, dict) or not data.get('version'):
|
|
raise ConnectionError('This does not look like a Home Assistant server.')
|
|
return str(data['version'])[:100]
|
|
|
|
|
|
def discover_entities(base_url, token):
|
|
data = _get_json(base_url, token, '/api/states')
|
|
if not isinstance(data, list):
|
|
raise ConnectionError('Home Assistant returned an invalid entity list.')
|
|
entities = []
|
|
for state in data:
|
|
if not isinstance(state, dict) or not str(state.get('entity_id', '')).startswith('todo.'):
|
|
continue
|
|
entity_id = str(state['entity_id'])[:255]
|
|
attrs = state.get('attributes') or {}
|
|
name = str(attrs.get('friendly_name') or entity_id)[:255] if isinstance(attrs, dict) else entity_id
|
|
try:
|
|
features = int(attrs.get('supported_features', 0)) if isinstance(attrs, dict) else 0
|
|
except (TypeError, ValueError):
|
|
features = 0
|
|
entities.append({'id': entity_id, 'name': name, 'features': max(0, features),
|
|
'available': isinstance(state.get('state'), str) and state['state'] != 'unavailable'})
|
|
return sorted(entities, key=lambda entity: entity['name'].lower())
|
|
|
|
|
|
def get_items(base_url, token, entity_id):
|
|
if not entity_id.startswith('todo.'):
|
|
raise ConnectionError('Choose a valid to-do list.')
|
|
response = _request_json(base_url, token, '/api/services/todo/get_items?return_response',
|
|
{'entity_id': entity_id, 'status': ['needs_action', 'completed']})
|
|
try:
|
|
items = response['service_response'][entity_id]['items']
|
|
if not isinstance(items, list):
|
|
raise KeyError
|
|
result = {}
|
|
for item in items:
|
|
uid = item['uid']
|
|
summary = item['summary']
|
|
status = item['status']
|
|
if not isinstance(uid, str) or not uid or len(uid) > 255 or not isinstance(summary, str) or not summary.strip() or len(summary.strip()) > 180 or status not in {'needs_action', 'completed'} or uid in result:
|
|
raise KeyError
|
|
due = item.get('due')
|
|
if due is not None and (not isinstance(due, str) or len(due) > 64):
|
|
raise KeyError
|
|
description = item.get('description') or ''
|
|
if not isinstance(description, str) or len(description) > 10000:
|
|
raise KeyError
|
|
result[uid] = {'uid': uid, 'name': summary.strip(), 'status': status,
|
|
'due': due, 'description': description}
|
|
return result
|
|
except (KeyError, TypeError, AttributeError):
|
|
raise ConnectionError('Home Assistant returned an incomplete to-do list. No changes were made.') from None
|
|
|
|
|
|
def add_item(base_url, token, entity_id, name, *, due_date=None, description=None):
|
|
data = {'entity_id': entity_id, 'item': name}
|
|
if due_date is not None:
|
|
data['due_date'] = due_date
|
|
if description:
|
|
data['description'] = description
|
|
return _request_json(base_url, token, '/api/services/todo/add_item', data)
|
|
|
|
|
|
def update_item(base_url, token, entity_id, uid, *, name=None, status=None, due_date=None,
|
|
description=None):
|
|
data = {'entity_id': entity_id, 'item': uid}
|
|
if name is not None:
|
|
data['rename'] = name
|
|
if status is not None:
|
|
data['status'] = status
|
|
if due_date is not None:
|
|
data['due_date'] = due_date
|
|
if description is not None:
|
|
data['description'] = description
|
|
return _request_json(base_url, token, '/api/services/todo/update_item', data)
|