Compare commits
100 Commits
raccoon-fl
...
project-7
| Author | SHA1 | Date | |
|---|---|---|---|
| d828c27c42 | |||
| d7e9409156 | |||
| aa373af3cb | |||
| 4cd5e06635 | |||
| 7db6dc7eba | |||
| cb8eb69adf | |||
| feec6ef9fb | |||
| 2e81d9d300 | |||
| 0f04889edf | |||
| 08a8379d5b | |||
| 3b9e068f9b | |||
| 78514a1673 | |||
| ce0fae6b1c | |||
| df5e8cbdd3 | |||
| cf81be9c40 | |||
| 5f579fb5e6 | |||
| 757e772c94 | |||
| 6db023feef | |||
| 4d7b50e4a3 | |||
| 3dffd055a4 | |||
| 454c531c10 | |||
| a1c9c5fe95 | |||
| 4ac67cd553 | |||
| 8f599c6f9c | |||
| b4f6fb977c | |||
| 31e690ab35 | |||
| 2b6898ab84 | |||
| 29c23a4a8f | |||
| a3dd68aede | |||
| 040251f69c | |||
| f338dfe04e | |||
| c711a6d5b0 | |||
| 12321a6013 | |||
| 74d4534d59 | |||
| 8a63ac2209 | |||
| 5bc44d1a1e | |||
| e14abf6490 | |||
| a15c794612 | |||
| e55fd1f41e | |||
| eeafd74131 | |||
| 67217f46fc | |||
| 620c9e2c4b | |||
| ababc68dc5 | |||
| ae2dd295e2 | |||
| 698c5bd731 | |||
| e55ccea018 | |||
| bceb52e8ee | |||
| 7f4d388e19 | |||
| d54276de34 | |||
| 530c85f50c | |||
| 6856e75265 | |||
| 18574c0ca6 | |||
| 0bd21e0d88 | |||
| 2aa9ab7ff4 | |||
| fe1f0de788 | |||
| abf389d7fc | |||
| 87b54b8a98 | |||
| e2e3f73ad5 | |||
| 9ec7917e12 | |||
| 8031ff1d4c | |||
| 9956c5614e | |||
| b1188a7b62 | |||
| ff1bed2f39 | |||
| dd68f8679e | |||
| e6ebc5c5c0 | |||
| 8fe923e6dc | |||
| f544a95e16 | |||
| 5b010039d7 | |||
| 10f0668e32 | |||
| e758db67ef | |||
| 8149c677c4 | |||
| bc7e65dcfb | |||
| bc57513628 | |||
| e23a1af1ea | |||
| 6eef8a5151 | |||
| 00408fd43c | |||
| a7b6b57cab | |||
| 242ea3d8bb | |||
| 10583d64ef | |||
| 58d17d7b26 | |||
| 7d640114bb | |||
| 08555c13aa | |||
| 3f433c35c9 | |||
| f2b8e617d6 | |||
| 41f21f8392 | |||
| b4c0d24083 | |||
| 0311e3e3c7 | |||
| 7254922982 | |||
| e01a9d3425 | |||
| 530711cd8a | |||
| 450c4a1892 | |||
| 4351a77f13 | |||
| 00f3886b34 | |||
| 49dac6b3b1 | |||
| 989deccb63 | |||
| 6850368c2d | |||
| 625d94abe5 | |||
| 65b484d7f5 | |||
| a16a457669 | |||
| f10303b8c2 |
56
.gitignore
vendored
56
.gitignore
vendored
@@ -1,3 +1,59 @@
|
|||||||
archive
|
archive
|
||||||
**/__pycache__
|
**/__pycache__
|
||||||
.env
|
.env
|
||||||
|
|
||||||
|
MODNet-with-training/
|
||||||
|
avds-cleaner/
|
||||||
|
avspeech/
|
||||||
|
browser-extensions/
|
||||||
|
elasticmq-container/
|
||||||
|
folders
|
||||||
|
gcp-application/
|
||||||
|
gcp-cloud-infrastructure/
|
||||||
|
gcp-infrastructure/
|
||||||
|
lambda-cloudwatch-logs-to-loggly/
|
||||||
|
lambda-datadog-forwarder/
|
||||||
|
lambda-potion-engagement/
|
||||||
|
lambda-potion-schedular/
|
||||||
|
lambda-potion-transcription-scheduler/
|
||||||
|
lambda-text-to-speech/
|
||||||
|
lambda-video-processing/
|
||||||
|
microservice-dynamic-screen-recording/
|
||||||
|
microservice-potion-voice/
|
||||||
|
potion-ai/
|
||||||
|
potion-ai-cpu/
|
||||||
|
potion-ai-gpu/
|
||||||
|
potion-ai-pretrained-models-infra/
|
||||||
|
potion-analytics/
|
||||||
|
potion-api/
|
||||||
|
potion-app/
|
||||||
|
potion-app-infra/
|
||||||
|
potion-bastion/
|
||||||
|
potion-custom-domain-app/
|
||||||
|
potion-devops/
|
||||||
|
potion-dynamic-screen-recording-lambda/
|
||||||
|
potion-job-consumer/
|
||||||
|
potion-job-producer/
|
||||||
|
potion-multi-dsr-watcher/
|
||||||
|
potion-qa/
|
||||||
|
potion-snapshot-testing/
|
||||||
|
potion-stitch/
|
||||||
|
potion-tryon/
|
||||||
|
potion-video-background-change/
|
||||||
|
potion-video-processing/
|
||||||
|
potion-video-processing-devops/
|
||||||
|
potion-voice/
|
||||||
|
potion-voice-dataset/
|
||||||
|
potion-voice-utils/
|
||||||
|
potion-watcher/
|
||||||
|
potion-web/
|
||||||
|
potion-website/
|
||||||
|
potion-website-recording-handler/
|
||||||
|
potion-wp-site/
|
||||||
|
sentence-split-service/
|
||||||
|
urlbox-experiments/
|
||||||
|
video-synth-api/
|
||||||
|
wav2lip-fa/
|
||||||
|
yeahsure-tryon/
|
||||||
|
|
||||||
|
*.gz
|
||||||
406
261119notes.txt
Normal file
406
261119notes.txt
Normal file
@@ -0,0 +1,406 @@
|
|||||||
|
Now I have a good understanding of the codebase. Let me summarize some refactoring task ideas that would be suitable for the
|
||||||
|
Armadillo task. The key criteria are:
|
||||||
|
|
||||||
|
1. Real work on the repo (add feature, fix bug, refactor, write tests)
|
||||||
|
2. Complex enough for 3-5 turns
|
||||||
|
3. Can be checked with tests or behavior
|
||||||
|
4. Not already solved in public
|
||||||
|
5. No Docker or external websites needed
|
||||||
|
|
||||||
|
Good refactoring ideas:
|
||||||
|
|
||||||
|
1. Template Light - Consolidate Color Mode Handling: The template light has massive duplication for
|
||||||
|
RGB/RGBW/RGBWW/HS/temperature/brightness/effect. Each has its own script, template, state variable, and property. Could
|
||||||
|
refactor into a unified handler.
|
||||||
|
|
||||||
|
2. MQTT Light - Schema Consolidation: The MQTT light has 4 schema files (schema_basic.py, schema_json.py, schema_template.py,
|
||||||
|
schema.py) with lots of shared logic. Could consolidate common functionality.
|
||||||
|
|
||||||
|
3. DataUpdateCoordinator Enhancement: The coordinator is used everywhere but could benefit from better type hints, async context
|
||||||
|
manager support, or better error handling patterns.
|
||||||
|
|
||||||
|
4. Debouncer Improvements: The debouncer is used in many places - could add better metrics, configurable backoff, or integration
|
||||||
|
with the new async timeout patterns.
|
||||||
|
|
||||||
|
5. Light Component - Deprecated Constant Cleanup: There are many deprecated constants (SUPPORT_*, COLOR_MODE_*) that could be
|
||||||
|
cleaned up with automated migration.
|
||||||
|
|
||||||
|
6. Config Entries - Split Large File: The config_entries.py is 3000+ lines - could split into smaller modules.
|
||||||
|
|
||||||
|
7. Entity Helper - Common Property Patterns: Many entities have similar patterns for state attributes - could create a mixin or
|
||||||
|
base class.
|
||||||
|
|
||||||
|
Let me present these ideas to the user.
|
||||||
|
|
||||||
|
Based on my exploration of the Home Assistant codebase, here are refactoring task ideas that fit the Armadillo criteria (real
|
||||||
|
work, 3-5 turns, testable, no Docker/external deps):
|
||||||
|
|
||||||
|
────────────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
### 1. Template Light: Consolidate Color Mode Handling ⭐ Best candidate
|
||||||
|
|
||||||
|
File: homeassistant/components/template/light.py (~1000 lines)
|
||||||
|
|
||||||
|
Problem: Massive duplication for each color mode (RGB, RGBW, RGBWW, HS, temperature, brightness, effect) — each has its own
|
||||||
|
script, template, state variable, property, and template setup.
|
||||||
|
|
||||||
|
Refactoring: Create a ColorModeHandler dataclass/protocol that encapsulates script/template/state/property per mode. Loop over
|
||||||
|
supported modes instead of 7× copy-pasted blocks.
|
||||||
|
|
||||||
|
Tests: Existing template light tests in tests/components/template/test_light.py cover all modes.
|
||||||
|
|
||||||
|
────────────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
### 2. MQTT Light: Unify Schema Implementations
|
||||||
|
|
||||||
|
Files: homeassistant/components/mqtt/light/schema_{basic,json,template}.py + schema.py
|
||||||
|
|
||||||
|
Problem: 4 schema files with significant overlap in validation, color mode handling, and entity creation logic.
|
||||||
|
|
||||||
|
Refactoring: Extract shared validation/color-mode logic into a common base class or module. Reduce duplication across JSON,
|
||||||
|
template, and basic schemas.
|
||||||
|
|
||||||
|
Tests: tests/components/mqtt/test_light.py has extensive coverage.
|
||||||
|
|
||||||
|
────────────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
### 3. DataUpdateCoordinator: Add Async Context Manager + Better Errors
|
||||||
|
|
||||||
|
File: homeassistant/helpers/update_coordinator.py
|
||||||
|
|
||||||
|
Problem: Coordinators are manually started/stopped. No async with support. Error handling is basic (UpdateFailed only).
|
||||||
|
|
||||||
|
Refactoring:
|
||||||
|
- Add __aenter__/__aexit__ for automatic async_config_entry_first_refresh + shutdown
|
||||||
|
- Add richer error types (auth, not_ready, rate_limit) that map to config entry states
|
||||||
|
- Add optional update_timeout parameter
|
||||||
|
|
||||||
|
Tests: tests/helpers/test_update_coordinator.py
|
||||||
|
|
||||||
|
────────────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
### 4. Debouncer: Configurable Backoff + Metrics
|
||||||
|
|
||||||
|
File: homeassistant/helpers/debounce.py
|
||||||
|
|
||||||
|
Problem: Fixed cooldown, no observability. Used in 20+ integrations.
|
||||||
|
|
||||||
|
Refactoring:
|
||||||
|
- Add exponential backoff option (backoff_factor, max_cooldown)
|
||||||
|
- Add call_count / last_called / rejected_count properties for debugging
|
||||||
|
- Add optional callback on debounce rejection
|
||||||
|
|
||||||
|
Tests: tests/helpers/test_debounce.py
|
||||||
|
|
||||||
|
────────────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
### 5. Light Component: Remove Deprecated Constants
|
||||||
|
|
||||||
|
File: homeassistant/components/light/__init__.py + integrations
|
||||||
|
|
||||||
|
Problem: ~30 deprecated SUPPORT_* and COLOR_MODE_* constants with DeprecatedConstant wrappers, still imported by many
|
||||||
|
integrations.
|
||||||
|
|
||||||
|
Refactoring:
|
||||||
|
- Remove deprecated constants from light __init__.py
|
||||||
|
- Update remaining integrations (mqtt, template, matter, hue, etc.) to use LightEntityFeature / ColorMode enums directly
|
||||||
|
- Add codemod script for automated migration
|
||||||
|
|
||||||
|
Tests: Light tests + integration tests for each updated component.
|
||||||
|
|
||||||
|
────────────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
### 6. Config Entries: Split Monolithic File
|
||||||
|
|
||||||
|
File: homeassistant/config_entries.py (3,300+ lines)
|
||||||
|
|
||||||
|
Problem: Single massive file handling config entry lifecycle, discovery, flows, storage, migrations, notifications.
|
||||||
|
|
||||||
|
Refactoring: Split into:
|
||||||
|
- config_entries/entry.py — ConfigEntry dataclass
|
||||||
|
- config_entries/flow.py — ConfigFlow base + registry
|
||||||
|
- config_entries/storage.py — Storage logic
|
||||||
|
- config_entries/discovery.py — Discovery handling
|
||||||
|
- config_entries/__init__.py — Public re-exports
|
||||||
|
|
||||||
|
Tests: tests/config_entries/ — comprehensive suite.
|
||||||
|
|
||||||
|
────────────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
### 7. Entity: Extract Common Attribute Mixins
|
||||||
|
|
||||||
|
Files: homeassistant/helpers/entity.py + many components
|
||||||
|
|
||||||
|
Problem: Repeated patterns for extra_state_attributes, supported_features, capability_attributes across entities.
|
||||||
|
|
||||||
|
Refactoring: Create mixin classes like AttributesMixin, FeaturesMixin with declarative field definitions (similar to dataclasses
|
||||||
|
or propcache).
|
||||||
|
|
||||||
|
Tests: Entity tests + spot-check integrations.
|
||||||
|
|
||||||
|
────────────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
### My Recommendation: Task #1 (Template Light)
|
||||||
|
|
||||||
|
- Self-contained to one file
|
||||||
|
- High impact — removes ~400 lines of duplication
|
||||||
|
- Well-tested — existing test suite validates all color modes
|
||||||
|
- Clear success criteria — all template light tests pass, code is DRY
|
||||||
|
- No external deps — pure Python refactoring
|
||||||
|
|
||||||
|
Would you like me to elaborate on any of these, or help you pick one to start with?
|
||||||
|
|
||||||
|
|
||||||
|
before we explore your ideas - is thie codebase the frontend and the backend?
|
||||||
|
|
||||||
|
|
||||||
|
The user is asking if this codebase contains both frontend and backend code. Let me check what's in the repo - Home Assistant is
|
||||||
|
primarily a Python backend, but it does have some frontend components (like the Lovelace UI, which is served by the backend but
|
||||||
|
built separately).
|
||||||
|
|
||||||
|
|
||||||
|
$ ls -la | head -30
|
||||||
|
|
||||||
|
... (25 earlier lines, ctrl+o to expand)
|
||||||
|
-rw-r--r-- 1 ericbell ericbell 3886 Oct 29 12:01 .pre-commit-config.yaml
|
||||||
|
-rw-r--r-- 1 ericbell ericbell 233 Oct 29 12:01 .prettierignore
|
||||||
|
drwxr-xr-x 3 ericbell ericbell 4096 Oct 29 12:01 pylint
|
||||||
|
-rw-r--r-- 1 ericbell ericbell 43893 Oct 29 12:01 pyproject.toml
|
||||||
|
-rw-r--r-- 1 ericbell ericbell 1964 Oct 29 12:01 README.rst
|
||||||
|
|
||||||
|
Took 0.0s
|
||||||
|
|
||||||
|
|
||||||
|
This is the Home Assistant Core repository - it's a Python backend. Let me check if there's any frontend code in here.
|
||||||
|
|
||||||
|
|
||||||
|
$ find . -name "*.ts" -o -name "*.tsx" -o -name "*.vue" -o -name "*.js" -o -name "package.json" 2>/dev/null | head -20
|
||||||
|
|
||||||
|
./tests/components/lidarr/fixtures/initialize.js
|
||||||
|
./tests/components/lidarr/fixtures/initialize-wrong.js
|
||||||
|
|
||||||
|
Took 0.2s
|
||||||
|
|
||||||
|
|
||||||
|
Almost no JavaScript/TypeScript files. This is a Python-only backend.
|
||||||
|
|
||||||
|
|
||||||
|
$ ls homeassistant/components/frontend/
|
||||||
|
|
||||||
|
... (1 earlier lines, ctrl+o to expand)
|
||||||
|
__init__.py
|
||||||
|
manifest.json
|
||||||
|
services.yaml
|
||||||
|
storage.py
|
||||||
|
strings.json
|
||||||
|
|
||||||
|
Took 0.0s
|
||||||
|
|
||||||
|
|
||||||
|
The "frontend" component here is just a Python integration that serves the pre-built frontend. Let me check if there's a frontend
|
||||||
|
directory or if the frontend is completely separate.
|
||||||
|
|
||||||
|
|
||||||
|
read homeassistant/components/frontend/__init__.py:1-80
|
||||||
|
|
||||||
|
|
||||||
|
This is the Python backend that serves the frontend. The actual frontend (React/TypeScript) is in a separate repository
|
||||||
|
(home-assistant/frontend). This repo is the backend only.
|
||||||
|
|
||||||
|
No — this is the backend only (Python).
|
||||||
|
|
||||||
|
The homeassistant/components/frontend/ you see is just a Python integration that serves the pre-built frontend assets
|
||||||
|
(HTML/JS/CSS). The actual frontend codebase (React + TypeScript) lives in a separate repo: home-assistant/frontend.
|
||||||
|
|
||||||
|
This repo (home-assistant/core) contains:
|
||||||
|
- Core: event loop, state machine, config entries, entity system
|
||||||
|
- Integrations: 950+ components (light, mqtt, hue, zwave, etc.) — all Python
|
||||||
|
- Helpers: update_coordinator, debounce, entity registry, device registry, etc.
|
||||||
|
- API: REST + WebSocket endpoints
|
||||||
|
- Frontend serving: static asset delivery, panel registration, theme storage
|
||||||
|
|
||||||
|
No TypeScript, no Vue, no webpack, no npm — pure Python.
|
||||||
|
|
||||||
|
|
||||||
|
your #1 idea is template light. you gave a bit of a synopsis already but give me a simplfied tour
|
||||||
|
|
||||||
|
|
||||||
|
The user wants a simplified tour of the template light code to understand the refactoring opportunity better. Let me walk through
|
||||||
|
the key parts of the file.
|
||||||
|
|
||||||
|
|
||||||
|
read homeassistant/components/template/light.py:180-379
|
||||||
|
|
||||||
|
|
||||||
|
Let me also look at the turn_on method and the async_turn_on/turn_off methods to see the full picture.
|
||||||
|
|
||||||
|
|
||||||
|
read homeassistant/components/template/light.py:500-699
|
||||||
|
|
||||||
|
|
||||||
|
Now I have a good picture. Let me provide a simplified tour.
|
||||||
|
|
||||||
|
────────────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
Template Light — Simplified Tour
|
||||||
|
|
||||||
|
File: homeassistant/components/template/light.py (~1000 lines)
|
||||||
|
|
||||||
|
### The Pattern (Repeated 7×)
|
||||||
|
|
||||||
|
For each color mode (brightness, temperature, HS, RGB, RGBW, RGBWW, effect), the class has:
|
||||||
|
|
||||||
|
┌─────────────────┬────────────────────────────────┬────────────────────────────────┐
|
||||||
|
│ Item │ Example (Brightness) │ Example (RGB) │
|
||||||
|
├─────────────────┼────────────────────────────────┼────────────────────────────────┤
|
||||||
|
│ Config key │ level_action, level_template │ rgb_action, rgb_template │
|
||||||
|
├─────────────────┼────────────────────────────────┼────────────────────────────────┤
|
||||||
|
│ Script │ self._level_script │ self._rgb_script │
|
||||||
|
├─────────────────┼────────────────────────────────┼────────────────────────────────┤
|
||||||
|
│ Template │ self._level_template │ self._rgb_template │
|
||||||
|
├─────────────────┼────────────────────────────────┼────────────────────────────────┤
|
||||||
|
│ State var │ self._brightness │ self._rgb_color │
|
||||||
|
├─────────────────┼────────────────────────────────┼────────────────────────────────┤
|
||||||
|
│ Property │ brightness │ rgb_color │
|
||||||
|
├─────────────────┼────────────────────────────────┼────────────────────────────────┤
|
||||||
|
│ Template setup │ _async_setup_templates() block │ _async_setup_templates() block │
|
||||||
|
├─────────────────┼────────────────────────────────┼────────────────────────────────┤
|
||||||
|
│ Update callback │ _update_brightness() │ _update_rgb() │
|
||||||
|
├─────────────────┼────────────────────────────────┼────────────────────────────────┤
|
||||||
|
│ Turn-on logic │ elif ATTR_BRIGHTNESS... block │ elif ATTR_RGB_COLOR... block │
|
||||||
|
└─────────────────┴────────────────────────────────┴────────────────────────────────┘
|
||||||
|
|
||||||
|
### Constructor (Lines 180–260)
|
||||||
|
|
||||||
|
```python
|
||||||
|
# 7 nearly identical if-blocks:
|
||||||
|
if (level_action := config.get(CONF_LEVEL_ACTION)) is not None:
|
||||||
|
self._level_script = Script(hass, level_action, ...)
|
||||||
|
# ... repeated for temperature, hs, rgb, rgbw, rgbww, effect
|
||||||
|
|
||||||
|
# 7 state variables:
|
||||||
|
self._brightness = None
|
||||||
|
self._temperature = None
|
||||||
|
self._hs_color = None
|
||||||
|
self._rgb_color = None
|
||||||
|
self._rgbw_color = None
|
||||||
|
self._rgbww_color = None
|
||||||
|
self._effect = None
|
||||||
|
|
||||||
|
# Color mode detection — manual chain:
|
||||||
|
color_modes = {ColorMode.ONOFF}
|
||||||
|
if self._level_script: color_modes.add(ColorMode.BRIGHTNESS)
|
||||||
|
if self._temperature_script: color_modes.add(ColorMode.COLOR_TEMP)
|
||||||
|
# ... etc
|
||||||
|
```
|
||||||
|
|
||||||
|
### Properties (Lines 260–330)
|
||||||
|
|
||||||
|
```python
|
||||||
|
@property def brightness(self): return self._brightness
|
||||||
|
@property def color_temp_kelvin(self): ... # conversion logic
|
||||||
|
@property def hs_color(self): return self._hs_color
|
||||||
|
@property def rgb_color(self): return self._rgb_color
|
||||||
|
@property def rgbw_color(self): return self._rgbw_color
|
||||||
|
@property def rgbww_color(self): return self._rgbww_color
|
||||||
|
@property def effect(self): return self._effect
|
||||||
|
# ... all boilerplate
|
||||||
|
```
|
||||||
|
|
||||||
|
### Template Setup (Lines 330–420)
|
||||||
|
|
||||||
|
```python
|
||||||
|
@callback
|
||||||
|
def _async_setup_templates(self):
|
||||||
|
if self._template: self.add_template_attribute("_state", ...)
|
||||||
|
if self._level_template: self.add_template_attribute("_brightness", ...)
|
||||||
|
if self._max_mireds_template: self.add_template_attribute("_max_mireds_template", ...)
|
||||||
|
if self._min_mireds_template: self.add_template_attribute("_min_mireds_template", ...)
|
||||||
|
if self._temperature_template: self.add_template_attribute("_temperature", ...)
|
||||||
|
if self._color_template: self.add_template_attribute("_hs_color", ...)
|
||||||
|
if self._hs_template: self.add_template_attribute("_hs_color", ...)
|
||||||
|
if self._rgb_template: self.add_template_attribute("_rgb_color", ...)
|
||||||
|
if self._rgbw_template: self.add_template_attribute("_rgbw_color", ...)
|
||||||
|
if self._rgbww_template: self.add_template_attribute("_rgbww_color", ...)
|
||||||
|
if self._effect_list_template: self.add_template_attribute("_effect_list", ...)
|
||||||
|
if self._effect_template: self.add_template_attribute("_effect", ...)
|
||||||
|
if self._supports_transition_template: self.add_template_attribute(...)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Turn On (Lines 420–650) — Giant if/elif Chain
|
||||||
|
|
||||||
|
```python
|
||||||
|
async def async_turn_on(self, **kwargs):
|
||||||
|
# 7 optimistic-set blocks (RGB, RGBW, RGBWW each ~25 lines)
|
||||||
|
# Then 7 script-dispatch blocks:
|
||||||
|
if ATTR_COLOR_TEMP_KELVIN in kwargs and self._temperature_script:
|
||||||
|
await self.async_run_script(self._temperature_script, ...)
|
||||||
|
elif ATTR_EFFECT in kwargs and self._effect_script:
|
||||||
|
await self.async_run_script(self._effect_script, ...)
|
||||||
|
elif ATTR_HS_COLOR in kwargs and self._color_script:
|
||||||
|
...
|
||||||
|
elif ATTR_HS_COLOR in kwargs and self._hs_script:
|
||||||
|
...
|
||||||
|
elif ATTR_RGBWW_COLOR in kwargs and self._rgbww_script:
|
||||||
|
...
|
||||||
|
elif ATTR_RGBW_COLOR in kwargs and self._rgbw_script:
|
||||||
|
...
|
||||||
|
elif ATTR_RGB_COLOR in kwargs and self._rgb_script:
|
||||||
|
...
|
||||||
|
elif ATTR_BRIGHTNESS in kwargs and self._level_script:
|
||||||
|
...
|
||||||
|
else:
|
||||||
|
await self.async_run_script(self._on_script, ...)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Update Callbacks (Lines 650–850)
|
||||||
|
|
||||||
|
```python
|
||||||
|
@callback def _update_brightness(self, brightness): ...
|
||||||
|
@callback def _update_temperature(self, temperature): ...
|
||||||
|
@callback def _update_hs(self, hs_color): ...
|
||||||
|
@callback def _update_rgb(self, rgb_color): ...
|
||||||
|
@callback def _update_rgbw(self, rgbw_color): ...
|
||||||
|
@callback def _update_rgbww(self, rgbww_color): ...
|
||||||
|
@callback def _update_effect(self, effect): ...
|
||||||
|
@callback def _update_effect_list(self, effect_list): ...
|
||||||
|
@callback def _update_max_mireds(self, max_mireds): ...
|
||||||
|
@callback def _update_min_mireds(self, min_mireds): ...
|
||||||
|
@callback def _update_supports_transition(self, supports_transition): ...
|
||||||
|
```
|
||||||
|
|
||||||
|
────────────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
The Refactoring
|
||||||
|
|
||||||
|
Replace all of the above with a data-driven approach:
|
||||||
|
|
||||||
|
```python
|
||||||
|
@dataclass
|
||||||
|
class ColorModeHandler:
|
||||||
|
color_mode: ColorMode
|
||||||
|
script_key: str # e.g., "rgb_action"
|
||||||
|
template_key: str # e.g., "rgb_template"
|
||||||
|
state_attr: str # e.g., "_rgb_color"
|
||||||
|
property_name: str # e.g., "rgb_color"
|
||||||
|
attr_key: str # e.g., ATTR_RGB_COLOR
|
||||||
|
param_builder: Callable # converts kwargs -> run_variables
|
||||||
|
optimistic_clear: list[str] # which other attrs to clear on optimistic set
|
||||||
|
|
||||||
|
HANDLERS = [
|
||||||
|
ColorModeHandler(ColorMode.BRIGHTNESS, "level_action", "level_template",
|
||||||
|
"_brightness", "brightness", ATTR_BRIGHTNESS, ...),
|
||||||
|
ColorModeHandler(ColorMode.COLOR_TEMP, "temperature_action", "temperature_template",
|
||||||
|
"_temperature", "color_temp_kelvin", ATTR_COLOR_TEMP_KELVIN, ...),
|
||||||
|
# ... 5 more
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
Then:
|
||||||
|
- Constructor: loop over HANDLERS, create scripts/templates/state vars dynamically
|
||||||
|
- Properties: use __getattr__ or generate via cached_property loop
|
||||||
|
- Template setup: loop over HANDLERS, call add_template_attribute
|
||||||
|
- Turn on: loop over HANDLERS, match attr_key in kwargs
|
||||||
|
- Update callbacks: single generic _update_state(attr, value) + validator map
|
||||||
|
|
||||||
|
Resu
|
||||||
166
home-assistant/.core_files.yaml
Normal file
166
home-assistant/.core_files.yaml
Normal file
@@ -0,0 +1,166 @@
|
|||||||
|
# Defines a list of files that are part of main core of Home Assistant.
|
||||||
|
# Changes to these files/filters define how our CI test suite is ran.
|
||||||
|
core: &core
|
||||||
|
- homeassistant/*.py
|
||||||
|
- homeassistant/auth/**
|
||||||
|
- homeassistant/helpers/**
|
||||||
|
- homeassistant/package_constraints.txt
|
||||||
|
- homeassistant/util/**
|
||||||
|
- mypy.ini
|
||||||
|
- pyproject.toml
|
||||||
|
- requirements.txt
|
||||||
|
- setup.cfg
|
||||||
|
|
||||||
|
# Our base platforms, that are used by other integrations
|
||||||
|
base_platforms: &base_platforms
|
||||||
|
- homeassistant/components/air_quality/**
|
||||||
|
- homeassistant/components/alarm_control_panel/**
|
||||||
|
- homeassistant/components/assist_satellite/**
|
||||||
|
- homeassistant/components/binary_sensor/**
|
||||||
|
- homeassistant/components/button/**
|
||||||
|
- homeassistant/components/calendar/**
|
||||||
|
- homeassistant/components/camera/**
|
||||||
|
- homeassistant/components/climate/**
|
||||||
|
- homeassistant/components/cover/**
|
||||||
|
- homeassistant/components/date/**
|
||||||
|
- homeassistant/components/datetime/**
|
||||||
|
- homeassistant/components/device_tracker/**
|
||||||
|
- homeassistant/components/diagnostics/**
|
||||||
|
- homeassistant/components/event/**
|
||||||
|
- homeassistant/components/fan/**
|
||||||
|
- homeassistant/components/geo_location/**
|
||||||
|
- homeassistant/components/humidifier/**
|
||||||
|
- homeassistant/components/image/**
|
||||||
|
- homeassistant/components/image_processing/**
|
||||||
|
- homeassistant/components/lawn_mower/**
|
||||||
|
- homeassistant/components/light/**
|
||||||
|
- homeassistant/components/lock/**
|
||||||
|
- homeassistant/components/media_player/**
|
||||||
|
- homeassistant/components/notify/**
|
||||||
|
- homeassistant/components/number/**
|
||||||
|
- homeassistant/components/remote/**
|
||||||
|
- homeassistant/components/scene/**
|
||||||
|
- homeassistant/components/select/**
|
||||||
|
- homeassistant/components/sensor/**
|
||||||
|
- homeassistant/components/siren/**
|
||||||
|
- homeassistant/components/stt/**
|
||||||
|
- homeassistant/components/switch/**
|
||||||
|
- homeassistant/components/text/**
|
||||||
|
- homeassistant/components/time/**
|
||||||
|
- homeassistant/components/todo/**
|
||||||
|
- homeassistant/components/tts/**
|
||||||
|
- homeassistant/components/update/**
|
||||||
|
- homeassistant/components/vacuum/**
|
||||||
|
- homeassistant/components/valve/**
|
||||||
|
- homeassistant/components/water_heater/**
|
||||||
|
- homeassistant/components/weather/**
|
||||||
|
|
||||||
|
# Extra components that trigger the full suite
|
||||||
|
components: &components
|
||||||
|
- homeassistant/components/alexa/**
|
||||||
|
- homeassistant/components/application_credentials/**
|
||||||
|
- homeassistant/components/assist_pipeline/**
|
||||||
|
- homeassistant/components/auth/**
|
||||||
|
- homeassistant/components/automation/**
|
||||||
|
- homeassistant/components/backup/**
|
||||||
|
- homeassistant/components/blueprint/**
|
||||||
|
- homeassistant/components/bluetooth/**
|
||||||
|
- homeassistant/components/cloud/**
|
||||||
|
- homeassistant/components/config/**
|
||||||
|
- homeassistant/components/configurator/**
|
||||||
|
- homeassistant/components/conversation/**
|
||||||
|
- homeassistant/components/demo/**
|
||||||
|
- homeassistant/components/device_automation/**
|
||||||
|
- homeassistant/components/dhcp/**
|
||||||
|
- homeassistant/components/discovery/**
|
||||||
|
- homeassistant/components/energy/**
|
||||||
|
- homeassistant/components/ffmpeg/**
|
||||||
|
- homeassistant/components/frontend/**
|
||||||
|
- homeassistant/components/google_assistant/**
|
||||||
|
- homeassistant/components/group/**
|
||||||
|
- homeassistant/components/hassio/**
|
||||||
|
- homeassistant/components/homeassistant/**
|
||||||
|
- homeassistant/components/homeassistant_hardware/**
|
||||||
|
- homeassistant/components/http/**
|
||||||
|
- homeassistant/components/image/**
|
||||||
|
- homeassistant/components/input_boolean/**
|
||||||
|
- homeassistant/components/input_button/**
|
||||||
|
- homeassistant/components/input_datetime/**
|
||||||
|
- homeassistant/components/input_number/**
|
||||||
|
- homeassistant/components/input_select/**
|
||||||
|
- homeassistant/components/input_text/**
|
||||||
|
- homeassistant/components/logbook/**
|
||||||
|
- homeassistant/components/logger/**
|
||||||
|
- homeassistant/components/lovelace/**
|
||||||
|
- homeassistant/components/media_source/**
|
||||||
|
- homeassistant/components/mjpeg/**
|
||||||
|
- homeassistant/components/modbus/**
|
||||||
|
- homeassistant/components/mqtt/**
|
||||||
|
- homeassistant/components/network/**
|
||||||
|
- homeassistant/components/onboarding/**
|
||||||
|
- homeassistant/components/otp/**
|
||||||
|
- homeassistant/components/persistent_notification/**
|
||||||
|
- homeassistant/components/person/**
|
||||||
|
- homeassistant/components/recorder/**
|
||||||
|
- homeassistant/components/recovery_mode/**
|
||||||
|
- homeassistant/components/repairs/**
|
||||||
|
- homeassistant/components/script/**
|
||||||
|
- homeassistant/components/shopping_list/**
|
||||||
|
- homeassistant/components/ssdp/**
|
||||||
|
- homeassistant/components/stream/**
|
||||||
|
- homeassistant/components/sun/**
|
||||||
|
- homeassistant/components/system_health/**
|
||||||
|
- homeassistant/components/tag/**
|
||||||
|
- homeassistant/components/template/**
|
||||||
|
- homeassistant/components/timer/**
|
||||||
|
- homeassistant/components/trace/**
|
||||||
|
- homeassistant/components/usb/**
|
||||||
|
- homeassistant/components/webhook/**
|
||||||
|
- homeassistant/components/websocket_api/**
|
||||||
|
- homeassistant/components/zeroconf/**
|
||||||
|
- homeassistant/components/zone/**
|
||||||
|
|
||||||
|
# Testing related files that affect the whole test/linting suite
|
||||||
|
tests: &tests
|
||||||
|
- codecov.yaml
|
||||||
|
- pylint/**
|
||||||
|
- requirements_test_pre_commit.txt
|
||||||
|
- requirements_test.txt
|
||||||
|
- tests/*.py
|
||||||
|
- tests/auth/**
|
||||||
|
- tests/backports/**
|
||||||
|
- tests/components/conftest.py
|
||||||
|
- tests/components/diagnostics/**
|
||||||
|
- tests/components/history/**
|
||||||
|
- tests/components/light/common.py
|
||||||
|
- tests/components/logbook/**
|
||||||
|
- tests/components/recorder/**
|
||||||
|
- tests/components/repairs/**
|
||||||
|
- tests/components/sensor/**
|
||||||
|
- tests/hassfest/**
|
||||||
|
- tests/helpers/**
|
||||||
|
- tests/mock/**
|
||||||
|
- tests/pylint/**
|
||||||
|
- tests/scripts/**
|
||||||
|
- tests/test_util/**
|
||||||
|
- tests/testing_config/**
|
||||||
|
- tests/util/**
|
||||||
|
|
||||||
|
other: &other
|
||||||
|
- .github/workflows/**
|
||||||
|
- homeassistant/scripts/**
|
||||||
|
|
||||||
|
requirements: &requirements
|
||||||
|
- .github/workflows/**
|
||||||
|
- homeassistant/package_constraints.txt
|
||||||
|
- requirements*.txt
|
||||||
|
- pyproject.toml
|
||||||
|
- script/licenses.py
|
||||||
|
|
||||||
|
any:
|
||||||
|
- *base_platforms
|
||||||
|
- *components
|
||||||
|
- *core
|
||||||
|
- *other
|
||||||
|
- *requirements
|
||||||
|
- *tests
|
||||||
71
home-assistant/.devcontainer/devcontainer.json
Normal file
71
home-assistant/.devcontainer/devcontainer.json
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
{
|
||||||
|
"name": "Home Assistant Dev",
|
||||||
|
"context": "..",
|
||||||
|
"dockerFile": "../Dockerfile.dev",
|
||||||
|
"postCreateCommand": "git config --global --add safe.directory ${containerWorkspaceFolder} && script/setup",
|
||||||
|
"postStartCommand": "script/bootstrap",
|
||||||
|
"containerEnv": {
|
||||||
|
"PYTHONASYNCIODEBUG": "1"
|
||||||
|
},
|
||||||
|
"features": {
|
||||||
|
"ghcr.io/devcontainers/features/github-cli:1": {}
|
||||||
|
},
|
||||||
|
// Port 5683 udp is used by Shelly integration
|
||||||
|
"appPort": ["8123:8123", "5683:5683/udp"],
|
||||||
|
"runArgs": [
|
||||||
|
"-e",
|
||||||
|
"GIT_EDITOR=code --wait",
|
||||||
|
"--security-opt",
|
||||||
|
"label=disable"
|
||||||
|
],
|
||||||
|
"customizations": {
|
||||||
|
"vscode": {
|
||||||
|
"extensions": [
|
||||||
|
"charliermarsh.ruff",
|
||||||
|
"ms-python.pylint",
|
||||||
|
"ms-python.vscode-pylance",
|
||||||
|
"visualstudioexptteam.vscodeintellicode",
|
||||||
|
"redhat.vscode-yaml",
|
||||||
|
"esbenp.prettier-vscode",
|
||||||
|
"GitHub.vscode-pull-request-github",
|
||||||
|
"GitHub.copilot"
|
||||||
|
],
|
||||||
|
// Please keep this file in sync with settings in home-assistant/.vscode/settings.default.json
|
||||||
|
"settings": {
|
||||||
|
"python.experiments.optOutFrom": ["pythonTestAdapter"],
|
||||||
|
"python.defaultInterpreterPath": "/home/vscode/.local/ha-venv/bin/python",
|
||||||
|
"python.pythonPath": "/home/vscode/.local/ha-venv/bin/python",
|
||||||
|
"python.terminal.activateEnvInCurrentTerminal": true,
|
||||||
|
"python.testing.pytestArgs": ["--no-cov"],
|
||||||
|
"pylint.importStrategy": "fromEnvironment",
|
||||||
|
"editor.formatOnPaste": false,
|
||||||
|
"editor.formatOnSave": true,
|
||||||
|
"editor.formatOnType": true,
|
||||||
|
"files.trimTrailingWhitespace": true,
|
||||||
|
"terminal.integrated.profiles.linux": {
|
||||||
|
"zsh": {
|
||||||
|
"path": "/usr/bin/zsh"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"terminal.integrated.defaultProfile.linux": "zsh",
|
||||||
|
"yaml.customTags": [
|
||||||
|
"!input scalar",
|
||||||
|
"!secret scalar",
|
||||||
|
"!include_dir_named scalar",
|
||||||
|
"!include_dir_list scalar",
|
||||||
|
"!include_dir_merge_list scalar",
|
||||||
|
"!include_dir_merge_named scalar"
|
||||||
|
],
|
||||||
|
"[python]": {
|
||||||
|
"editor.defaultFormatter": "charliermarsh.ruff"
|
||||||
|
},
|
||||||
|
"json.schemas": [
|
||||||
|
{
|
||||||
|
"fileMatch": ["homeassistant/components/*/manifest.json"],
|
||||||
|
"url": "./script/json_schemas/manifest_schema.json"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
20
home-assistant/.dockerignore
Normal file
20
home-assistant/.dockerignore
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
# General files
|
||||||
|
.git
|
||||||
|
.github
|
||||||
|
config
|
||||||
|
docs
|
||||||
|
|
||||||
|
# Development
|
||||||
|
.devcontainer
|
||||||
|
.vscode
|
||||||
|
.tool-versions
|
||||||
|
|
||||||
|
# Test related files
|
||||||
|
tests
|
||||||
|
|
||||||
|
# Other virtualization methods
|
||||||
|
venv
|
||||||
|
.vagrant
|
||||||
|
|
||||||
|
# Temporary files
|
||||||
|
**/__pycache__
|
||||||
14
home-assistant/.git-blame-ignore-revs
Normal file
14
home-assistant/.git-blame-ignore-revs
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
# Black
|
||||||
|
4de97abc3aa83188666336ce0a015a5bab75bc8f
|
||||||
|
|
||||||
|
# Switch formatting from black to ruff-format (#102893)
|
||||||
|
706add4a57120a93d7b7fe40e722b00d634c76c2
|
||||||
|
|
||||||
|
# Prettify json (component test fixtures) (#68892)
|
||||||
|
053c4428a933c3c04c22642f93c93fccba3e8bfd
|
||||||
|
|
||||||
|
# Prettify json (tests) (#68888)
|
||||||
|
496d90bf00429d9d924caeb0155edc0bf54e86b9
|
||||||
|
|
||||||
|
# Bump ruff to 0.3.4 (#112690)
|
||||||
|
6bb4e7d62c60389608acf4a7d7dacd8f029307dd
|
||||||
13
home-assistant/.gitattributes
vendored
Normal file
13
home-assistant/.gitattributes
vendored
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
# Ensure Docker script files uses LF to support Docker for Windows.
|
||||||
|
# Ensure "git config --global core.autocrlf input" before you clone
|
||||||
|
* text eol=lf
|
||||||
|
*.py whitespace=error
|
||||||
|
|
||||||
|
*.ico binary
|
||||||
|
*.jpg binary
|
||||||
|
*.png binary
|
||||||
|
*.zip binary
|
||||||
|
*.mp3 binary
|
||||||
|
*.pcm binary
|
||||||
|
|
||||||
|
Dockerfile.dev linguist-language=Dockerfile
|
||||||
1
home-assistant/.github/FUNDING.yml
vendored
Normal file
1
home-assistant/.github/FUNDING.yml
vendored
Normal file
@@ -0,0 +1 @@
|
|||||||
|
custom: https://www.openhomefoundation.org
|
||||||
49
home-assistant/.github/ISSUE_TEMPLATE.md
vendored
Normal file
49
home-assistant/.github/ISSUE_TEMPLATE.md
vendored
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
<!-- READ THIS FIRST:
|
||||||
|
- If you need additional help with this template, please refer to https://www.home-assistant.io/help/reporting_issues/
|
||||||
|
- Make sure you are running the latest version of Home Assistant before reporting an issue: https://github.com/home-assistant/core/releases
|
||||||
|
- Do not report issues for integrations if you are using custom components or integrations.
|
||||||
|
- Provide as many details as possible. Paste logs, configuration samples and code into the backticks.
|
||||||
|
DO NOT DELETE ANY TEXT from this template! Otherwise, your issue may be closed without comment.
|
||||||
|
-->
|
||||||
|
## The problem
|
||||||
|
<!--
|
||||||
|
Describe the issue you are experiencing here to communicate to the
|
||||||
|
maintainers. Tell us what you were trying to do and what happened.
|
||||||
|
-->
|
||||||
|
|
||||||
|
|
||||||
|
## Environment
|
||||||
|
<!--
|
||||||
|
Provide details about the versions you are using, which helps us to reproduce
|
||||||
|
and find the issue quicker. Version information is found in the
|
||||||
|
Home Assistant frontend: Settings -> About.
|
||||||
|
-->
|
||||||
|
|
||||||
|
- Home Assistant Core release with the issue:
|
||||||
|
- Last working Home Assistant Core release (if known):
|
||||||
|
- Operating environment (OS/Container/Supervised/Core):
|
||||||
|
- Integration causing this issue:
|
||||||
|
- Link to integration documentation on our website:
|
||||||
|
|
||||||
|
## Problem-relevant `configuration.yaml`
|
||||||
|
<!--
|
||||||
|
An example configuration that caused the problem for you. Fill this out even
|
||||||
|
if it seems unimportant to you. Please be sure to remove personal information
|
||||||
|
like passwords, private URLs and other credentials.
|
||||||
|
-->
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
## Traceback/Error logs
|
||||||
|
<!--
|
||||||
|
If you come across any trace or error logs, please provide them.
|
||||||
|
-->
|
||||||
|
|
||||||
|
```txt
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
## Additional information
|
||||||
|
|
||||||
105
home-assistant/.github/ISSUE_TEMPLATE/bug_report.yml
vendored
Normal file
105
home-assistant/.github/ISSUE_TEMPLATE/bug_report.yml
vendored
Normal file
@@ -0,0 +1,105 @@
|
|||||||
|
name: Report an issue with Home Assistant Core
|
||||||
|
description: Report an issue with Home Assistant Core.
|
||||||
|
body:
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: |
|
||||||
|
This issue form is for reporting bugs only!
|
||||||
|
|
||||||
|
If you have a feature or enhancement request, please use the [feature request][fr] section of our [Community Forum][fr].
|
||||||
|
|
||||||
|
[fr]: https://community.home-assistant.io/c/feature-requests
|
||||||
|
- type: textarea
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
attributes:
|
||||||
|
label: The problem
|
||||||
|
description: >-
|
||||||
|
Describe the issue you are experiencing here, to communicate to the
|
||||||
|
maintainers. Tell us what you were trying to do and what happened.
|
||||||
|
|
||||||
|
Provide a clear and concise description of what the problem is.
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: |
|
||||||
|
## Environment
|
||||||
|
- type: input
|
||||||
|
id: version
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
attributes:
|
||||||
|
label: What version of Home Assistant Core has the issue?
|
||||||
|
placeholder: core-
|
||||||
|
description: >
|
||||||
|
Can be found in: [Settings ⇒ System ⇒ Repairs ⇒ Three Dots in Upper Right ⇒ System information](https://my.home-assistant.io/redirect/system_health/).
|
||||||
|
|
||||||
|
[](https://my.home-assistant.io/redirect/system_health/)
|
||||||
|
- type: input
|
||||||
|
attributes:
|
||||||
|
label: What was the last working version of Home Assistant Core?
|
||||||
|
placeholder: core-
|
||||||
|
description: >
|
||||||
|
If known, otherwise leave blank.
|
||||||
|
- type: dropdown
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
attributes:
|
||||||
|
label: What type of installation are you running?
|
||||||
|
description: >
|
||||||
|
Can be found in: [Settings ⇒ System ⇒ Repairs ⇒ Three Dots in Upper Right ⇒ System information](https://my.home-assistant.io/redirect/system_health/).
|
||||||
|
|
||||||
|
[](https://my.home-assistant.io/redirect/system_health/)
|
||||||
|
options:
|
||||||
|
- Home Assistant OS
|
||||||
|
- Home Assistant Container
|
||||||
|
- Home Assistant Supervised
|
||||||
|
- Home Assistant Core
|
||||||
|
- type: input
|
||||||
|
id: integration_name
|
||||||
|
attributes:
|
||||||
|
label: Integration causing the issue
|
||||||
|
description: >
|
||||||
|
The name of the integration, for example Automation or Philips Hue.
|
||||||
|
- type: input
|
||||||
|
id: integration_link
|
||||||
|
attributes:
|
||||||
|
label: Link to integration documentation on our website
|
||||||
|
placeholder: "https://www.home-assistant.io/integrations/..."
|
||||||
|
description: |
|
||||||
|
Providing a link [to the documentation][docs] helps us categorize the issue and might speed up the
|
||||||
|
investigation by automatically informing a contributor, while also providing a useful reference for others.
|
||||||
|
|
||||||
|
[docs]: https://www.home-assistant.io/integrations
|
||||||
|
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: |
|
||||||
|
# Details
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: Diagnostics information
|
||||||
|
placeholder: "drag-and-drop the diagnostics data file here (do not copy-and-paste the content)"
|
||||||
|
description: >-
|
||||||
|
Many integrations provide the ability to [download diagnostic data](https://www.home-assistant.io/docs/configuration/troubleshooting/#debug-logs-and-diagnostics).
|
||||||
|
|
||||||
|
**It would really help if you could download the diagnostics data for the device you are having issues with,
|
||||||
|
and <ins>drag-and-drop that file into the textbox below.</ins>**
|
||||||
|
|
||||||
|
It generally allows pinpointing defects and thus resolving issues faster.
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: Example YAML snippet
|
||||||
|
description: |
|
||||||
|
If applicable, please provide an example piece of YAML that can help reproduce this problem.
|
||||||
|
This can be from an automation, script, scene or configuration.
|
||||||
|
render: yaml
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: Anything in the logs that might be useful for us?
|
||||||
|
description: For example, error message, or stack traces.
|
||||||
|
render: txt
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: Additional information
|
||||||
|
description: >
|
||||||
|
If you have any additional information for us, use the field below.
|
||||||
17
home-assistant/.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
17
home-assistant/.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
blank_issues_enabled: false
|
||||||
|
contact_links:
|
||||||
|
- name: Report a bug with the UI, Frontend or Dashboards
|
||||||
|
url: https://github.com/home-assistant/frontend/issues
|
||||||
|
about: This is the issue tracker for our backend. Please report issues with the UI in the frontend repository.
|
||||||
|
- name: Report incorrect or missing information on our website
|
||||||
|
url: https://github.com/home-assistant/home-assistant.io/issues
|
||||||
|
about: Our documentation has its own issue tracker. Please report issues with the website there.
|
||||||
|
- name: I have a question or need support
|
||||||
|
url: https://www.home-assistant.io/help
|
||||||
|
about: We use GitHub for tracking bugs, check our website for resources on getting help.
|
||||||
|
- name: Feature Request
|
||||||
|
url: https://community.home-assistant.io/c/feature-requests
|
||||||
|
about: Please use our Community Forum for making feature requests.
|
||||||
|
- name: I'm unsure where to go
|
||||||
|
url: https://www.home-assistant.io/join-chat
|
||||||
|
about: If you are unsure where to go, then joining our chat is recommended; Just ask!
|
||||||
110
home-assistant/.github/PULL_REQUEST_TEMPLATE.md
vendored
Normal file
110
home-assistant/.github/PULL_REQUEST_TEMPLATE.md
vendored
Normal file
@@ -0,0 +1,110 @@
|
|||||||
|
<!--
|
||||||
|
You are amazing! Thanks for contributing to our project!
|
||||||
|
Please, DO NOT DELETE ANY TEXT from this template! (unless instructed).
|
||||||
|
-->
|
||||||
|
## Breaking change
|
||||||
|
<!--
|
||||||
|
If your PR contains a breaking change for existing users, it is important
|
||||||
|
to tell them what breaks, how to make it work again and why we did this.
|
||||||
|
This piece of text is published with the release notes, so it helps if you
|
||||||
|
write it towards our users, not us.
|
||||||
|
Note: Remove this section if this PR is NOT a breaking change.
|
||||||
|
-->
|
||||||
|
|
||||||
|
|
||||||
|
## Proposed change
|
||||||
|
<!--
|
||||||
|
Describe the big picture of your changes here to communicate to the
|
||||||
|
maintainers why we should accept this pull request. If it fixes a bug
|
||||||
|
or resolves a feature request, be sure to link to that issue in the
|
||||||
|
additional information section.
|
||||||
|
-->
|
||||||
|
|
||||||
|
|
||||||
|
## Type of change
|
||||||
|
<!--
|
||||||
|
What type of change does your PR introduce to Home Assistant?
|
||||||
|
NOTE: Please, check only 1! box!
|
||||||
|
If your PR requires multiple boxes to be checked, you'll most likely need to
|
||||||
|
split it into multiple PRs. This makes things easier and faster to code review.
|
||||||
|
-->
|
||||||
|
|
||||||
|
- [ ] Dependency upgrade
|
||||||
|
- [ ] Bugfix (non-breaking change which fixes an issue)
|
||||||
|
- [ ] New integration (thank you!)
|
||||||
|
- [ ] New feature (which adds functionality to an existing integration)
|
||||||
|
- [ ] Deprecation (breaking change to happen in the future)
|
||||||
|
- [ ] Breaking change (fix/feature causing existing functionality to break)
|
||||||
|
- [ ] Code quality improvements to existing code or addition of tests
|
||||||
|
|
||||||
|
## Additional information
|
||||||
|
<!--
|
||||||
|
Details are important, and help maintainers processing your PR.
|
||||||
|
Please be sure to fill out additional details, if applicable.
|
||||||
|
-->
|
||||||
|
|
||||||
|
- This PR fixes or closes issue: fixes #
|
||||||
|
- This PR is related to issue:
|
||||||
|
- Link to documentation pull request:
|
||||||
|
|
||||||
|
## Checklist
|
||||||
|
<!--
|
||||||
|
Put an `x` in the boxes that apply. You can also fill these out after
|
||||||
|
creating the PR. If you're unsure about any of them, don't hesitate to ask.
|
||||||
|
We're here to help! This is simply a reminder of what we are going to look
|
||||||
|
for before merging your code.
|
||||||
|
-->
|
||||||
|
|
||||||
|
- [ ] The code change is tested and works locally.
|
||||||
|
- [ ] Local tests pass. **Your PR cannot be merged unless tests pass**
|
||||||
|
- [ ] There is no commented out code in this PR.
|
||||||
|
- [ ] I have followed the [development checklist][dev-checklist]
|
||||||
|
- [ ] I have followed the [perfect PR recommendations][perfect-pr]
|
||||||
|
- [ ] The code has been formatted using Ruff (`ruff format homeassistant tests`)
|
||||||
|
- [ ] Tests have been added to verify that the new code works.
|
||||||
|
|
||||||
|
If user exposed functionality or configuration variables are added/changed:
|
||||||
|
|
||||||
|
- [ ] Documentation added/updated for [www.home-assistant.io][docs-repository]
|
||||||
|
|
||||||
|
If the code communicates with devices, web services, or third-party tools:
|
||||||
|
|
||||||
|
- [ ] The [manifest file][manifest-docs] has all fields filled out correctly.
|
||||||
|
Updated and included derived files by running: `python3 -m script.hassfest`.
|
||||||
|
- [ ] New or updated dependencies have been added to `requirements_all.txt`.
|
||||||
|
Updated by running `python3 -m script.gen_requirements_all`.
|
||||||
|
- [ ] For the updated dependencies - a link to the changelog, or at minimum a diff between library versions is added to the PR description.
|
||||||
|
|
||||||
|
<!--
|
||||||
|
This project is very active and we have a high turnover of pull requests.
|
||||||
|
|
||||||
|
Unfortunately, the number of incoming pull requests is higher than what our
|
||||||
|
reviewers can review and merge so there is a long backlog of pull requests
|
||||||
|
waiting for review. You can help here!
|
||||||
|
|
||||||
|
By reviewing another pull request, you will help raise the code quality of
|
||||||
|
that pull request and the final review will be faster. This way the general
|
||||||
|
pace of pull request reviews will go up and your wait time will go down.
|
||||||
|
|
||||||
|
When picking a pull request to review, try to choose one that hasn't yet
|
||||||
|
been reviewed.
|
||||||
|
|
||||||
|
Thanks for helping out!
|
||||||
|
-->
|
||||||
|
|
||||||
|
To help with the load of incoming pull requests:
|
||||||
|
|
||||||
|
- [ ] I have reviewed two other [open pull requests][prs] in this repository.
|
||||||
|
|
||||||
|
[prs]: https://github.com/home-assistant/core/pulls?q=is%3Aopen+is%3Apr+-author%3A%40me+-draft%3Atrue+-label%3Awaiting-for-upstream+sort%3Acreated-desc+review%3Anone+-status%3Afailure
|
||||||
|
|
||||||
|
<!--
|
||||||
|
Thank you for contributing <3
|
||||||
|
|
||||||
|
Below, some useful links you could explore:
|
||||||
|
-->
|
||||||
|
[dev-checklist]: https://developers.home-assistant.io/docs/development_checklist/
|
||||||
|
[manifest-docs]: https://developers.home-assistant.io/docs/creating_integration_manifest/
|
||||||
|
[quality-scale]: https://developers.home-assistant.io/docs/integration_quality_scale_index/
|
||||||
|
[docs-repository]: https://github.com/home-assistant/home-assistant.io
|
||||||
|
[perfect-pr]: https://developers.home-assistant.io/docs/review-process/#creating-the-perfect-pr
|
||||||
BIN
home-assistant/.github/assets/screenshot-integrations.png
vendored
Normal file
BIN
home-assistant/.github/assets/screenshot-integrations.png
vendored
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 65 KiB |
BIN
home-assistant/.github/assets/screenshot-states.png
vendored
Normal file
BIN
home-assistant/.github/assets/screenshot-states.png
vendored
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 115 KiB |
8
home-assistant/.github/dependabot.yml
vendored
Normal file
8
home-assistant/.github/dependabot.yml
vendored
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
version: 2
|
||||||
|
updates:
|
||||||
|
- package-ecosystem: "github-actions"
|
||||||
|
directory: "/"
|
||||||
|
schedule:
|
||||||
|
interval: daily
|
||||||
|
time: "06:00"
|
||||||
|
open-pull-requests-limit: 10
|
||||||
538
home-assistant/.github/workflows/builder.yml
vendored
Normal file
538
home-assistant/.github/workflows/builder.yml
vendored
Normal file
@@ -0,0 +1,538 @@
|
|||||||
|
name: Build images
|
||||||
|
|
||||||
|
# yamllint disable-line rule:truthy
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
release:
|
||||||
|
types: ["published"]
|
||||||
|
schedule:
|
||||||
|
- cron: "0 2 * * *"
|
||||||
|
|
||||||
|
env:
|
||||||
|
BUILD_TYPE: core
|
||||||
|
DEFAULT_PYTHON: "3.13"
|
||||||
|
PIP_TIMEOUT: 60
|
||||||
|
UV_HTTP_TIMEOUT: 60
|
||||||
|
UV_SYSTEM_PYTHON: "true"
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
init:
|
||||||
|
name: Initialize build
|
||||||
|
if: github.repository_owner == 'home-assistant'
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
outputs:
|
||||||
|
architectures: ${{ steps.info.outputs.architectures }}
|
||||||
|
version: ${{ steps.version.outputs.version }}
|
||||||
|
channel: ${{ steps.version.outputs.channel }}
|
||||||
|
publish: ${{ steps.version.outputs.publish }}
|
||||||
|
steps:
|
||||||
|
- name: Checkout the repository
|
||||||
|
uses: actions/checkout@v4.2.2
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- name: Set up Python ${{ env.DEFAULT_PYTHON }}
|
||||||
|
uses: actions/setup-python@v5.3.0
|
||||||
|
with:
|
||||||
|
python-version: ${{ env.DEFAULT_PYTHON }}
|
||||||
|
|
||||||
|
- name: Get information
|
||||||
|
id: info
|
||||||
|
uses: home-assistant/actions/helpers/info@master
|
||||||
|
|
||||||
|
- name: Get version
|
||||||
|
id: version
|
||||||
|
uses: home-assistant/actions/helpers/version@master
|
||||||
|
with:
|
||||||
|
type: ${{ env.BUILD_TYPE }}
|
||||||
|
|
||||||
|
- name: Verify version
|
||||||
|
uses: home-assistant/actions/helpers/verify-version@master
|
||||||
|
with:
|
||||||
|
ignore-dev: true
|
||||||
|
|
||||||
|
- name: Fail if translations files are checked in
|
||||||
|
run: |
|
||||||
|
if [ -n "$(find homeassistant/components/*/translations -type f)" ]; then
|
||||||
|
echo "Translations files are checked in, please remove the following files:"
|
||||||
|
find homeassistant/components/*/translations -type f
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
- name: Download Translations
|
||||||
|
run: python3 -m script.translations download
|
||||||
|
env:
|
||||||
|
LOKALISE_TOKEN: ${{ secrets.LOKALISE_TOKEN }}
|
||||||
|
|
||||||
|
- name: Archive translations
|
||||||
|
shell: bash
|
||||||
|
run: find ./homeassistant/components/*/translations -name "*.json" | tar zcvf translations.tar.gz -T -
|
||||||
|
|
||||||
|
- name: Upload translations
|
||||||
|
uses: actions/upload-artifact@v4.5.0
|
||||||
|
with:
|
||||||
|
name: translations
|
||||||
|
path: translations.tar.gz
|
||||||
|
if-no-files-found: error
|
||||||
|
|
||||||
|
build_base:
|
||||||
|
name: Build ${{ matrix.arch }} base core image
|
||||||
|
if: github.repository_owner == 'home-assistant'
|
||||||
|
needs: init
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
packages: write
|
||||||
|
id-token: write
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
arch: ${{ fromJson(needs.init.outputs.architectures) }}
|
||||||
|
steps:
|
||||||
|
- name: Checkout the repository
|
||||||
|
uses: actions/checkout@v4.2.2
|
||||||
|
|
||||||
|
- name: Download nightly wheels of frontend
|
||||||
|
if: needs.init.outputs.channel == 'dev'
|
||||||
|
uses: dawidd6/action-download-artifact@v7
|
||||||
|
with:
|
||||||
|
github_token: ${{secrets.GITHUB_TOKEN}}
|
||||||
|
repo: home-assistant/frontend
|
||||||
|
branch: dev
|
||||||
|
workflow: nightly.yaml
|
||||||
|
workflow_conclusion: success
|
||||||
|
name: wheels
|
||||||
|
|
||||||
|
- name: Download nightly wheels of intents
|
||||||
|
if: needs.init.outputs.channel == 'dev'
|
||||||
|
uses: dawidd6/action-download-artifact@v7
|
||||||
|
with:
|
||||||
|
github_token: ${{secrets.GITHUB_TOKEN}}
|
||||||
|
repo: home-assistant/intents-package
|
||||||
|
branch: main
|
||||||
|
workflow: nightly.yaml
|
||||||
|
workflow_conclusion: success
|
||||||
|
name: package
|
||||||
|
|
||||||
|
- name: Set up Python ${{ env.DEFAULT_PYTHON }}
|
||||||
|
if: needs.init.outputs.channel == 'dev'
|
||||||
|
uses: actions/setup-python@v5.3.0
|
||||||
|
with:
|
||||||
|
python-version: ${{ env.DEFAULT_PYTHON }}
|
||||||
|
|
||||||
|
- name: Adjust nightly version
|
||||||
|
if: needs.init.outputs.channel == 'dev'
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
UV_PRERELEASE: allow
|
||||||
|
run: |
|
||||||
|
python3 -m pip install "$(grep '^uv' < requirements.txt)"
|
||||||
|
uv pip install packaging tomli
|
||||||
|
uv pip install .
|
||||||
|
python3 script/version_bump.py nightly --set-nightly-version "${{ needs.init.outputs.version }}"
|
||||||
|
|
||||||
|
if [[ "$(ls home_assistant_frontend*.whl)" =~ ^home_assistant_frontend-(.*)-py3-none-any.whl$ ]]; then
|
||||||
|
echo "Found frontend wheel, setting version to: ${BASH_REMATCH[1]}"
|
||||||
|
frontend_version="${BASH_REMATCH[1]}" yq \
|
||||||
|
--inplace e -o json \
|
||||||
|
'.requirements = ["home-assistant-frontend=="+env(frontend_version)]' \
|
||||||
|
homeassistant/components/frontend/manifest.json
|
||||||
|
|
||||||
|
sed -i "s|home-assistant-frontend==.*|home-assistant-frontend==${BASH_REMATCH[1]}|" \
|
||||||
|
homeassistant/package_constraints.txt
|
||||||
|
|
||||||
|
sed -i "s|home-assistant-frontend==.*||" requirements_all.txt
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ "$(ls home_assistant_intents*.whl)" =~ ^home_assistant_intents-(.*)-py3-none-any.whl$ ]]; then
|
||||||
|
echo "Found intents wheel, setting version to: ${BASH_REMATCH[1]}"
|
||||||
|
yq \
|
||||||
|
--inplace e -o json \
|
||||||
|
'del(.requirements[] | select(contains("home-assistant-intents")))' \
|
||||||
|
homeassistant/components/conversation/manifest.json
|
||||||
|
|
||||||
|
intents_version="${BASH_REMATCH[1]}" yq \
|
||||||
|
--inplace e -o json \
|
||||||
|
'.requirements += ["home-assistant-intents=="+env(intents_version)]' \
|
||||||
|
homeassistant/components/conversation/manifest.json
|
||||||
|
|
||||||
|
sed -i "s|home-assistant-intents==.*|home-assistant-intents==${BASH_REMATCH[1]}|" \
|
||||||
|
homeassistant/package_constraints.txt
|
||||||
|
|
||||||
|
sed -i "s|home-assistant-intents==.*||" requirements_all.txt
|
||||||
|
fi
|
||||||
|
|
||||||
|
- name: Adjustments for armhf
|
||||||
|
if: matrix.arch == 'armhf'
|
||||||
|
run: |
|
||||||
|
# Pandas has issues building on armhf, it is expected they
|
||||||
|
# will drop the platform in the near future (they consider it
|
||||||
|
# "flimsy" on 386). The following packages depend on pandas,
|
||||||
|
# so we comment them out.
|
||||||
|
sed -i "s|env-canada|# env-canada|g" requirements_all.txt
|
||||||
|
sed -i "s|noaa-coops|# noaa-coops|g" requirements_all.txt
|
||||||
|
sed -i "s|pyezviz|# pyezviz|g" requirements_all.txt
|
||||||
|
sed -i "s|pykrakenapi|# pykrakenapi|g" requirements_all.txt
|
||||||
|
|
||||||
|
- name: Download translations
|
||||||
|
uses: actions/download-artifact@v4.1.8
|
||||||
|
with:
|
||||||
|
name: translations
|
||||||
|
|
||||||
|
- name: Extract translations
|
||||||
|
run: |
|
||||||
|
tar xvf translations.tar.gz
|
||||||
|
rm translations.tar.gz
|
||||||
|
|
||||||
|
- name: Write meta info file
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
echo "${{ github.sha }};${{ github.ref }};${{ github.event_name }};${{ github.actor }}" > rootfs/OFFICIAL_IMAGE
|
||||||
|
|
||||||
|
- name: Login to GitHub Container Registry
|
||||||
|
uses: docker/login-action@v3.3.0
|
||||||
|
with:
|
||||||
|
registry: ghcr.io
|
||||||
|
username: ${{ github.repository_owner }}
|
||||||
|
password: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
- name: Build base image
|
||||||
|
uses: home-assistant/builder@2024.08.2
|
||||||
|
with:
|
||||||
|
args: |
|
||||||
|
$BUILD_ARGS \
|
||||||
|
--${{ matrix.arch }} \
|
||||||
|
--cosign \
|
||||||
|
--target /data \
|
||||||
|
--generic ${{ needs.init.outputs.version }}
|
||||||
|
|
||||||
|
build_machine:
|
||||||
|
name: Build ${{ matrix.machine }} machine core image
|
||||||
|
if: github.repository_owner == 'home-assistant'
|
||||||
|
needs: ["init", "build_base"]
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
packages: write
|
||||||
|
id-token: write
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
machine:
|
||||||
|
- generic-x86-64
|
||||||
|
- intel-nuc
|
||||||
|
- khadas-vim3
|
||||||
|
- odroid-c2
|
||||||
|
- odroid-c4
|
||||||
|
- odroid-m1
|
||||||
|
- odroid-n2
|
||||||
|
- odroid-xu
|
||||||
|
- qemuarm
|
||||||
|
- qemuarm-64
|
||||||
|
- qemux86
|
||||||
|
- qemux86-64
|
||||||
|
- raspberrypi
|
||||||
|
- raspberrypi2
|
||||||
|
- raspberrypi3
|
||||||
|
- raspberrypi3-64
|
||||||
|
- raspberrypi4
|
||||||
|
- raspberrypi4-64
|
||||||
|
- raspberrypi5-64
|
||||||
|
- tinker
|
||||||
|
- yellow
|
||||||
|
- green
|
||||||
|
steps:
|
||||||
|
- name: Checkout the repository
|
||||||
|
uses: actions/checkout@v4.2.2
|
||||||
|
|
||||||
|
- name: Set build additional args
|
||||||
|
run: |
|
||||||
|
# Create general tags
|
||||||
|
if [[ "${{ needs.init.outputs.version }}" =~ d ]]; then
|
||||||
|
echo "BUILD_ARGS=--additional-tag dev" >> $GITHUB_ENV
|
||||||
|
elif [[ "${{ needs.init.outputs.version }}" =~ b ]]; then
|
||||||
|
echo "BUILD_ARGS=--additional-tag beta" >> $GITHUB_ENV
|
||||||
|
else
|
||||||
|
echo "BUILD_ARGS=--additional-tag stable" >> $GITHUB_ENV
|
||||||
|
fi
|
||||||
|
|
||||||
|
- name: Login to GitHub Container Registry
|
||||||
|
uses: docker/login-action@v3.3.0
|
||||||
|
with:
|
||||||
|
registry: ghcr.io
|
||||||
|
username: ${{ github.repository_owner }}
|
||||||
|
password: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
- name: Build base image
|
||||||
|
uses: home-assistant/builder@2024.08.2
|
||||||
|
with:
|
||||||
|
args: |
|
||||||
|
$BUILD_ARGS \
|
||||||
|
--target /data/machine \
|
||||||
|
--cosign \
|
||||||
|
--machine "${{ needs.init.outputs.version }}=${{ matrix.machine }}"
|
||||||
|
|
||||||
|
publish_ha:
|
||||||
|
name: Publish version files
|
||||||
|
environment: ${{ needs.init.outputs.channel }}
|
||||||
|
if: github.repository_owner == 'home-assistant'
|
||||||
|
needs: ["init", "build_machine"]
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout the repository
|
||||||
|
uses: actions/checkout@v4.2.2
|
||||||
|
|
||||||
|
- name: Initialize git
|
||||||
|
uses: home-assistant/actions/helpers/git-init@master
|
||||||
|
with:
|
||||||
|
name: ${{ secrets.GIT_NAME }}
|
||||||
|
email: ${{ secrets.GIT_EMAIL }}
|
||||||
|
token: ${{ secrets.GIT_TOKEN }}
|
||||||
|
|
||||||
|
- name: Update version file
|
||||||
|
uses: home-assistant/actions/helpers/version-push@master
|
||||||
|
with:
|
||||||
|
key: "homeassistant[]"
|
||||||
|
key-description: "Home Assistant Core"
|
||||||
|
version: ${{ needs.init.outputs.version }}
|
||||||
|
channel: ${{ needs.init.outputs.channel }}
|
||||||
|
|
||||||
|
- name: Update version file (stable -> beta)
|
||||||
|
if: needs.init.outputs.channel == 'stable'
|
||||||
|
uses: home-assistant/actions/helpers/version-push@master
|
||||||
|
with:
|
||||||
|
key: "homeassistant[]"
|
||||||
|
key-description: "Home Assistant Core"
|
||||||
|
version: ${{ needs.init.outputs.version }}
|
||||||
|
channel: beta
|
||||||
|
|
||||||
|
publish_container:
|
||||||
|
name: Publish meta container for ${{ matrix.registry }}
|
||||||
|
environment: ${{ needs.init.outputs.channel }}
|
||||||
|
if: github.repository_owner == 'home-assistant'
|
||||||
|
needs: ["init", "build_base"]
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
packages: write
|
||||||
|
id-token: write
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
registry: ["ghcr.io/home-assistant", "docker.io/homeassistant"]
|
||||||
|
steps:
|
||||||
|
- name: Checkout the repository
|
||||||
|
uses: actions/checkout@v4.2.2
|
||||||
|
|
||||||
|
- name: Install Cosign
|
||||||
|
uses: sigstore/cosign-installer@v3.7.0
|
||||||
|
with:
|
||||||
|
cosign-release: "v2.2.3"
|
||||||
|
|
||||||
|
- name: Login to DockerHub
|
||||||
|
if: matrix.registry == 'docker.io/homeassistant'
|
||||||
|
uses: docker/login-action@v3.3.0
|
||||||
|
with:
|
||||||
|
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||||
|
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||||
|
|
||||||
|
- name: Login to GitHub Container Registry
|
||||||
|
if: matrix.registry == 'ghcr.io/home-assistant'
|
||||||
|
uses: docker/login-action@v3.3.0
|
||||||
|
with:
|
||||||
|
registry: ghcr.io
|
||||||
|
username: ${{ github.repository_owner }}
|
||||||
|
password: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
- name: Build Meta Image
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
export DOCKER_CLI_EXPERIMENTAL=enabled
|
||||||
|
|
||||||
|
function create_manifest() {
|
||||||
|
local tag_l=${1}
|
||||||
|
local tag_r=${2}
|
||||||
|
local registry=${{ matrix.registry }}
|
||||||
|
|
||||||
|
docker manifest create "${registry}/home-assistant:${tag_l}" \
|
||||||
|
"${registry}/amd64-homeassistant:${tag_r}" \
|
||||||
|
"${registry}/i386-homeassistant:${tag_r}" \
|
||||||
|
"${registry}/armhf-homeassistant:${tag_r}" \
|
||||||
|
"${registry}/armv7-homeassistant:${tag_r}" \
|
||||||
|
"${registry}/aarch64-homeassistant:${tag_r}"
|
||||||
|
|
||||||
|
docker manifest annotate "${registry}/home-assistant:${tag_l}" \
|
||||||
|
"${registry}/amd64-homeassistant:${tag_r}" \
|
||||||
|
--os linux --arch amd64
|
||||||
|
|
||||||
|
docker manifest annotate "${registry}/home-assistant:${tag_l}" \
|
||||||
|
"${registry}/i386-homeassistant:${tag_r}" \
|
||||||
|
--os linux --arch 386
|
||||||
|
|
||||||
|
docker manifest annotate "${registry}/home-assistant:${tag_l}" \
|
||||||
|
"${registry}/armhf-homeassistant:${tag_r}" \
|
||||||
|
--os linux --arch arm --variant=v6
|
||||||
|
|
||||||
|
docker manifest annotate "${registry}/home-assistant:${tag_l}" \
|
||||||
|
"${registry}/armv7-homeassistant:${tag_r}" \
|
||||||
|
--os linux --arch arm --variant=v7
|
||||||
|
|
||||||
|
docker manifest annotate "${registry}/home-assistant:${tag_l}" \
|
||||||
|
"${registry}/aarch64-homeassistant:${tag_r}" \
|
||||||
|
--os linux --arch arm64 --variant=v8
|
||||||
|
|
||||||
|
docker manifest push --purge "${registry}/home-assistant:${tag_l}"
|
||||||
|
cosign sign --yes "${registry}/home-assistant:${tag_l}"
|
||||||
|
}
|
||||||
|
|
||||||
|
function validate_image() {
|
||||||
|
local image=${1}
|
||||||
|
if ! cosign verify --certificate-oidc-issuer https://token.actions.githubusercontent.com --certificate-identity-regexp https://github.com/home-assistant/core/.* "${image}"; then
|
||||||
|
echo "Invalid signature!"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
function push_dockerhub() {
|
||||||
|
local image=${1}
|
||||||
|
local tag=${2}
|
||||||
|
|
||||||
|
docker tag "ghcr.io/home-assistant/${image}:${tag}" "docker.io/homeassistant/${image}:${tag}"
|
||||||
|
docker push "docker.io/homeassistant/${image}:${tag}"
|
||||||
|
cosign sign --yes "docker.io/homeassistant/${image}:${tag}"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Pull images from github container registry and verify signature
|
||||||
|
docker pull "ghcr.io/home-assistant/amd64-homeassistant:${{ needs.init.outputs.version }}"
|
||||||
|
docker pull "ghcr.io/home-assistant/i386-homeassistant:${{ needs.init.outputs.version }}"
|
||||||
|
docker pull "ghcr.io/home-assistant/armhf-homeassistant:${{ needs.init.outputs.version }}"
|
||||||
|
docker pull "ghcr.io/home-assistant/armv7-homeassistant:${{ needs.init.outputs.version }}"
|
||||||
|
docker pull "ghcr.io/home-assistant/aarch64-homeassistant:${{ needs.init.outputs.version }}"
|
||||||
|
|
||||||
|
validate_image "ghcr.io/home-assistant/amd64-homeassistant:${{ needs.init.outputs.version }}"
|
||||||
|
validate_image "ghcr.io/home-assistant/i386-homeassistant:${{ needs.init.outputs.version }}"
|
||||||
|
validate_image "ghcr.io/home-assistant/armhf-homeassistant:${{ needs.init.outputs.version }}"
|
||||||
|
validate_image "ghcr.io/home-assistant/armv7-homeassistant:${{ needs.init.outputs.version }}"
|
||||||
|
validate_image "ghcr.io/home-assistant/aarch64-homeassistant:${{ needs.init.outputs.version }}"
|
||||||
|
|
||||||
|
if [[ "${{ matrix.registry }}" == "docker.io/homeassistant" ]]; then
|
||||||
|
# Upload images to dockerhub
|
||||||
|
push_dockerhub "amd64-homeassistant" "${{ needs.init.outputs.version }}"
|
||||||
|
push_dockerhub "i386-homeassistant" "${{ needs.init.outputs.version }}"
|
||||||
|
push_dockerhub "armhf-homeassistant" "${{ needs.init.outputs.version }}"
|
||||||
|
push_dockerhub "armv7-homeassistant" "${{ needs.init.outputs.version }}"
|
||||||
|
push_dockerhub "aarch64-homeassistant" "${{ needs.init.outputs.version }}"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Create version tag
|
||||||
|
create_manifest "${{ needs.init.outputs.version }}" "${{ needs.init.outputs.version }}"
|
||||||
|
|
||||||
|
# Create general tags
|
||||||
|
if [[ "${{ needs.init.outputs.version }}" =~ d ]]; then
|
||||||
|
create_manifest "dev" "${{ needs.init.outputs.version }}"
|
||||||
|
elif [[ "${{ needs.init.outputs.version }}" =~ b ]]; then
|
||||||
|
create_manifest "beta" "${{ needs.init.outputs.version }}"
|
||||||
|
create_manifest "rc" "${{ needs.init.outputs.version }}"
|
||||||
|
else
|
||||||
|
create_manifest "stable" "${{ needs.init.outputs.version }}"
|
||||||
|
create_manifest "latest" "${{ needs.init.outputs.version }}"
|
||||||
|
create_manifest "beta" "${{ needs.init.outputs.version }}"
|
||||||
|
create_manifest "rc" "${{ needs.init.outputs.version }}"
|
||||||
|
|
||||||
|
# Create series version tag (e.g. 2021.6)
|
||||||
|
v="${{ needs.init.outputs.version }}"
|
||||||
|
create_manifest "${v%.*}" "${{ needs.init.outputs.version }}"
|
||||||
|
fi
|
||||||
|
|
||||||
|
build_python:
|
||||||
|
name: Build PyPi package
|
||||||
|
environment: ${{ needs.init.outputs.channel }}
|
||||||
|
needs: ["init", "build_base"]
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
if: github.repository_owner == 'home-assistant' && needs.init.outputs.publish == 'true'
|
||||||
|
steps:
|
||||||
|
- name: Checkout the repository
|
||||||
|
uses: actions/checkout@v4.2.2
|
||||||
|
|
||||||
|
- name: Set up Python ${{ env.DEFAULT_PYTHON }}
|
||||||
|
uses: actions/setup-python@v5.3.0
|
||||||
|
with:
|
||||||
|
python-version: ${{ env.DEFAULT_PYTHON }}
|
||||||
|
|
||||||
|
- name: Download translations
|
||||||
|
uses: actions/download-artifact@v4.1.8
|
||||||
|
with:
|
||||||
|
name: translations
|
||||||
|
|
||||||
|
- name: Extract translations
|
||||||
|
run: |
|
||||||
|
tar xvf translations.tar.gz
|
||||||
|
rm translations.tar.gz
|
||||||
|
|
||||||
|
- name: Build package
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
# Remove dist, build, and homeassistant.egg-info
|
||||||
|
# when build locally for testing!
|
||||||
|
pip install twine build
|
||||||
|
python -m build
|
||||||
|
|
||||||
|
- name: Upload package
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
export TWINE_USERNAME="__token__"
|
||||||
|
export TWINE_PASSWORD="${{ secrets.TWINE_TOKEN }}"
|
||||||
|
|
||||||
|
twine upload dist/* --skip-existing
|
||||||
|
|
||||||
|
hassfest-image:
|
||||||
|
name: Build and test hassfest image
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
packages: write
|
||||||
|
attestations: write
|
||||||
|
id-token: write
|
||||||
|
needs: ["init"]
|
||||||
|
if: github.repository_owner == 'home-assistant'
|
||||||
|
env:
|
||||||
|
HASSFEST_IMAGE_NAME: ghcr.io/home-assistant/hassfest
|
||||||
|
HASSFEST_IMAGE_TAG: ghcr.io/home-assistant/hassfest:${{ needs.init.outputs.version }}
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||||
|
|
||||||
|
- name: Login to GitHub Container Registry
|
||||||
|
uses: docker/login-action@9780b0c442fbb1117ed29e0efdff1e18412f7567 # v3.3.0
|
||||||
|
with:
|
||||||
|
registry: ghcr.io
|
||||||
|
username: ${{ github.repository_owner }}
|
||||||
|
password: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
- name: Build Docker image
|
||||||
|
uses: docker/build-push-action@48aba3b46d1b1fec4febb7c5d0c644b249a11355 # v6.10.0
|
||||||
|
with:
|
||||||
|
context: . # So action will not pull the repository again
|
||||||
|
file: ./script/hassfest/docker/Dockerfile
|
||||||
|
load: true
|
||||||
|
tags: ${{ env.HASSFEST_IMAGE_TAG }}
|
||||||
|
|
||||||
|
- name: Run hassfest against core
|
||||||
|
run: docker run --rm -v ${{ github.workspace }}:/github/workspace ${{ env.HASSFEST_IMAGE_TAG }} --core-path=/github/workspace
|
||||||
|
|
||||||
|
- name: Push Docker image
|
||||||
|
if: needs.init.outputs.channel != 'dev' && needs.init.outputs.publish == 'true'
|
||||||
|
id: push
|
||||||
|
uses: docker/build-push-action@48aba3b46d1b1fec4febb7c5d0c644b249a11355 # v6.10.0
|
||||||
|
with:
|
||||||
|
context: . # So action will not pull the repository again
|
||||||
|
file: ./script/hassfest/docker/Dockerfile
|
||||||
|
push: true
|
||||||
|
tags: ${{ env.HASSFEST_IMAGE_TAG }},${{ env.HASSFEST_IMAGE_NAME }}:latest
|
||||||
|
|
||||||
|
- name: Generate artifact attestation
|
||||||
|
if: needs.init.outputs.channel != 'dev' && needs.init.outputs.publish == 'true'
|
||||||
|
uses: actions/attest-build-provenance@7668571508540a607bdfd90a87a560489fe372eb # v2.1.0
|
||||||
|
with:
|
||||||
|
subject-name: ${{ env.HASSFEST_IMAGE_NAME }}
|
||||||
|
subject-digest: ${{ steps.push.outputs.digest }}
|
||||||
|
push-to-registry: true
|
||||||
1417
home-assistant/.github/workflows/ci.yaml
vendored
Normal file
1417
home-assistant/.github/workflows/ci.yaml
vendored
Normal file
File diff suppressed because it is too large
Load Diff
34
home-assistant/.github/workflows/codeql.yml
vendored
Normal file
34
home-assistant/.github/workflows/codeql.yml
vendored
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
name: "CodeQL"
|
||||||
|
|
||||||
|
# yamllint disable-line rule:truthy
|
||||||
|
on:
|
||||||
|
schedule:
|
||||||
|
- cron: "30 18 * * 4"
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: ${{ github.workflow }}-${{ github.ref }}
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
analyze:
|
||||||
|
name: Analyze
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 360
|
||||||
|
permissions:
|
||||||
|
actions: read
|
||||||
|
contents: read
|
||||||
|
security-events: write
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Check out code from GitHub
|
||||||
|
uses: actions/checkout@v4.2.2
|
||||||
|
|
||||||
|
- name: Initialize CodeQL
|
||||||
|
uses: github/codeql-action/init@v3.28.0
|
||||||
|
with:
|
||||||
|
languages: python
|
||||||
|
|
||||||
|
- name: Perform CodeQL Analysis
|
||||||
|
uses: github/codeql-action/analyze@v3.28.0
|
||||||
|
with:
|
||||||
|
category: "/language:python"
|
||||||
21
home-assistant/.github/workflows/lock.yml
vendored
Normal file
21
home-assistant/.github/workflows/lock.yml
vendored
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
name: Lock
|
||||||
|
|
||||||
|
# yamllint disable-line rule:truthy
|
||||||
|
on:
|
||||||
|
schedule:
|
||||||
|
- cron: "0 * * * *"
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
lock:
|
||||||
|
if: github.repository_owner == 'home-assistant'
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: dessant/lock-threads@v5.0.1
|
||||||
|
with:
|
||||||
|
github-token: ${{ github.token }}
|
||||||
|
issue-inactive-days: "30"
|
||||||
|
exclude-issue-created-before: "2020-10-01T00:00:00Z"
|
||||||
|
issue-lock-reason: ""
|
||||||
|
pr-inactive-days: "1"
|
||||||
|
exclude-pr-created-before: "2020-11-01T00:00:00Z"
|
||||||
|
pr-lock-reason: ""
|
||||||
14
home-assistant/.github/workflows/matchers/check-executables-have-shebangs.json
vendored
Normal file
14
home-assistant/.github/workflows/matchers/check-executables-have-shebangs.json
vendored
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
{
|
||||||
|
"problemMatcher": [
|
||||||
|
{
|
||||||
|
"owner": "check-executables-have-shebangs",
|
||||||
|
"pattern": [
|
||||||
|
{
|
||||||
|
"regexp": "^(.+):\\s(.+)$",
|
||||||
|
"file": 1,
|
||||||
|
"message": 2
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
16
home-assistant/.github/workflows/matchers/check-json.json
vendored
Normal file
16
home-assistant/.github/workflows/matchers/check-json.json
vendored
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
{
|
||||||
|
"problemMatcher": [
|
||||||
|
{
|
||||||
|
"owner": "check-json",
|
||||||
|
"pattern": [
|
||||||
|
{
|
||||||
|
"regexp": "^(.+):\\s(.+\\sline\\s(\\d+)\\scolumn\\s(\\d+).+)$",
|
||||||
|
"file": 1,
|
||||||
|
"message": 2,
|
||||||
|
"line": 3,
|
||||||
|
"column": 4
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
16
home-assistant/.github/workflows/matchers/codespell.json
vendored
Normal file
16
home-assistant/.github/workflows/matchers/codespell.json
vendored
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
{
|
||||||
|
"problemMatcher": [
|
||||||
|
{
|
||||||
|
"owner": "codespell",
|
||||||
|
"severity": "warning",
|
||||||
|
"pattern": [
|
||||||
|
{
|
||||||
|
"regexp": "^(.+):(\\d+):\\s(.+)$",
|
||||||
|
"file": 1,
|
||||||
|
"line": 2,
|
||||||
|
"message": 3
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
16
home-assistant/.github/workflows/matchers/hadolint.json
vendored
Normal file
16
home-assistant/.github/workflows/matchers/hadolint.json
vendored
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
{
|
||||||
|
"problemMatcher": [
|
||||||
|
{
|
||||||
|
"owner": "hadolint",
|
||||||
|
"pattern": [
|
||||||
|
{
|
||||||
|
"regexp": "^(.+):(\\d+)\\s+((DL\\d{4}).+)$",
|
||||||
|
"file": 1,
|
||||||
|
"line": 2,
|
||||||
|
"message": 3,
|
||||||
|
"code": 4
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
16
home-assistant/.github/workflows/matchers/mypy.json
vendored
Normal file
16
home-assistant/.github/workflows/matchers/mypy.json
vendored
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
{
|
||||||
|
"problemMatcher": [
|
||||||
|
{
|
||||||
|
"owner": "mypy",
|
||||||
|
"pattern": [
|
||||||
|
{
|
||||||
|
"regexp": "^(.+):(\\d+):\\s(error|warning):\\s(.+)$",
|
||||||
|
"file": 1,
|
||||||
|
"line": 2,
|
||||||
|
"severity": 3,
|
||||||
|
"message": 4
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
32
home-assistant/.github/workflows/matchers/pylint.json
vendored
Normal file
32
home-assistant/.github/workflows/matchers/pylint.json
vendored
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
{
|
||||||
|
"problemMatcher": [
|
||||||
|
{
|
||||||
|
"owner": "pylint-error",
|
||||||
|
"severity": "error",
|
||||||
|
"pattern": [
|
||||||
|
{
|
||||||
|
"regexp": "^(.+):(\\d+):(\\d+):\\s(([EF]\\d{4}):\\s.+)$",
|
||||||
|
"file": 1,
|
||||||
|
"line": 2,
|
||||||
|
"column": 3,
|
||||||
|
"message": 4,
|
||||||
|
"code": 5
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"owner": "pylint-warning",
|
||||||
|
"severity": "warning",
|
||||||
|
"pattern": [
|
||||||
|
{
|
||||||
|
"regexp": "^(.+):(\\d+):(\\d+):\\s(([CRW]\\d{4}):\\s.+)$",
|
||||||
|
"file": 1,
|
||||||
|
"line": 2,
|
||||||
|
"column": 3,
|
||||||
|
"message": 4,
|
||||||
|
"code": 5
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
18
home-assistant/.github/workflows/matchers/pytest-slow.json
vendored
Normal file
18
home-assistant/.github/workflows/matchers/pytest-slow.json
vendored
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
{
|
||||||
|
"problemMatcher": [
|
||||||
|
{
|
||||||
|
"owner": "python",
|
||||||
|
"pattern": [
|
||||||
|
{
|
||||||
|
"regexp": "^=+ slowest durations =+$"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"regexp": "^((.*s)\\s(call|setup|teardown)\\s+(.*)::(.*))$",
|
||||||
|
"message": 1,
|
||||||
|
"file": 2,
|
||||||
|
"loop": true
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
18
home-assistant/.github/workflows/matchers/python.json
vendored
Normal file
18
home-assistant/.github/workflows/matchers/python.json
vendored
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
{
|
||||||
|
"problemMatcher": [
|
||||||
|
{
|
||||||
|
"owner": "python",
|
||||||
|
"pattern": [
|
||||||
|
{
|
||||||
|
"regexp": "^\\s*File\\s\\\"(.*)\\\",\\sline\\s(\\d+),\\sin\\s(.*)$",
|
||||||
|
"file": 1,
|
||||||
|
"line": 2
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"regexp": "^\\s*raise\\s(.*)\\(\\'(.*)\\'\\)$",
|
||||||
|
"message": 2
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
22
home-assistant/.github/workflows/matchers/yamllint.json
vendored
Normal file
22
home-assistant/.github/workflows/matchers/yamllint.json
vendored
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
{
|
||||||
|
"problemMatcher": [
|
||||||
|
{
|
||||||
|
"owner": "yamllint",
|
||||||
|
"pattern": [
|
||||||
|
{
|
||||||
|
"regexp": "^(.*\\.ya?ml)$",
|
||||||
|
"file": 1
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"regexp": "^\\s{2}(\\d+):(\\d+)\\s+(error|warning)\\s+(.*?)\\s+\\((.*)\\)$",
|
||||||
|
"line": 1,
|
||||||
|
"column": 2,
|
||||||
|
"severity": 3,
|
||||||
|
"message": 4,
|
||||||
|
"code": 5,
|
||||||
|
"loop": true
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
113
home-assistant/.github/workflows/stale.yml
vendored
Normal file
113
home-assistant/.github/workflows/stale.yml
vendored
Normal file
@@ -0,0 +1,113 @@
|
|||||||
|
name: Stale
|
||||||
|
|
||||||
|
# yamllint disable-line rule:truthy
|
||||||
|
on:
|
||||||
|
schedule:
|
||||||
|
- cron: "0 * * * *"
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
stale:
|
||||||
|
if: github.repository_owner == 'home-assistant'
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
# The 60 day stale policy for PRs
|
||||||
|
# Used for:
|
||||||
|
# - PRs
|
||||||
|
# - No PRs marked as no-stale
|
||||||
|
# - No issues (-1)
|
||||||
|
- name: 60 days stale PRs policy
|
||||||
|
uses: actions/stale@v9.0.0
|
||||||
|
with:
|
||||||
|
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
days-before-stale: 60
|
||||||
|
days-before-close: 7
|
||||||
|
days-before-issue-stale: -1
|
||||||
|
days-before-issue-close: -1
|
||||||
|
operations-per-run: 150
|
||||||
|
remove-stale-when-updated: true
|
||||||
|
stale-pr-label: "stale"
|
||||||
|
exempt-pr-labels: "no-stale"
|
||||||
|
stale-pr-message: >
|
||||||
|
There hasn't been any activity on this pull request recently. This
|
||||||
|
pull request has been automatically marked as stale because of that
|
||||||
|
and will be closed if no further activity occurs within 7 days.
|
||||||
|
|
||||||
|
If you are the author of this PR, please leave a comment if you want
|
||||||
|
to keep it open. Also, please rebase your PR onto the latest dev
|
||||||
|
branch to ensure that it's up to date with the latest changes.
|
||||||
|
|
||||||
|
Thank you for your contribution!
|
||||||
|
|
||||||
|
# Generate a token for the GitHub App, we use this method to avoid
|
||||||
|
# hitting API limits for our GitHub actions + have a higher rate limit.
|
||||||
|
# This is only used for issues.
|
||||||
|
- name: Generate app token
|
||||||
|
id: token
|
||||||
|
# Pinned to a specific version of the action for security reasons
|
||||||
|
# v1.7.0
|
||||||
|
uses: tibdex/github-app-token@3beb63f4bd073e61482598c45c71c1019b59b73a
|
||||||
|
with:
|
||||||
|
app_id: ${{ secrets.ISSUE_TRIAGE_APP_ID }}
|
||||||
|
private_key: ${{ secrets.ISSUE_TRIAGE_APP_PEM }}
|
||||||
|
|
||||||
|
# The 90 day stale policy for issues
|
||||||
|
# Used for:
|
||||||
|
# - Issues
|
||||||
|
# - No issues marked as no-stale or help-wanted
|
||||||
|
# - No PRs (-1)
|
||||||
|
- name: 90 days stale issues
|
||||||
|
uses: actions/stale@v9.0.0
|
||||||
|
with:
|
||||||
|
repo-token: ${{ steps.token.outputs.token }}
|
||||||
|
days-before-stale: 90
|
||||||
|
days-before-close: 7
|
||||||
|
days-before-pr-stale: -1
|
||||||
|
days-before-pr-close: -1
|
||||||
|
operations-per-run: 250
|
||||||
|
remove-stale-when-updated: true
|
||||||
|
stale-issue-label: "stale"
|
||||||
|
exempt-issue-labels: "no-stale,help-wanted,needs-more-information"
|
||||||
|
stale-issue-message: >
|
||||||
|
There hasn't been any activity on this issue recently. Due to the
|
||||||
|
high number of incoming GitHub notifications, we have to clean some
|
||||||
|
of the old issues, as many of them have already been resolved with
|
||||||
|
the latest updates.
|
||||||
|
|
||||||
|
Please make sure to update to the latest Home Assistant version and
|
||||||
|
check if that solves the issue. Let us know if that works for you by
|
||||||
|
adding a comment 👍
|
||||||
|
|
||||||
|
This issue has now been marked as stale and will be closed if no
|
||||||
|
further activity occurs. Thank you for your contributions.
|
||||||
|
|
||||||
|
# The 30 day stale policy for issues
|
||||||
|
# Used for:
|
||||||
|
# - Issues that are pending more information (incomplete issues)
|
||||||
|
# - No Issues marked as no-stale or help-wanted
|
||||||
|
# - No PRs (-1)
|
||||||
|
- name: Needs more information stale issues policy
|
||||||
|
uses: actions/stale@v9.0.0
|
||||||
|
with:
|
||||||
|
repo-token: ${{ steps.token.outputs.token }}
|
||||||
|
only-labels: "needs-more-information"
|
||||||
|
days-before-stale: 14
|
||||||
|
days-before-close: 7
|
||||||
|
days-before-pr-stale: -1
|
||||||
|
days-before-pr-close: -1
|
||||||
|
operations-per-run: 250
|
||||||
|
remove-stale-when-updated: true
|
||||||
|
stale-issue-label: "stale"
|
||||||
|
exempt-issue-labels: "no-stale,help-wanted"
|
||||||
|
stale-issue-message: >
|
||||||
|
There hasn't been any activity on this issue recently. Due to the
|
||||||
|
high number of incoming GitHub notifications, we have to clean some
|
||||||
|
of the old issues, as many of them have already been resolved with
|
||||||
|
the latest updates.
|
||||||
|
|
||||||
|
Please make sure to update to the latest Home Assistant version and
|
||||||
|
check if that solves the issue. Let us know if that works for you by
|
||||||
|
adding a comment 👍
|
||||||
|
|
||||||
|
This issue has now been marked as stale and will be closed if no
|
||||||
|
further activity occurs. Thank you for your contributions.
|
||||||
32
home-assistant/.github/workflows/translations.yml
vendored
Normal file
32
home-assistant/.github/workflows/translations.yml
vendored
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
name: Translations
|
||||||
|
|
||||||
|
# yamllint disable-line rule:truthy
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- dev
|
||||||
|
paths:
|
||||||
|
- "**strings.json"
|
||||||
|
|
||||||
|
env:
|
||||||
|
DEFAULT_PYTHON: "3.12"
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
upload:
|
||||||
|
name: Upload
|
||||||
|
if: github.repository_owner == 'home-assistant'
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout the repository
|
||||||
|
uses: actions/checkout@v4.2.2
|
||||||
|
|
||||||
|
- name: Set up Python ${{ env.DEFAULT_PYTHON }}
|
||||||
|
uses: actions/setup-python@v5.3.0
|
||||||
|
with:
|
||||||
|
python-version: ${{ env.DEFAULT_PYTHON }}
|
||||||
|
|
||||||
|
- name: Upload Translations
|
||||||
|
run: |
|
||||||
|
export LOKALISE_TOKEN="${{ secrets.LOKALISE_TOKEN }}"
|
||||||
|
python3 -m script.translations upload
|
||||||
240
home-assistant/.github/workflows/wheels.yml
vendored
Normal file
240
home-assistant/.github/workflows/wheels.yml
vendored
Normal file
@@ -0,0 +1,240 @@
|
|||||||
|
name: Build wheels
|
||||||
|
|
||||||
|
# yamllint disable-line rule:truthy
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
schedule:
|
||||||
|
- cron: "0 4 * * *"
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- dev
|
||||||
|
- rc
|
||||||
|
paths:
|
||||||
|
- ".github/workflows/wheels.yml"
|
||||||
|
- "homeassistant/package_constraints.txt"
|
||||||
|
- "requirements_all.txt"
|
||||||
|
- "requirements.txt"
|
||||||
|
- "script/gen_requirements_all.py"
|
||||||
|
|
||||||
|
env:
|
||||||
|
DEFAULT_PYTHON: "3.12"
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: ${{ github.workflow }}-${{ github.ref_name}}
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
init:
|
||||||
|
name: Initialize wheels builder
|
||||||
|
if: github.repository_owner == 'home-assistant'
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
outputs:
|
||||||
|
architectures: ${{ steps.info.outputs.architectures }}
|
||||||
|
steps:
|
||||||
|
- name: Checkout the repository
|
||||||
|
uses: actions/checkout@v4.2.2
|
||||||
|
|
||||||
|
- name: Set up Python ${{ env.DEFAULT_PYTHON }}
|
||||||
|
id: python
|
||||||
|
uses: actions/setup-python@v5.3.0
|
||||||
|
with:
|
||||||
|
python-version: ${{ env.DEFAULT_PYTHON }}
|
||||||
|
check-latest: true
|
||||||
|
|
||||||
|
- name: Create Python virtual environment
|
||||||
|
run: |
|
||||||
|
python -m venv venv
|
||||||
|
. venv/bin/activate
|
||||||
|
python --version
|
||||||
|
pip install "$(grep '^uv' < requirements.txt)"
|
||||||
|
uv pip install -r requirements.txt
|
||||||
|
|
||||||
|
- name: Get information
|
||||||
|
id: info
|
||||||
|
uses: home-assistant/actions/helpers/info@master
|
||||||
|
|
||||||
|
- name: Create requirements_diff file
|
||||||
|
run: |
|
||||||
|
if [[ ${{ github.event_name }} =~ (schedule|workflow_dispatch) ]]; then
|
||||||
|
touch requirements_diff.txt
|
||||||
|
else
|
||||||
|
curl -s -o requirements_diff.txt https://raw.githubusercontent.com/home-assistant/core/master/requirements.txt
|
||||||
|
fi
|
||||||
|
|
||||||
|
- name: Write env-file
|
||||||
|
run: |
|
||||||
|
(
|
||||||
|
echo "GRPC_PYTHON_BUILD_SYSTEM_OPENSSL=true"
|
||||||
|
echo "GRPC_PYTHON_BUILD_WITH_CYTHON=true"
|
||||||
|
|
||||||
|
# Fix out of memory issues with rust
|
||||||
|
echo "CARGO_NET_GIT_FETCH_WITH_CLI=true"
|
||||||
|
|
||||||
|
# OpenCV headless installation
|
||||||
|
echo "CI_BUILD=1"
|
||||||
|
echo "ENABLE_HEADLESS=1"
|
||||||
|
|
||||||
|
# Use C-Extension for SQLAlchemy
|
||||||
|
echo "REQUIRE_SQLALCHEMY_CEXT=1"
|
||||||
|
) > .env_file
|
||||||
|
|
||||||
|
- name: Upload env_file
|
||||||
|
uses: actions/upload-artifact@v4.5.0
|
||||||
|
with:
|
||||||
|
name: env_file
|
||||||
|
path: ./.env_file
|
||||||
|
include-hidden-files: true
|
||||||
|
overwrite: true
|
||||||
|
|
||||||
|
- name: Upload requirements_diff
|
||||||
|
uses: actions/upload-artifact@v4.5.0
|
||||||
|
with:
|
||||||
|
name: requirements_diff
|
||||||
|
path: ./requirements_diff.txt
|
||||||
|
overwrite: true
|
||||||
|
|
||||||
|
- name: Generate requirements
|
||||||
|
run: |
|
||||||
|
. venv/bin/activate
|
||||||
|
python -m script.gen_requirements_all ci
|
||||||
|
|
||||||
|
- name: Upload requirements_all_wheels
|
||||||
|
uses: actions/upload-artifact@v4.5.0
|
||||||
|
with:
|
||||||
|
name: requirements_all_wheels
|
||||||
|
path: ./requirements_all_wheels_*.txt
|
||||||
|
|
||||||
|
core:
|
||||||
|
name: Build Core wheels ${{ matrix.abi }} for ${{ matrix.arch }} (musllinux_1_2)
|
||||||
|
if: github.repository_owner == 'home-assistant'
|
||||||
|
needs: init
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
abi: ["cp312", "cp313"]
|
||||||
|
arch: ${{ fromJson(needs.init.outputs.architectures) }}
|
||||||
|
steps:
|
||||||
|
- name: Checkout the repository
|
||||||
|
uses: actions/checkout@v4.2.2
|
||||||
|
|
||||||
|
- name: Download env_file
|
||||||
|
uses: actions/download-artifact@v4.1.8
|
||||||
|
with:
|
||||||
|
name: env_file
|
||||||
|
|
||||||
|
- name: Download requirements_diff
|
||||||
|
uses: actions/download-artifact@v4.1.8
|
||||||
|
with:
|
||||||
|
name: requirements_diff
|
||||||
|
|
||||||
|
- name: Adjust build env
|
||||||
|
run: |
|
||||||
|
# Don't build wheels for uv as uv requires a greater version of rust as currently available on alpine
|
||||||
|
sed -i "/uv/d" requirements.txt
|
||||||
|
sed -i "/uv/d" requirements_diff.txt
|
||||||
|
|
||||||
|
- name: Build wheels
|
||||||
|
uses: home-assistant/wheels@2024.11.0
|
||||||
|
with:
|
||||||
|
abi: ${{ matrix.abi }}
|
||||||
|
tag: musllinux_1_2
|
||||||
|
arch: ${{ matrix.arch }}
|
||||||
|
wheels-key: ${{ secrets.WHEELS_KEY }}
|
||||||
|
env-file: true
|
||||||
|
apk: "libffi-dev;openssl-dev;yaml-dev;nasm;zlib-dev"
|
||||||
|
skip-binary: aiohttp;multidict;propcache;yarl;SQLAlchemy
|
||||||
|
constraints: "homeassistant/package_constraints.txt"
|
||||||
|
requirements-diff: "requirements_diff.txt"
|
||||||
|
requirements: "requirements.txt"
|
||||||
|
|
||||||
|
integrations:
|
||||||
|
name: Build wheels ${{ matrix.abi }} for ${{ matrix.arch }}
|
||||||
|
if: github.repository_owner == 'home-assistant'
|
||||||
|
needs: init
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
abi: ["cp312", "cp313"]
|
||||||
|
arch: ${{ fromJson(needs.init.outputs.architectures) }}
|
||||||
|
steps:
|
||||||
|
- name: Checkout the repository
|
||||||
|
uses: actions/checkout@v4.2.2
|
||||||
|
|
||||||
|
- name: Download env_file
|
||||||
|
uses: actions/download-artifact@v4.1.8
|
||||||
|
with:
|
||||||
|
name: env_file
|
||||||
|
|
||||||
|
- name: Download requirements_diff
|
||||||
|
uses: actions/download-artifact@v4.1.8
|
||||||
|
with:
|
||||||
|
name: requirements_diff
|
||||||
|
|
||||||
|
- name: Download requirements_all_wheels
|
||||||
|
uses: actions/download-artifact@v4.1.8
|
||||||
|
with:
|
||||||
|
name: requirements_all_wheels
|
||||||
|
|
||||||
|
- name: Adjust build env
|
||||||
|
run: |
|
||||||
|
if [ "${{ matrix.arch }}" = "i386" ]; then
|
||||||
|
echo "NPY_DISABLE_SVML=1" >> .env_file
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Do not pin numpy in wheels building
|
||||||
|
sed -i "/numpy/d" homeassistant/package_constraints.txt
|
||||||
|
# Don't build wheels for uv as uv requires a greater version of rust as currently available on alpine
|
||||||
|
sed -i "/uv/d" requirements.txt
|
||||||
|
sed -i "/uv/d" requirements_diff.txt
|
||||||
|
|
||||||
|
- name: Split requirements all
|
||||||
|
run: |
|
||||||
|
# We split requirements all into multiple files.
|
||||||
|
# This is to prevent the build from running out of memory when
|
||||||
|
# resolving packages on 32-bits systems (like armhf, armv7).
|
||||||
|
|
||||||
|
split -l $(expr $(expr $(cat requirements_all.txt | wc -l) + 1) / 3) requirements_all_wheels_${{ matrix.arch }}.txt requirements_all.txt
|
||||||
|
|
||||||
|
- name: Build wheels (part 1)
|
||||||
|
uses: home-assistant/wheels@2024.11.0
|
||||||
|
with:
|
||||||
|
abi: ${{ matrix.abi }}
|
||||||
|
tag: musllinux_1_2
|
||||||
|
arch: ${{ matrix.arch }}
|
||||||
|
wheels-key: ${{ secrets.WHEELS_KEY }}
|
||||||
|
env-file: true
|
||||||
|
apk: "bluez-dev;libffi-dev;openssl-dev;glib-dev;eudev-dev;libxml2-dev;libxslt-dev;libpng-dev;libjpeg-turbo-dev;tiff-dev;cups-dev;gmp-dev;mpfr-dev;mpc1-dev;ffmpeg-dev;gammu-dev;yaml-dev;openblas-dev;fftw-dev;lapack-dev;gfortran;blas-dev;eigen-dev;freetype-dev;glew-dev;harfbuzz-dev;hdf5-dev;libdc1394-dev;libtbb-dev;mesa-dev;openexr-dev;openjpeg-dev;uchardet-dev;nasm;zlib-dev"
|
||||||
|
skip-binary: aiohttp;charset-normalizer;grpcio;multidict;SQLAlchemy;propcache;protobuf;pymicro-vad;yarl
|
||||||
|
constraints: "homeassistant/package_constraints.txt"
|
||||||
|
requirements-diff: "requirements_diff.txt"
|
||||||
|
requirements: "requirements_all.txtaa"
|
||||||
|
|
||||||
|
- name: Build wheels (part 2)
|
||||||
|
uses: home-assistant/wheels@2024.11.0
|
||||||
|
with:
|
||||||
|
abi: ${{ matrix.abi }}
|
||||||
|
tag: musllinux_1_2
|
||||||
|
arch: ${{ matrix.arch }}
|
||||||
|
wheels-key: ${{ secrets.WHEELS_KEY }}
|
||||||
|
env-file: true
|
||||||
|
apk: "bluez-dev;libffi-dev;openssl-dev;glib-dev;eudev-dev;libxml2-dev;libxslt-dev;libpng-dev;libjpeg-turbo-dev;tiff-dev;cups-dev;gmp-dev;mpfr-dev;mpc1-dev;ffmpeg-dev;gammu-dev;yaml-dev;openblas-dev;fftw-dev;lapack-dev;gfortran;blas-dev;eigen-dev;freetype-dev;glew-dev;harfbuzz-dev;hdf5-dev;libdc1394-dev;libtbb-dev;mesa-dev;openexr-dev;openjpeg-dev;uchardet-dev;nasm;zlib-dev"
|
||||||
|
skip-binary: aiohttp;charset-normalizer;grpcio;multidict;SQLAlchemy;propcache;protobuf;pymicro-vad;yarl
|
||||||
|
constraints: "homeassistant/package_constraints.txt"
|
||||||
|
requirements-diff: "requirements_diff.txt"
|
||||||
|
requirements: "requirements_all.txtab"
|
||||||
|
|
||||||
|
- name: Build wheels (part 3)
|
||||||
|
uses: home-assistant/wheels@2024.11.0
|
||||||
|
with:
|
||||||
|
abi: ${{ matrix.abi }}
|
||||||
|
tag: musllinux_1_2
|
||||||
|
arch: ${{ matrix.arch }}
|
||||||
|
wheels-key: ${{ secrets.WHEELS_KEY }}
|
||||||
|
env-file: true
|
||||||
|
apk: "bluez-dev;libffi-dev;openssl-dev;glib-dev;eudev-dev;libxml2-dev;libxslt-dev;libpng-dev;libjpeg-turbo-dev;tiff-dev;cups-dev;gmp-dev;mpfr-dev;mpc1-dev;ffmpeg-dev;gammu-dev;yaml-dev;openblas-dev;fftw-dev;lapack-dev;gfortran;blas-dev;eigen-dev;freetype-dev;glew-dev;harfbuzz-dev;hdf5-dev;libdc1394-dev;libtbb-dev;mesa-dev;openexr-dev;openjpeg-dev;uchardet-dev;nasm;zlib-dev"
|
||||||
|
skip-binary: aiohttp;charset-normalizer;grpcio;multidict;SQLAlchemy;propcache;protobuf;pymicro-vad;yarl
|
||||||
|
constraints: "homeassistant/package_constraints.txt"
|
||||||
|
requirements-diff: "requirements_diff.txt"
|
||||||
|
requirements: "requirements_all.txtac"
|
||||||
139
home-assistant/.gitignore
vendored
Normal file
139
home-assistant/.gitignore
vendored
Normal file
@@ -0,0 +1,139 @@
|
|||||||
|
/config
|
||||||
|
config2/*
|
||||||
|
|
||||||
|
tests/testing_config/deps
|
||||||
|
tests/testing_config/home-assistant.log*
|
||||||
|
|
||||||
|
# hass-release
|
||||||
|
data/
|
||||||
|
.token
|
||||||
|
|
||||||
|
# Translations
|
||||||
|
homeassistant/components/*/translations
|
||||||
|
|
||||||
|
# Hide sublime text stuff
|
||||||
|
*.sublime-project
|
||||||
|
*.sublime-workspace
|
||||||
|
|
||||||
|
# Hide some OS X stuff
|
||||||
|
.DS_Store
|
||||||
|
.AppleDouble
|
||||||
|
.LSOverride
|
||||||
|
Icon
|
||||||
|
|
||||||
|
# Thumbnails
|
||||||
|
._*
|
||||||
|
|
||||||
|
# IntelliJ IDEA
|
||||||
|
.idea
|
||||||
|
*.iml
|
||||||
|
|
||||||
|
# pytest
|
||||||
|
.pytest_cache
|
||||||
|
.cache
|
||||||
|
|
||||||
|
# GITHUB Proposed Python stuff:
|
||||||
|
*.py[cod]
|
||||||
|
__pycache__
|
||||||
|
|
||||||
|
# C extensions
|
||||||
|
*.so
|
||||||
|
|
||||||
|
# Packages
|
||||||
|
*.egg
|
||||||
|
*.egg-info
|
||||||
|
dist
|
||||||
|
build
|
||||||
|
eggs
|
||||||
|
.eggs
|
||||||
|
parts
|
||||||
|
bin
|
||||||
|
var
|
||||||
|
sdist
|
||||||
|
develop-eggs
|
||||||
|
.installed.cfg
|
||||||
|
lib
|
||||||
|
lib64
|
||||||
|
pip-wheel-metadata
|
||||||
|
|
||||||
|
# Logs
|
||||||
|
*.log
|
||||||
|
pip-log.txt
|
||||||
|
|
||||||
|
# Unit test / coverage reports
|
||||||
|
.coverage
|
||||||
|
coverage.xml
|
||||||
|
nosetests.xml
|
||||||
|
htmlcov/
|
||||||
|
test-reports/
|
||||||
|
test-results.xml
|
||||||
|
test-output.xml
|
||||||
|
pytest-*.txt
|
||||||
|
|
||||||
|
# Translations
|
||||||
|
*.mo
|
||||||
|
|
||||||
|
# Mr Developer
|
||||||
|
.mr.developer.cfg
|
||||||
|
.project
|
||||||
|
.pydevproject
|
||||||
|
|
||||||
|
.python-version
|
||||||
|
.tool-versions
|
||||||
|
|
||||||
|
# emacs auto backups
|
||||||
|
*~
|
||||||
|
*#
|
||||||
|
*.orig
|
||||||
|
|
||||||
|
# venv stuff
|
||||||
|
pyvenv.cfg
|
||||||
|
pip-selfcheck.json
|
||||||
|
venv
|
||||||
|
.venv
|
||||||
|
Pipfile*
|
||||||
|
share/*
|
||||||
|
/Scripts/
|
||||||
|
|
||||||
|
# vimmy stuff
|
||||||
|
*.swp
|
||||||
|
*.swo
|
||||||
|
tags
|
||||||
|
ctags.tmp
|
||||||
|
|
||||||
|
# vagrant stuff
|
||||||
|
virtualization/vagrant/setup_done
|
||||||
|
virtualization/vagrant/.vagrant
|
||||||
|
virtualization/vagrant/config
|
||||||
|
|
||||||
|
# Visual Studio Code
|
||||||
|
.vscode/*
|
||||||
|
!.vscode/cSpell.json
|
||||||
|
!.vscode/extensions.json
|
||||||
|
!.vscode/tasks.json
|
||||||
|
.env
|
||||||
|
|
||||||
|
# Windows Explorer
|
||||||
|
desktop.ini
|
||||||
|
/home-assistant.pyproj
|
||||||
|
/home-assistant.sln
|
||||||
|
/.vs/*
|
||||||
|
|
||||||
|
# mypy
|
||||||
|
/.mypy_cache/*
|
||||||
|
/.dmypy.json
|
||||||
|
|
||||||
|
# Secrets
|
||||||
|
.lokalise_token
|
||||||
|
|
||||||
|
# monkeytype
|
||||||
|
monkeytype.sqlite3
|
||||||
|
|
||||||
|
# This is left behind by Azure Restore Cache
|
||||||
|
tmp_cache
|
||||||
|
|
||||||
|
# python-language-server / Rope
|
||||||
|
.ropeproject
|
||||||
|
|
||||||
|
# Will be created from script/split_tests.py
|
||||||
|
pytest_buckets.txt
|
||||||
6
home-assistant/.hadolint.yaml
Normal file
6
home-assistant/.hadolint.yaml
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
ignored:
|
||||||
|
- DL3006
|
||||||
|
- DL3008
|
||||||
|
- DL3013
|
||||||
|
- DL3018
|
||||||
|
- DL3042
|
||||||
100
home-assistant/.pre-commit-config.yaml
Normal file
100
home-assistant/.pre-commit-config.yaml
Normal file
@@ -0,0 +1,100 @@
|
|||||||
|
repos:
|
||||||
|
- repo: https://github.com/astral-sh/ruff-pre-commit
|
||||||
|
rev: v0.8.3
|
||||||
|
hooks:
|
||||||
|
- id: ruff
|
||||||
|
args:
|
||||||
|
- --fix
|
||||||
|
- id: ruff-format
|
||||||
|
files: ^((homeassistant|pylint|script|tests)/.+)?[^/]+\.(py|pyi)$
|
||||||
|
- repo: https://github.com/codespell-project/codespell
|
||||||
|
rev: v2.3.0
|
||||||
|
hooks:
|
||||||
|
- id: codespell
|
||||||
|
args:
|
||||||
|
- --ignore-words-list=aiport,astroid,checkin,currenty,hass,iif,incomfort,lookin,nam,NotIn
|
||||||
|
- --skip="./.*,*.csv,*.json,*.ambr"
|
||||||
|
- --quiet-level=2
|
||||||
|
exclude_types: [csv, json, html]
|
||||||
|
exclude: ^tests/fixtures/|homeassistant/generated/|tests/components/.*/snapshots/
|
||||||
|
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||||
|
rev: v5.0.0
|
||||||
|
hooks:
|
||||||
|
- id: check-executables-have-shebangs
|
||||||
|
stages: [manual]
|
||||||
|
- id: check-json
|
||||||
|
exclude: (.vscode|.devcontainer)
|
||||||
|
- id: no-commit-to-branch
|
||||||
|
args:
|
||||||
|
- --branch=dev
|
||||||
|
- --branch=master
|
||||||
|
- --branch=rc
|
||||||
|
- repo: https://github.com/adrienverge/yamllint.git
|
||||||
|
rev: v1.35.1
|
||||||
|
hooks:
|
||||||
|
- id: yamllint
|
||||||
|
- repo: https://github.com/pre-commit/mirrors-prettier
|
||||||
|
rev: v3.0.3
|
||||||
|
hooks:
|
||||||
|
- id: prettier
|
||||||
|
- repo: https://github.com/cdce8p/python-typing-update
|
||||||
|
rev: v0.6.0
|
||||||
|
hooks:
|
||||||
|
# Run `python-typing-update` hook manually from time to time
|
||||||
|
# to update python typing syntax.
|
||||||
|
# Will require manual work, before submitting changes!
|
||||||
|
# pre-commit run --hook-stage manual python-typing-update --all-files
|
||||||
|
- id: python-typing-update
|
||||||
|
stages: [manual]
|
||||||
|
args:
|
||||||
|
- --py311-plus
|
||||||
|
- --force
|
||||||
|
- --keep-updates
|
||||||
|
files: ^(homeassistant|tests|script)/.+\.py$
|
||||||
|
- repo: local
|
||||||
|
hooks:
|
||||||
|
# Run mypy through our wrapper script in order to get the possible
|
||||||
|
# pyenv and/or virtualenv activated; it may not have been e.g. if
|
||||||
|
# committing from a GUI tool that was not launched from an activated
|
||||||
|
# shell.
|
||||||
|
- id: mypy
|
||||||
|
name: mypy
|
||||||
|
entry: script/run-in-env.sh mypy
|
||||||
|
language: script
|
||||||
|
types_or: [python, pyi]
|
||||||
|
require_serial: true
|
||||||
|
files: ^(homeassistant|pylint)/.+\.(py|pyi)$
|
||||||
|
- id: pylint
|
||||||
|
name: pylint
|
||||||
|
entry: script/run-in-env.sh pylint -j 0 --ignore-missing-annotations=y
|
||||||
|
language: script
|
||||||
|
types_or: [python, pyi]
|
||||||
|
files: ^(homeassistant|tests)/.+\.(py|pyi)$
|
||||||
|
- id: gen_requirements_all
|
||||||
|
name: gen_requirements_all
|
||||||
|
entry: script/run-in-env.sh python3 -m script.gen_requirements_all
|
||||||
|
pass_filenames: false
|
||||||
|
language: script
|
||||||
|
types: [text]
|
||||||
|
files: ^(homeassistant/.+/manifest\.json|homeassistant/brands/.+\.json|pyproject\.toml|\.pre-commit-config\.yaml|script/gen_requirements_all\.py)$
|
||||||
|
- id: hassfest
|
||||||
|
name: hassfest
|
||||||
|
entry: script/run-in-env.sh python3 -m script.hassfest
|
||||||
|
pass_filenames: false
|
||||||
|
language: script
|
||||||
|
types: [text]
|
||||||
|
files: ^(homeassistant/.+/(icons|manifest|strings)\.json|homeassistant/.+/(quality_scale)\.yaml|homeassistant/brands/.*\.json|homeassistant/.+/services\.yaml|script/hassfest/(?!metadata|mypy_config).+\.py|requirements.+\.txt)$
|
||||||
|
- id: hassfest-metadata
|
||||||
|
name: hassfest-metadata
|
||||||
|
entry: script/run-in-env.sh python3 -m script.hassfest -p metadata,docker
|
||||||
|
pass_filenames: false
|
||||||
|
language: script
|
||||||
|
types: [text]
|
||||||
|
files: ^(script/hassfest/metadata\.py|homeassistant/const\.py$|pyproject\.toml|homeassistant/components/go2rtc/const\.py)$
|
||||||
|
- id: hassfest-mypy-config
|
||||||
|
name: hassfest-mypy-config
|
||||||
|
entry: script/run-in-env.sh python3 -m script.hassfest -p mypy_config
|
||||||
|
pass_filenames: false
|
||||||
|
language: script
|
||||||
|
types: [text]
|
||||||
|
files: ^(script/hassfest/mypy_config\.py|\.strict-typing|mypy\.ini)$
|
||||||
7
home-assistant/.prettierignore
Normal file
7
home-assistant/.prettierignore
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
*.md
|
||||||
|
.strict-typing
|
||||||
|
homeassistant/components/*/translations/*.json
|
||||||
|
homeassistant/generated/*
|
||||||
|
tests/components/lidarr/fixtures/initialize.js
|
||||||
|
tests/components/lidarr/fixtures/initialize-wrong.js
|
||||||
|
tests/fixtures/core/config/yaml_errors/
|
||||||
535
home-assistant/.strict-typing
Normal file
535
home-assistant/.strict-typing
Normal file
@@ -0,0 +1,535 @@
|
|||||||
|
# Used by hassfest for generating mypy.ini.
|
||||||
|
# If component is fully covered with type annotations, please add it here
|
||||||
|
# to enable strict mypy checks.
|
||||||
|
|
||||||
|
# Strict typing is enabled by default for core files.
|
||||||
|
# Add it here to add 'disallow_any_generics'.
|
||||||
|
# --- Only for core file! ---
|
||||||
|
homeassistant.auth.auth_store
|
||||||
|
homeassistant.auth.providers.*
|
||||||
|
homeassistant.core
|
||||||
|
homeassistant.exceptions
|
||||||
|
homeassistant.helpers.area_registry
|
||||||
|
homeassistant.helpers.condition
|
||||||
|
homeassistant.helpers.debounce
|
||||||
|
homeassistant.helpers.deprecation
|
||||||
|
homeassistant.helpers.device_registry
|
||||||
|
homeassistant.helpers.discovery
|
||||||
|
homeassistant.helpers.dispatcher
|
||||||
|
homeassistant.helpers.entity
|
||||||
|
homeassistant.helpers.entity_platform
|
||||||
|
homeassistant.helpers.entity_values
|
||||||
|
homeassistant.helpers.event
|
||||||
|
homeassistant.helpers.reload
|
||||||
|
homeassistant.helpers.script
|
||||||
|
homeassistant.helpers.script_variables
|
||||||
|
homeassistant.helpers.singleton
|
||||||
|
homeassistant.helpers.sun
|
||||||
|
homeassistant.helpers.translation
|
||||||
|
homeassistant.loader
|
||||||
|
homeassistant.requirements
|
||||||
|
homeassistant.runner
|
||||||
|
homeassistant.setup
|
||||||
|
homeassistant.util.async_
|
||||||
|
homeassistant.util.color
|
||||||
|
homeassistant.util.decorator
|
||||||
|
homeassistant.util.location
|
||||||
|
homeassistant.util.logging
|
||||||
|
homeassistant.util.process
|
||||||
|
homeassistant.util.unit_system
|
||||||
|
|
||||||
|
# --- Add components below this line ---
|
||||||
|
homeassistant.components
|
||||||
|
homeassistant.components.abode.*
|
||||||
|
homeassistant.components.acaia.*
|
||||||
|
homeassistant.components.accuweather.*
|
||||||
|
homeassistant.components.acer_projector.*
|
||||||
|
homeassistant.components.acmeda.*
|
||||||
|
homeassistant.components.actiontec.*
|
||||||
|
homeassistant.components.adax.*
|
||||||
|
homeassistant.components.adguard.*
|
||||||
|
homeassistant.components.aftership.*
|
||||||
|
homeassistant.components.air_quality.*
|
||||||
|
homeassistant.components.airgradient.*
|
||||||
|
homeassistant.components.airly.*
|
||||||
|
homeassistant.components.airnow.*
|
||||||
|
homeassistant.components.airq.*
|
||||||
|
homeassistant.components.airthings.*
|
||||||
|
homeassistant.components.airthings_ble.*
|
||||||
|
homeassistant.components.airtouch5.*
|
||||||
|
homeassistant.components.airvisual.*
|
||||||
|
homeassistant.components.airvisual_pro.*
|
||||||
|
homeassistant.components.airzone.*
|
||||||
|
homeassistant.components.airzone_cloud.*
|
||||||
|
homeassistant.components.aladdin_connect.*
|
||||||
|
homeassistant.components.alarm_control_panel.*
|
||||||
|
homeassistant.components.alert.*
|
||||||
|
homeassistant.components.alexa.*
|
||||||
|
homeassistant.components.alpha_vantage.*
|
||||||
|
homeassistant.components.amazon_polly.*
|
||||||
|
homeassistant.components.amberelectric.*
|
||||||
|
homeassistant.components.ambient_network.*
|
||||||
|
homeassistant.components.ambient_station.*
|
||||||
|
homeassistant.components.amcrest.*
|
||||||
|
homeassistant.components.ampio.*
|
||||||
|
homeassistant.components.analytics.*
|
||||||
|
homeassistant.components.analytics_insights.*
|
||||||
|
homeassistant.components.android_ip_webcam.*
|
||||||
|
homeassistant.components.androidtv.*
|
||||||
|
homeassistant.components.androidtv_remote.*
|
||||||
|
homeassistant.components.anel_pwrctrl.*
|
||||||
|
homeassistant.components.anova.*
|
||||||
|
homeassistant.components.anthemav.*
|
||||||
|
homeassistant.components.apache_kafka.*
|
||||||
|
homeassistant.components.apcupsd.*
|
||||||
|
homeassistant.components.api.*
|
||||||
|
homeassistant.components.apple_tv.*
|
||||||
|
homeassistant.components.apprise.*
|
||||||
|
homeassistant.components.aprs.*
|
||||||
|
homeassistant.components.apsystems.*
|
||||||
|
homeassistant.components.aqualogic.*
|
||||||
|
homeassistant.components.aquostv.*
|
||||||
|
homeassistant.components.aranet.*
|
||||||
|
homeassistant.components.arcam_fmj.*
|
||||||
|
homeassistant.components.arris_tg2492lg.*
|
||||||
|
homeassistant.components.aruba.*
|
||||||
|
homeassistant.components.arwn.*
|
||||||
|
homeassistant.components.aseko_pool_live.*
|
||||||
|
homeassistant.components.assist_pipeline.*
|
||||||
|
homeassistant.components.assist_satellite.*
|
||||||
|
homeassistant.components.asuswrt.*
|
||||||
|
homeassistant.components.autarco.*
|
||||||
|
homeassistant.components.auth.*
|
||||||
|
homeassistant.components.automation.*
|
||||||
|
homeassistant.components.awair.*
|
||||||
|
homeassistant.components.axis.*
|
||||||
|
homeassistant.components.backup.*
|
||||||
|
homeassistant.components.baf.*
|
||||||
|
homeassistant.components.bang_olufsen.*
|
||||||
|
homeassistant.components.bayesian.*
|
||||||
|
homeassistant.components.binary_sensor.*
|
||||||
|
homeassistant.components.bitcoin.*
|
||||||
|
homeassistant.components.blockchain.*
|
||||||
|
homeassistant.components.blue_current.*
|
||||||
|
homeassistant.components.blueprint.*
|
||||||
|
homeassistant.components.bluesound.*
|
||||||
|
homeassistant.components.bluetooth.*
|
||||||
|
homeassistant.components.bluetooth_adapters.*
|
||||||
|
homeassistant.components.bluetooth_tracker.*
|
||||||
|
homeassistant.components.bmw_connected_drive.*
|
||||||
|
homeassistant.components.bond.*
|
||||||
|
homeassistant.components.braviatv.*
|
||||||
|
homeassistant.components.brother.*
|
||||||
|
homeassistant.components.browser.*
|
||||||
|
homeassistant.components.bryant_evolution.*
|
||||||
|
homeassistant.components.bthome.*
|
||||||
|
homeassistant.components.button.*
|
||||||
|
homeassistant.components.calendar.*
|
||||||
|
homeassistant.components.cambridge_audio.*
|
||||||
|
homeassistant.components.camera.*
|
||||||
|
homeassistant.components.canary.*
|
||||||
|
homeassistant.components.cert_expiry.*
|
||||||
|
homeassistant.components.clickatell.*
|
||||||
|
homeassistant.components.clicksend.*
|
||||||
|
homeassistant.components.climate.*
|
||||||
|
homeassistant.components.cloud.*
|
||||||
|
homeassistant.components.co2signal.*
|
||||||
|
homeassistant.components.command_line.*
|
||||||
|
homeassistant.components.config.*
|
||||||
|
homeassistant.components.configurator.*
|
||||||
|
homeassistant.components.cookidoo.*
|
||||||
|
homeassistant.components.counter.*
|
||||||
|
homeassistant.components.cover.*
|
||||||
|
homeassistant.components.cpuspeed.*
|
||||||
|
homeassistant.components.crownstone.*
|
||||||
|
homeassistant.components.date.*
|
||||||
|
homeassistant.components.datetime.*
|
||||||
|
homeassistant.components.deako.*
|
||||||
|
homeassistant.components.deconz.*
|
||||||
|
homeassistant.components.default_config.*
|
||||||
|
homeassistant.components.demo.*
|
||||||
|
homeassistant.components.derivative.*
|
||||||
|
homeassistant.components.device_automation.*
|
||||||
|
homeassistant.components.device_tracker.*
|
||||||
|
homeassistant.components.devolo_home_control.*
|
||||||
|
homeassistant.components.devolo_home_network.*
|
||||||
|
homeassistant.components.dhcp.*
|
||||||
|
homeassistant.components.diagnostics.*
|
||||||
|
homeassistant.components.discovergy.*
|
||||||
|
homeassistant.components.dlna_dmr.*
|
||||||
|
homeassistant.components.dlna_dms.*
|
||||||
|
homeassistant.components.dnsip.*
|
||||||
|
homeassistant.components.doorbird.*
|
||||||
|
homeassistant.components.dormakaba_dkey.*
|
||||||
|
homeassistant.components.downloader.*
|
||||||
|
homeassistant.components.dsmr.*
|
||||||
|
homeassistant.components.duckdns.*
|
||||||
|
homeassistant.components.dunehd.*
|
||||||
|
homeassistant.components.duotecno.*
|
||||||
|
homeassistant.components.easyenergy.*
|
||||||
|
homeassistant.components.ecovacs.*
|
||||||
|
homeassistant.components.ecowitt.*
|
||||||
|
homeassistant.components.efergy.*
|
||||||
|
homeassistant.components.eheimdigital.*
|
||||||
|
homeassistant.components.electrasmart.*
|
||||||
|
homeassistant.components.electric_kiwi.*
|
||||||
|
homeassistant.components.elevenlabs.*
|
||||||
|
homeassistant.components.elgato.*
|
||||||
|
homeassistant.components.elkm1.*
|
||||||
|
homeassistant.components.emulated_hue.*
|
||||||
|
homeassistant.components.energenie_power_sockets.*
|
||||||
|
homeassistant.components.energy.*
|
||||||
|
homeassistant.components.energyzero.*
|
||||||
|
homeassistant.components.enigma2.*
|
||||||
|
homeassistant.components.enphase_envoy.*
|
||||||
|
homeassistant.components.eq3btsmart.*
|
||||||
|
homeassistant.components.esphome.*
|
||||||
|
homeassistant.components.event.*
|
||||||
|
homeassistant.components.evil_genius_labs.*
|
||||||
|
homeassistant.components.evohome.*
|
||||||
|
homeassistant.components.faa_delays.*
|
||||||
|
homeassistant.components.fan.*
|
||||||
|
homeassistant.components.fastdotcom.*
|
||||||
|
homeassistant.components.feedreader.*
|
||||||
|
homeassistant.components.file_upload.*
|
||||||
|
homeassistant.components.filesize.*
|
||||||
|
homeassistant.components.filter.*
|
||||||
|
homeassistant.components.fitbit.*
|
||||||
|
homeassistant.components.flexit_bacnet.*
|
||||||
|
homeassistant.components.flux_led.*
|
||||||
|
homeassistant.components.forecast_solar.*
|
||||||
|
homeassistant.components.fritz.*
|
||||||
|
homeassistant.components.fritzbox.*
|
||||||
|
homeassistant.components.fritzbox_callmonitor.*
|
||||||
|
homeassistant.components.fronius.*
|
||||||
|
homeassistant.components.frontend.*
|
||||||
|
homeassistant.components.fujitsu_fglair.*
|
||||||
|
homeassistant.components.fully_kiosk.*
|
||||||
|
homeassistant.components.fyta.*
|
||||||
|
homeassistant.components.generic_hygrostat.*
|
||||||
|
homeassistant.components.generic_thermostat.*
|
||||||
|
homeassistant.components.geo_location.*
|
||||||
|
homeassistant.components.geocaching.*
|
||||||
|
homeassistant.components.gios.*
|
||||||
|
homeassistant.components.glances.*
|
||||||
|
homeassistant.components.go2rtc.*
|
||||||
|
homeassistant.components.goalzero.*
|
||||||
|
homeassistant.components.google.*
|
||||||
|
homeassistant.components.google_assistant_sdk.*
|
||||||
|
homeassistant.components.google_cloud.*
|
||||||
|
homeassistant.components.google_photos.*
|
||||||
|
homeassistant.components.google_sheets.*
|
||||||
|
homeassistant.components.govee_ble.*
|
||||||
|
homeassistant.components.gpsd.*
|
||||||
|
homeassistant.components.greeneye_monitor.*
|
||||||
|
homeassistant.components.group.*
|
||||||
|
homeassistant.components.guardian.*
|
||||||
|
homeassistant.components.hardkernel.*
|
||||||
|
homeassistant.components.hardware.*
|
||||||
|
homeassistant.components.here_travel_time.*
|
||||||
|
homeassistant.components.history.*
|
||||||
|
homeassistant.components.history_stats.*
|
||||||
|
homeassistant.components.holiday.*
|
||||||
|
homeassistant.components.homeassistant.*
|
||||||
|
homeassistant.components.homeassistant_alerts.*
|
||||||
|
homeassistant.components.homeassistant_green.*
|
||||||
|
homeassistant.components.homeassistant_hardware.*
|
||||||
|
homeassistant.components.homeassistant_sky_connect.*
|
||||||
|
homeassistant.components.homeassistant_yellow.*
|
||||||
|
homeassistant.components.homekit.*
|
||||||
|
homeassistant.components.homekit_controller
|
||||||
|
homeassistant.components.homekit_controller.alarm_control_panel
|
||||||
|
homeassistant.components.homekit_controller.button
|
||||||
|
homeassistant.components.homekit_controller.config_flow
|
||||||
|
homeassistant.components.homekit_controller.const
|
||||||
|
homeassistant.components.homekit_controller.lock
|
||||||
|
homeassistant.components.homekit_controller.select
|
||||||
|
homeassistant.components.homekit_controller.storage
|
||||||
|
homeassistant.components.homekit_controller.utils
|
||||||
|
homeassistant.components.homewizard.*
|
||||||
|
homeassistant.components.homeworks.*
|
||||||
|
homeassistant.components.http.*
|
||||||
|
homeassistant.components.huawei_lte.*
|
||||||
|
homeassistant.components.humidifier.*
|
||||||
|
homeassistant.components.husqvarna_automower.*
|
||||||
|
homeassistant.components.hydrawise.*
|
||||||
|
homeassistant.components.hyperion.*
|
||||||
|
homeassistant.components.ibeacon.*
|
||||||
|
homeassistant.components.idasen_desk.*
|
||||||
|
homeassistant.components.image.*
|
||||||
|
homeassistant.components.image_processing.*
|
||||||
|
homeassistant.components.image_upload.*
|
||||||
|
homeassistant.components.imap.*
|
||||||
|
homeassistant.components.imgw_pib.*
|
||||||
|
homeassistant.components.input_button.*
|
||||||
|
homeassistant.components.input_select.*
|
||||||
|
homeassistant.components.input_text.*
|
||||||
|
homeassistant.components.integration.*
|
||||||
|
homeassistant.components.intent.*
|
||||||
|
homeassistant.components.intent_script.*
|
||||||
|
homeassistant.components.ios.*
|
||||||
|
homeassistant.components.iotty.*
|
||||||
|
homeassistant.components.ipp.*
|
||||||
|
homeassistant.components.iqvia.*
|
||||||
|
homeassistant.components.iron_os.*
|
||||||
|
homeassistant.components.islamic_prayer_times.*
|
||||||
|
homeassistant.components.isy994.*
|
||||||
|
homeassistant.components.jellyfin.*
|
||||||
|
homeassistant.components.jewish_calendar.*
|
||||||
|
homeassistant.components.jvc_projector.*
|
||||||
|
homeassistant.components.kaleidescape.*
|
||||||
|
homeassistant.components.knocki.*
|
||||||
|
homeassistant.components.knx.*
|
||||||
|
homeassistant.components.kraken.*
|
||||||
|
homeassistant.components.lacrosse.*
|
||||||
|
homeassistant.components.lacrosse_view.*
|
||||||
|
homeassistant.components.lamarzocco.*
|
||||||
|
homeassistant.components.lametric.*
|
||||||
|
homeassistant.components.laundrify.*
|
||||||
|
homeassistant.components.lawn_mower.*
|
||||||
|
homeassistant.components.lcn.*
|
||||||
|
homeassistant.components.ld2410_ble.*
|
||||||
|
homeassistant.components.led_ble.*
|
||||||
|
homeassistant.components.lektrico.*
|
||||||
|
homeassistant.components.lidarr.*
|
||||||
|
homeassistant.components.lifx.*
|
||||||
|
homeassistant.components.light.*
|
||||||
|
homeassistant.components.linear_garage_door.*
|
||||||
|
homeassistant.components.linkplay.*
|
||||||
|
homeassistant.components.litejet.*
|
||||||
|
homeassistant.components.litterrobot.*
|
||||||
|
homeassistant.components.local_ip.*
|
||||||
|
homeassistant.components.local_todo.*
|
||||||
|
homeassistant.components.lock.*
|
||||||
|
homeassistant.components.logbook.*
|
||||||
|
homeassistant.components.logger.*
|
||||||
|
homeassistant.components.london_underground.*
|
||||||
|
homeassistant.components.lookin.*
|
||||||
|
homeassistant.components.luftdaten.*
|
||||||
|
homeassistant.components.madvr.*
|
||||||
|
homeassistant.components.manual.*
|
||||||
|
homeassistant.components.mastodon.*
|
||||||
|
homeassistant.components.matrix.*
|
||||||
|
homeassistant.components.matter.*
|
||||||
|
homeassistant.components.mealie.*
|
||||||
|
homeassistant.components.media_extractor.*
|
||||||
|
homeassistant.components.media_player.*
|
||||||
|
homeassistant.components.media_source.*
|
||||||
|
homeassistant.components.met_eireann.*
|
||||||
|
homeassistant.components.metoffice.*
|
||||||
|
homeassistant.components.mikrotik.*
|
||||||
|
homeassistant.components.min_max.*
|
||||||
|
homeassistant.components.minecraft_server.*
|
||||||
|
homeassistant.components.mjpeg.*
|
||||||
|
homeassistant.components.modbus.*
|
||||||
|
homeassistant.components.modem_callerid.*
|
||||||
|
homeassistant.components.mold_indicator.*
|
||||||
|
homeassistant.components.monzo.*
|
||||||
|
homeassistant.components.moon.*
|
||||||
|
homeassistant.components.mopeka.*
|
||||||
|
homeassistant.components.motionmount.*
|
||||||
|
homeassistant.components.mqtt.*
|
||||||
|
homeassistant.components.music_assistant.*
|
||||||
|
homeassistant.components.my.*
|
||||||
|
homeassistant.components.mysensors.*
|
||||||
|
homeassistant.components.myuplink.*
|
||||||
|
homeassistant.components.nam.*
|
||||||
|
homeassistant.components.nanoleaf.*
|
||||||
|
homeassistant.components.nasweb.*
|
||||||
|
homeassistant.components.neato.*
|
||||||
|
homeassistant.components.nest.*
|
||||||
|
homeassistant.components.netatmo.*
|
||||||
|
homeassistant.components.network.*
|
||||||
|
homeassistant.components.nextdns.*
|
||||||
|
homeassistant.components.nfandroidtv.*
|
||||||
|
homeassistant.components.nightscout.*
|
||||||
|
homeassistant.components.nissan_leaf.*
|
||||||
|
homeassistant.components.no_ip.*
|
||||||
|
homeassistant.components.nordpool.*
|
||||||
|
homeassistant.components.notify.*
|
||||||
|
homeassistant.components.notion.*
|
||||||
|
homeassistant.components.number.*
|
||||||
|
homeassistant.components.nut.*
|
||||||
|
homeassistant.components.onboarding.*
|
||||||
|
homeassistant.components.oncue.*
|
||||||
|
homeassistant.components.onewire.*
|
||||||
|
homeassistant.components.onkyo.*
|
||||||
|
homeassistant.components.open_meteo.*
|
||||||
|
homeassistant.components.openai_conversation.*
|
||||||
|
homeassistant.components.openexchangerates.*
|
||||||
|
homeassistant.components.opensky.*
|
||||||
|
homeassistant.components.openuv.*
|
||||||
|
homeassistant.components.oralb.*
|
||||||
|
homeassistant.components.otbr.*
|
||||||
|
homeassistant.components.overkiz.*
|
||||||
|
homeassistant.components.p1_monitor.*
|
||||||
|
homeassistant.components.panel_custom.*
|
||||||
|
homeassistant.components.peblar.*
|
||||||
|
homeassistant.components.peco.*
|
||||||
|
homeassistant.components.persistent_notification.*
|
||||||
|
homeassistant.components.pi_hole.*
|
||||||
|
homeassistant.components.ping.*
|
||||||
|
homeassistant.components.plugwise.*
|
||||||
|
homeassistant.components.powerfox.*
|
||||||
|
homeassistant.components.powerwall.*
|
||||||
|
homeassistant.components.private_ble_device.*
|
||||||
|
homeassistant.components.prometheus.*
|
||||||
|
homeassistant.components.proximity.*
|
||||||
|
homeassistant.components.prusalink.*
|
||||||
|
homeassistant.components.pure_energie.*
|
||||||
|
homeassistant.components.purpleair.*
|
||||||
|
homeassistant.components.pushbullet.*
|
||||||
|
homeassistant.components.pvoutput.*
|
||||||
|
homeassistant.components.qnap_qsw.*
|
||||||
|
homeassistant.components.rabbitair.*
|
||||||
|
homeassistant.components.radarr.*
|
||||||
|
homeassistant.components.radio_browser.*
|
||||||
|
homeassistant.components.rainforest_raven.*
|
||||||
|
homeassistant.components.rainmachine.*
|
||||||
|
homeassistant.components.raspberry_pi.*
|
||||||
|
homeassistant.components.rdw.*
|
||||||
|
homeassistant.components.recollect_waste.*
|
||||||
|
homeassistant.components.recorder.*
|
||||||
|
homeassistant.components.remote.*
|
||||||
|
homeassistant.components.renault.*
|
||||||
|
homeassistant.components.reolink.*
|
||||||
|
homeassistant.components.repairs.*
|
||||||
|
homeassistant.components.rest.*
|
||||||
|
homeassistant.components.rest_command.*
|
||||||
|
homeassistant.components.rfxtrx.*
|
||||||
|
homeassistant.components.rhasspy.*
|
||||||
|
homeassistant.components.ridwell.*
|
||||||
|
homeassistant.components.ring.*
|
||||||
|
homeassistant.components.rituals_perfume_genie.*
|
||||||
|
homeassistant.components.roborock.*
|
||||||
|
homeassistant.components.roku.*
|
||||||
|
homeassistant.components.romy.*
|
||||||
|
homeassistant.components.rpi_power.*
|
||||||
|
homeassistant.components.rss_feed_template.*
|
||||||
|
homeassistant.components.rtsp_to_webrtc.*
|
||||||
|
homeassistant.components.russound_rio.*
|
||||||
|
homeassistant.components.ruuvi_gateway.*
|
||||||
|
homeassistant.components.ruuvitag_ble.*
|
||||||
|
homeassistant.components.samsungtv.*
|
||||||
|
homeassistant.components.scene.*
|
||||||
|
homeassistant.components.schedule.*
|
||||||
|
homeassistant.components.schlage.*
|
||||||
|
homeassistant.components.scrape.*
|
||||||
|
homeassistant.components.script.*
|
||||||
|
homeassistant.components.search.*
|
||||||
|
homeassistant.components.select.*
|
||||||
|
homeassistant.components.sensibo.*
|
||||||
|
homeassistant.components.sensirion_ble.*
|
||||||
|
homeassistant.components.sensor.*
|
||||||
|
homeassistant.components.sensoterra.*
|
||||||
|
homeassistant.components.senz.*
|
||||||
|
homeassistant.components.sfr_box.*
|
||||||
|
homeassistant.components.shell_command.*
|
||||||
|
homeassistant.components.shelly.*
|
||||||
|
homeassistant.components.shopping_list.*
|
||||||
|
homeassistant.components.simplepush.*
|
||||||
|
homeassistant.components.simplisafe.*
|
||||||
|
homeassistant.components.siren.*
|
||||||
|
homeassistant.components.skybell.*
|
||||||
|
homeassistant.components.slack.*
|
||||||
|
homeassistant.components.sleepiq.*
|
||||||
|
homeassistant.components.smhi.*
|
||||||
|
homeassistant.components.smlight.*
|
||||||
|
homeassistant.components.snooz.*
|
||||||
|
homeassistant.components.solarlog.*
|
||||||
|
homeassistant.components.sonarr.*
|
||||||
|
homeassistant.components.speedtestdotnet.*
|
||||||
|
homeassistant.components.spotify.*
|
||||||
|
homeassistant.components.sql.*
|
||||||
|
homeassistant.components.squeezebox.*
|
||||||
|
homeassistant.components.ssdp.*
|
||||||
|
homeassistant.components.starlink.*
|
||||||
|
homeassistant.components.statistics.*
|
||||||
|
homeassistant.components.steamist.*
|
||||||
|
homeassistant.components.stookwijzer.*
|
||||||
|
homeassistant.components.stream.*
|
||||||
|
homeassistant.components.streamlabswater.*
|
||||||
|
homeassistant.components.stt.*
|
||||||
|
homeassistant.components.suez_water.*
|
||||||
|
homeassistant.components.sun.*
|
||||||
|
homeassistant.components.surepetcare.*
|
||||||
|
homeassistant.components.switch.*
|
||||||
|
homeassistant.components.switch_as_x.*
|
||||||
|
homeassistant.components.switchbee.*
|
||||||
|
homeassistant.components.switchbot_cloud.*
|
||||||
|
homeassistant.components.switcher_kis.*
|
||||||
|
homeassistant.components.synology_dsm.*
|
||||||
|
homeassistant.components.system_health.*
|
||||||
|
homeassistant.components.system_log.*
|
||||||
|
homeassistant.components.systemmonitor.*
|
||||||
|
homeassistant.components.tag.*
|
||||||
|
homeassistant.components.tailscale.*
|
||||||
|
homeassistant.components.tailwind.*
|
||||||
|
homeassistant.components.tami4.*
|
||||||
|
homeassistant.components.tautulli.*
|
||||||
|
homeassistant.components.tcp.*
|
||||||
|
homeassistant.components.technove.*
|
||||||
|
homeassistant.components.tedee.*
|
||||||
|
homeassistant.components.text.*
|
||||||
|
homeassistant.components.thethingsnetwork.*
|
||||||
|
homeassistant.components.threshold.*
|
||||||
|
homeassistant.components.tibber.*
|
||||||
|
homeassistant.components.tile.*
|
||||||
|
homeassistant.components.tilt_ble.*
|
||||||
|
homeassistant.components.time.*
|
||||||
|
homeassistant.components.time_date.*
|
||||||
|
homeassistant.components.timer.*
|
||||||
|
homeassistant.components.tod.*
|
||||||
|
homeassistant.components.todo.*
|
||||||
|
homeassistant.components.tolo.*
|
||||||
|
homeassistant.components.tplink.*
|
||||||
|
homeassistant.components.tplink_omada.*
|
||||||
|
homeassistant.components.trace.*
|
||||||
|
homeassistant.components.tractive.*
|
||||||
|
homeassistant.components.tradfri.*
|
||||||
|
homeassistant.components.trafikverket_camera.*
|
||||||
|
homeassistant.components.trafikverket_ferry.*
|
||||||
|
homeassistant.components.trafikverket_train.*
|
||||||
|
homeassistant.components.trafikverket_weatherstation.*
|
||||||
|
homeassistant.components.transmission.*
|
||||||
|
homeassistant.components.trend.*
|
||||||
|
homeassistant.components.tts.*
|
||||||
|
homeassistant.components.twentemilieu.*
|
||||||
|
homeassistant.components.unifi.*
|
||||||
|
homeassistant.components.unifiprotect.*
|
||||||
|
homeassistant.components.upcloud.*
|
||||||
|
homeassistant.components.update.*
|
||||||
|
homeassistant.components.uptime.*
|
||||||
|
homeassistant.components.uptimerobot.*
|
||||||
|
homeassistant.components.usb.*
|
||||||
|
homeassistant.components.uvc.*
|
||||||
|
homeassistant.components.vacuum.*
|
||||||
|
homeassistant.components.vallox.*
|
||||||
|
homeassistant.components.valve.*
|
||||||
|
homeassistant.components.velbus.*
|
||||||
|
homeassistant.components.vlc_telnet.*
|
||||||
|
homeassistant.components.wake_on_lan.*
|
||||||
|
homeassistant.components.wake_word.*
|
||||||
|
homeassistant.components.wallbox.*
|
||||||
|
homeassistant.components.waqi.*
|
||||||
|
homeassistant.components.water_heater.*
|
||||||
|
homeassistant.components.watttime.*
|
||||||
|
homeassistant.components.weather.*
|
||||||
|
homeassistant.components.webhook.*
|
||||||
|
homeassistant.components.webostv.*
|
||||||
|
homeassistant.components.websocket_api.*
|
||||||
|
homeassistant.components.wemo.*
|
||||||
|
homeassistant.components.whois.*
|
||||||
|
homeassistant.components.withings.*
|
||||||
|
homeassistant.components.wiz.*
|
||||||
|
homeassistant.components.wled.*
|
||||||
|
homeassistant.components.workday.*
|
||||||
|
homeassistant.components.worldclock.*
|
||||||
|
homeassistant.components.xiaomi_ble.*
|
||||||
|
homeassistant.components.yale_smart_alarm.*
|
||||||
|
homeassistant.components.yalexs_ble.*
|
||||||
|
homeassistant.components.youtube.*
|
||||||
|
homeassistant.components.zeroconf.*
|
||||||
|
homeassistant.components.zodiac.*
|
||||||
|
homeassistant.components.zone.*
|
||||||
|
homeassistant.components.zwave_js.*
|
||||||
7
home-assistant/.vscode/extensions.json
vendored
Normal file
7
home-assistant/.vscode/extensions.json
vendored
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"recommendations": [
|
||||||
|
"charliermarsh.ruff",
|
||||||
|
"esbenp.prettier-vscode",
|
||||||
|
"ms-python.python"
|
||||||
|
]
|
||||||
|
}
|
||||||
231
home-assistant/.vscode/tasks.json
vendored
Normal file
231
home-assistant/.vscode/tasks.json
vendored
Normal file
@@ -0,0 +1,231 @@
|
|||||||
|
{
|
||||||
|
"version": "2.0.0",
|
||||||
|
"tasks": [
|
||||||
|
{
|
||||||
|
"label": "Run Home Assistant Core",
|
||||||
|
"type": "shell",
|
||||||
|
"command": "hass -c ./config",
|
||||||
|
"group": "test",
|
||||||
|
"presentation": {
|
||||||
|
"reveal": "always",
|
||||||
|
"panel": "new"
|
||||||
|
},
|
||||||
|
"problemMatcher": [],
|
||||||
|
"dependsOn": ["Compile English translations"]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "Pytest",
|
||||||
|
"type": "shell",
|
||||||
|
"command": "${command:python.interpreterPath} -m pytest --timeout=10 tests",
|
||||||
|
"dependsOn": ["Install all Test Requirements"],
|
||||||
|
"group": {
|
||||||
|
"kind": "test",
|
||||||
|
"isDefault": true
|
||||||
|
},
|
||||||
|
"presentation": {
|
||||||
|
"reveal": "always",
|
||||||
|
"panel": "new"
|
||||||
|
},
|
||||||
|
"problemMatcher": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "Pytest (changed tests only)",
|
||||||
|
"type": "shell",
|
||||||
|
"command": "${command:python.interpreterPath} -m pytest --timeout=10 --picked",
|
||||||
|
"group": {
|
||||||
|
"kind": "test",
|
||||||
|
"isDefault": true
|
||||||
|
},
|
||||||
|
"presentation": {
|
||||||
|
"reveal": "always",
|
||||||
|
"panel": "new"
|
||||||
|
},
|
||||||
|
"problemMatcher": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "Ruff",
|
||||||
|
"type": "shell",
|
||||||
|
"command": "pre-commit run ruff --all-files",
|
||||||
|
"group": {
|
||||||
|
"kind": "test",
|
||||||
|
"isDefault": true
|
||||||
|
},
|
||||||
|
"presentation": {
|
||||||
|
"reveal": "always",
|
||||||
|
"panel": "new"
|
||||||
|
},
|
||||||
|
"problemMatcher": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "Pre-commit",
|
||||||
|
"type": "shell",
|
||||||
|
"command": "pre-commit run --show-diff-on-failure",
|
||||||
|
"group": {
|
||||||
|
"kind": "test",
|
||||||
|
"isDefault": true
|
||||||
|
},
|
||||||
|
"presentation": {
|
||||||
|
"reveal": "always",
|
||||||
|
"panel": "new"
|
||||||
|
},
|
||||||
|
"problemMatcher": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "Pylint",
|
||||||
|
"type": "shell",
|
||||||
|
"command": "pylint homeassistant",
|
||||||
|
"dependsOn": ["Install all Requirements"],
|
||||||
|
"group": {
|
||||||
|
"kind": "test",
|
||||||
|
"isDefault": true
|
||||||
|
},
|
||||||
|
"presentation": {
|
||||||
|
"reveal": "always",
|
||||||
|
"panel": "new"
|
||||||
|
},
|
||||||
|
"problemMatcher": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "Code Coverage",
|
||||||
|
"detail": "Generate code coverage report for a given integration.",
|
||||||
|
"type": "shell",
|
||||||
|
"command": "${command:python.interpreterPath} -m pytest ./tests/components/${input:integrationName}/ --cov=homeassistant.components.${input:integrationName} --cov-report term-missing --durations-min=1 --durations=0 --numprocesses=auto",
|
||||||
|
"dependsOn": ["Compile English translations"],
|
||||||
|
"group": {
|
||||||
|
"kind": "test",
|
||||||
|
"isDefault": true
|
||||||
|
},
|
||||||
|
"presentation": {
|
||||||
|
"reveal": "always",
|
||||||
|
"panel": "new"
|
||||||
|
},
|
||||||
|
"problemMatcher": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "Update syrupy snapshots",
|
||||||
|
"detail": "Update syrupy snapshots for a given integration.",
|
||||||
|
"type": "shell",
|
||||||
|
"command": "${command:python.interpreterPath} -m pytest ./tests/components/${input:integrationName} --snapshot-update",
|
||||||
|
"dependsOn": ["Compile English translations"],
|
||||||
|
"group": {
|
||||||
|
"kind": "test",
|
||||||
|
"isDefault": true
|
||||||
|
},
|
||||||
|
"presentation": {
|
||||||
|
"reveal": "always",
|
||||||
|
"panel": "new"
|
||||||
|
},
|
||||||
|
"problemMatcher": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "Generate Requirements",
|
||||||
|
"type": "shell",
|
||||||
|
"command": "./script/gen_requirements_all.py",
|
||||||
|
"group": {
|
||||||
|
"kind": "build",
|
||||||
|
"isDefault": true
|
||||||
|
},
|
||||||
|
"presentation": {
|
||||||
|
"reveal": "always",
|
||||||
|
"panel": "new"
|
||||||
|
},
|
||||||
|
"problemMatcher": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "Install all Requirements",
|
||||||
|
"type": "shell",
|
||||||
|
"command": "uv pip install -r requirements_all.txt",
|
||||||
|
"group": {
|
||||||
|
"kind": "build",
|
||||||
|
"isDefault": true
|
||||||
|
},
|
||||||
|
"presentation": {
|
||||||
|
"reveal": "always",
|
||||||
|
"panel": "new"
|
||||||
|
},
|
||||||
|
"problemMatcher": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "Install all Test Requirements",
|
||||||
|
"type": "shell",
|
||||||
|
"command": "uv pip install -r requirements_test_all.txt",
|
||||||
|
"group": {
|
||||||
|
"kind": "build",
|
||||||
|
"isDefault": true
|
||||||
|
},
|
||||||
|
"presentation": {
|
||||||
|
"reveal": "always",
|
||||||
|
"panel": "new"
|
||||||
|
},
|
||||||
|
"problemMatcher": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "Compile English translations",
|
||||||
|
"detail": "In order to test changes to translation files, the translation strings must be compiled into Home Assistant's translation directories.",
|
||||||
|
"type": "shell",
|
||||||
|
"command": "${command:python.interpreterPath} -m script.translations develop --all",
|
||||||
|
"group": {
|
||||||
|
"kind": "build",
|
||||||
|
"isDefault": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "Run scaffold",
|
||||||
|
"detail": "Add new functionality to a integration using a scaffold.",
|
||||||
|
"type": "shell",
|
||||||
|
"command": "${command:python.interpreterPath} -m script.scaffold ${input:scaffoldName} --integration ${input:integrationName}",
|
||||||
|
"group": {
|
||||||
|
"kind": "build",
|
||||||
|
"isDefault": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "Create new integration",
|
||||||
|
"detail": "Use the scaffold to create a new integration.",
|
||||||
|
"type": "shell",
|
||||||
|
"command": "${command:python.interpreterPath} -m script.scaffold integration",
|
||||||
|
"group": {
|
||||||
|
"kind": "build",
|
||||||
|
"isDefault": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "Install integration requirements",
|
||||||
|
"detail": "Install all requirements of a given integration.",
|
||||||
|
"type": "shell",
|
||||||
|
"command": "${command:python.interpreterPath} -m script.install_integration_requirements ${input:integrationName}",
|
||||||
|
"group": {
|
||||||
|
"kind": "build",
|
||||||
|
"isDefault": true
|
||||||
|
},
|
||||||
|
"presentation": {
|
||||||
|
"reveal": "always",
|
||||||
|
"panel": "new"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"inputs": [
|
||||||
|
{
|
||||||
|
"id": "integrationName",
|
||||||
|
"type": "promptString",
|
||||||
|
"description": "For which integration should the task run?"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "scaffoldName",
|
||||||
|
"type": "pickString",
|
||||||
|
"options": [
|
||||||
|
"backup",
|
||||||
|
"config_flow",
|
||||||
|
"config_flow_discovery",
|
||||||
|
"config_flow_helper",
|
||||||
|
"config_flow_oauth2",
|
||||||
|
"device_action",
|
||||||
|
"device_condition",
|
||||||
|
"device_trigger",
|
||||||
|
"reproduce_state",
|
||||||
|
"significant_change"
|
||||||
|
],
|
||||||
|
"description": "Which scaffold should be run?"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
61
home-assistant/.yamllint
Normal file
61
home-assistant/.yamllint
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
ignore: |
|
||||||
|
tests/fixtures/core/config/yaml_errors/
|
||||||
|
rules:
|
||||||
|
braces:
|
||||||
|
level: error
|
||||||
|
min-spaces-inside: 0
|
||||||
|
max-spaces-inside: 1
|
||||||
|
min-spaces-inside-empty: -1
|
||||||
|
max-spaces-inside-empty: -1
|
||||||
|
brackets:
|
||||||
|
level: error
|
||||||
|
min-spaces-inside: 0
|
||||||
|
max-spaces-inside: 0
|
||||||
|
min-spaces-inside-empty: -1
|
||||||
|
max-spaces-inside-empty: -1
|
||||||
|
colons:
|
||||||
|
level: error
|
||||||
|
max-spaces-before: 0
|
||||||
|
max-spaces-after: 1
|
||||||
|
commas:
|
||||||
|
level: error
|
||||||
|
max-spaces-before: 0
|
||||||
|
min-spaces-after: 1
|
||||||
|
max-spaces-after: 1
|
||||||
|
comments:
|
||||||
|
level: error
|
||||||
|
require-starting-space: true
|
||||||
|
min-spaces-from-content: 1
|
||||||
|
comments-indentation:
|
||||||
|
level: error
|
||||||
|
document-end:
|
||||||
|
level: error
|
||||||
|
present: false
|
||||||
|
document-start:
|
||||||
|
level: error
|
||||||
|
present: false
|
||||||
|
empty-lines:
|
||||||
|
level: error
|
||||||
|
max: 1
|
||||||
|
max-start: 0
|
||||||
|
max-end: 1
|
||||||
|
hyphens:
|
||||||
|
level: error
|
||||||
|
max-spaces-after: 1
|
||||||
|
indentation:
|
||||||
|
level: error
|
||||||
|
spaces: 2
|
||||||
|
indent-sequences: true
|
||||||
|
check-multi-line-strings: false
|
||||||
|
key-duplicates:
|
||||||
|
level: error
|
||||||
|
line-length: disable
|
||||||
|
new-line-at-end-of-file:
|
||||||
|
level: error
|
||||||
|
new-lines:
|
||||||
|
level: error
|
||||||
|
type: unix
|
||||||
|
trailing-spaces:
|
||||||
|
level: error
|
||||||
|
truthy:
|
||||||
|
level: error
|
||||||
39
home-assistant/CLA.md
Normal file
39
home-assistant/CLA.md
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
# Contributor License Agreement
|
||||||
|
|
||||||
|
```
|
||||||
|
By making a contribution to this project, I certify that:
|
||||||
|
|
||||||
|
(a) The contribution was created in whole or in part by me and I
|
||||||
|
have the right to submit it under the Apache 2.0 license; or
|
||||||
|
|
||||||
|
(b) The contribution is based upon previous work that, to the best
|
||||||
|
of my knowledge, is covered under an appropriate open source
|
||||||
|
license and I have the right under that license to submit that
|
||||||
|
work with modifications, whether created in whole or in part
|
||||||
|
by me, under the Apache 2.0 license; or
|
||||||
|
|
||||||
|
(c) The contribution was provided directly to me by some other
|
||||||
|
person who certified (a), (b) or (c) and I have not modified
|
||||||
|
it.
|
||||||
|
|
||||||
|
(d) I understand and agree that this project and the contribution
|
||||||
|
are public and that a record of the contribution (including all
|
||||||
|
personal information I submit with it) is maintained indefinitely
|
||||||
|
and may be redistributed consistent with this project or the open
|
||||||
|
source license(s) involved.
|
||||||
|
```
|
||||||
|
|
||||||
|
## Attribution
|
||||||
|
|
||||||
|
The text of this license is available under the [Creative Commons Attribution-ShareAlike 3.0 Unported License](http://creativecommons.org/licenses/by-sa/3.0/). It is based on the Linux [Developer Certificate Of Origin](http://elinux.org/Developer_Certificate_Of_Origin), but is modified to explicitly use the Apache 2.0 license
|
||||||
|
and not mention sign-off.
|
||||||
|
|
||||||
|
## Signing
|
||||||
|
|
||||||
|
To sign this CLA you must first submit a pull request to a repository under the Home Assistant organization.
|
||||||
|
|
||||||
|
## Adoption
|
||||||
|
|
||||||
|
This Contributor License Agreement (CLA) was first announced on January 21st, 2017 in [this][cla-blog] blog post and adopted January 28th, 2017.
|
||||||
|
|
||||||
|
[cla-blog]: https://home-assistant.io/blog/2017/01/21/home-assistant-governance/
|
||||||
1771
home-assistant/CODEOWNERS
Normal file
1771
home-assistant/CODEOWNERS
Normal file
File diff suppressed because it is too large
Load Diff
140
home-assistant/CODE_OF_CONDUCT.md
Normal file
140
home-assistant/CODE_OF_CONDUCT.md
Normal file
@@ -0,0 +1,140 @@
|
|||||||
|
# Contributor Covenant Code of Conduct
|
||||||
|
|
||||||
|
## Our Pledge
|
||||||
|
|
||||||
|
We as members, contributors, and leaders pledge to make participation in our
|
||||||
|
community a harassment-free experience for everyone, regardless of age, body
|
||||||
|
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
||||||
|
identity and expression, level of experience, education, socioeconomic status,
|
||||||
|
nationality, personal appearance, race, religion, or sexual identity
|
||||||
|
and orientation.
|
||||||
|
|
||||||
|
We pledge to act and interact in ways that contribute to an open, welcoming,
|
||||||
|
diverse, inclusive, and healthy community.
|
||||||
|
|
||||||
|
## Our Standards
|
||||||
|
|
||||||
|
Examples of behavior that contributes to a positive environment for our
|
||||||
|
community include:
|
||||||
|
|
||||||
|
* Demonstrating empathy and kindness toward other people
|
||||||
|
* Being respectful of differing opinions, viewpoints, and experiences
|
||||||
|
* Giving and gracefully accepting constructive feedback
|
||||||
|
* Accepting responsibility and apologizing to those affected by our mistakes,
|
||||||
|
and learning from the experience
|
||||||
|
* Focusing on what is best not just for us as individuals, but for the
|
||||||
|
overall community
|
||||||
|
|
||||||
|
Examples of unacceptable behavior include:
|
||||||
|
|
||||||
|
* The use of sexualized language or imagery, and sexual attention or
|
||||||
|
advances of any kind
|
||||||
|
* Trolling, insulting or derogatory comments, and personal or political attacks
|
||||||
|
* Public or private harassment
|
||||||
|
* Publishing others' private information, such as a physical or email
|
||||||
|
address, without their explicit permission
|
||||||
|
* Other conduct which could reasonably be considered inappropriate in a
|
||||||
|
professional setting
|
||||||
|
|
||||||
|
## Enforcement Responsibilities
|
||||||
|
|
||||||
|
Community leaders are responsible for clarifying and enforcing our standards of
|
||||||
|
acceptable behavior and will take appropriate and fair corrective action in
|
||||||
|
response to any behavior that they deem inappropriate, threatening, offensive,
|
||||||
|
or harmful.
|
||||||
|
|
||||||
|
Community leaders have the right and responsibility to remove, edit, or reject
|
||||||
|
comments, commits, code, wiki edits, issues, and other contributions that are
|
||||||
|
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
||||||
|
decisions when appropriate.
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
|
||||||
|
This Code of Conduct applies within all community spaces, and also applies when
|
||||||
|
an individual is officially representing the community in public spaces.
|
||||||
|
Examples of representing our community include using an official e-mail address,
|
||||||
|
posting via an official social media account, or acting as an appointed
|
||||||
|
representative at an online or offline event.
|
||||||
|
|
||||||
|
## Enforcement
|
||||||
|
|
||||||
|
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||||
|
reported to the community leaders responsible for enforcement at
|
||||||
|
[safety@home-assistant.io][email] or by using the report/flag feature of
|
||||||
|
the medium used. All complaints will be reviewed and investigated promptly and
|
||||||
|
fairly.
|
||||||
|
|
||||||
|
All community leaders are obligated to respect the privacy and security of the
|
||||||
|
reporter of any incident.
|
||||||
|
|
||||||
|
## Enforcement Guidelines
|
||||||
|
|
||||||
|
Community leaders will follow these Community Impact Guidelines in determining
|
||||||
|
the consequences for any action they deem in violation of this Code of Conduct:
|
||||||
|
|
||||||
|
### 1. Correction
|
||||||
|
|
||||||
|
**Community Impact**: Use of inappropriate language or other behavior deemed
|
||||||
|
unprofessional or unwelcome in the community.
|
||||||
|
|
||||||
|
**Consequence**: A private, written warning from community leaders, providing
|
||||||
|
clarity around the nature of the violation and an explanation of why the
|
||||||
|
behavior was inappropriate. A public apology may be requested.
|
||||||
|
|
||||||
|
### 2. Warning
|
||||||
|
|
||||||
|
**Community Impact**: A violation through a single incident or series
|
||||||
|
of actions.
|
||||||
|
|
||||||
|
**Consequence**: A warning with consequences for continued behavior. No
|
||||||
|
interaction with the people involved, including unsolicited interaction with
|
||||||
|
those enforcing the Code of Conduct, for a specified period of time. This
|
||||||
|
includes avoiding interactions in community spaces as well as external channels
|
||||||
|
like social media. Violating these terms may lead to a temporary or
|
||||||
|
permanent ban.
|
||||||
|
|
||||||
|
### 3. Temporary Ban
|
||||||
|
|
||||||
|
**Community Impact**: A serious violation of community standards, including
|
||||||
|
sustained inappropriate behavior.
|
||||||
|
|
||||||
|
**Consequence**: A temporary ban from any sort of interaction or public
|
||||||
|
communication with the community for a specified period of time. No public or
|
||||||
|
private interaction with the people involved, including unsolicited interaction
|
||||||
|
with those enforcing the Code of Conduct, is allowed during this period.
|
||||||
|
Violating these terms may lead to a permanent ban.
|
||||||
|
|
||||||
|
### 4. Permanent Ban
|
||||||
|
|
||||||
|
**Community Impact**: Demonstrating a pattern of violation of community
|
||||||
|
standards, including sustained inappropriate behavior, harassment of an
|
||||||
|
individual, or aggression toward or disparagement of classes of individuals.
|
||||||
|
|
||||||
|
**Consequence**: A permanent ban from any sort of public interaction within
|
||||||
|
the community.
|
||||||
|
|
||||||
|
## Attribution
|
||||||
|
|
||||||
|
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
||||||
|
version 2.0, available [here][version].
|
||||||
|
|
||||||
|
Community Impact Guidelines were inspired by [Mozilla's code of conduct
|
||||||
|
enforcement ladder][mozilla].
|
||||||
|
|
||||||
|
## Adoption
|
||||||
|
|
||||||
|
This Code of Conduct was first adopted on January 21st, 2017, and announced in
|
||||||
|
[this][coc-blog] blog post and has been updated on May 25th, 2020 to version
|
||||||
|
2.0 of the [Contributor Covenant][homepage] as announced in [this][coc2-blog]
|
||||||
|
blog post.
|
||||||
|
|
||||||
|
For answers to common questions about this code of conduct, see the FAQ at
|
||||||
|
<https://www.contributor-covenant.org/faq>. Translations are available at
|
||||||
|
<https://www.contributor-covenant.org/translations>.
|
||||||
|
|
||||||
|
[coc-blog]: https://www.home-assistant.io/blog/2017/01/21/home-assistant-governance/
|
||||||
|
[coc2-blog]: https://www.home-assistant.io/blog/2020/05/25/code-of-conduct-updated/
|
||||||
|
[email]: mailto:safety@home-assistant.io
|
||||||
|
[homepage]: http://contributor-covenant.org
|
||||||
|
[mozilla]: https://github.com/mozilla/diversity
|
||||||
|
[version]: https://www.contributor-covenant.org/version/2/0/code_of_conduct.html
|
||||||
18
home-assistant/CONTRIBUTING.md
Normal file
18
home-assistant/CONTRIBUTING.md
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
# Contributing to Home Assistant
|
||||||
|
|
||||||
|
Everybody is invited and welcome to contribute to Home Assistant. There is a lot to do...if you are not a developer perhaps you would like to help with the documentation on [home-assistant.io](https://home-assistant.io/)? If you are a developer and have devices in your home which aren't working with Home Assistant yet, why not spend a couple of hours and help to integrate them?
|
||||||
|
|
||||||
|
The process is straight-forward.
|
||||||
|
|
||||||
|
- Read [How to get faster PR reviews](https://github.com/kubernetes/community/blob/master/contributors/guide/pull-requests.md#best-practices-for-faster-reviews) by Kubernetes (but skip step 0 and 1)
|
||||||
|
- Fork the Home Assistant [git repository](https://github.com/home-assistant/core).
|
||||||
|
- Write the code for your device, notification service, sensor, or IoT thing.
|
||||||
|
- Ensure tests work.
|
||||||
|
- Create a Pull Request against the [**dev**](https://github.com/home-assistant/core/tree/dev) branch of Home Assistant.
|
||||||
|
|
||||||
|
Still interested? Then you should take a peek at the [developer documentation](https://developers.home-assistant.io/) to get more details.
|
||||||
|
|
||||||
|
## Feature suggestions
|
||||||
|
|
||||||
|
If you want to suggest a new feature for Home Assistant (e.g., new integrations), please open a thread in our [Community Forum: Feature Requests](https://community.home-assistant.io/c/feature-requests).
|
||||||
|
We use [GitHub for tracking issues](https://github.com/home-assistant/core/issues), not for tracking feature requests.
|
||||||
63
home-assistant/Dockerfile
Normal file
63
home-assistant/Dockerfile
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
# Automatically generated by hassfest.
|
||||||
|
#
|
||||||
|
# To update, run python3 -m script.hassfest -p docker
|
||||||
|
ARG BUILD_FROM
|
||||||
|
FROM ${BUILD_FROM}
|
||||||
|
|
||||||
|
# Synchronize with homeassistant/core.py:async_stop
|
||||||
|
ENV \
|
||||||
|
S6_SERVICES_GRACETIME=240000 \
|
||||||
|
UV_SYSTEM_PYTHON=true \
|
||||||
|
UV_NO_CACHE=true
|
||||||
|
|
||||||
|
ARG QEMU_CPU
|
||||||
|
|
||||||
|
# Install uv
|
||||||
|
RUN pip3 install uv==0.5.8
|
||||||
|
|
||||||
|
WORKDIR /usr/src
|
||||||
|
|
||||||
|
## Setup Home Assistant Core dependencies
|
||||||
|
COPY requirements.txt homeassistant/
|
||||||
|
COPY homeassistant/package_constraints.txt homeassistant/homeassistant/
|
||||||
|
RUN \
|
||||||
|
uv pip install \
|
||||||
|
--no-build \
|
||||||
|
-r homeassistant/requirements.txt
|
||||||
|
|
||||||
|
COPY requirements_all.txt home_assistant_frontend-* home_assistant_intents-* homeassistant/
|
||||||
|
RUN \
|
||||||
|
if ls homeassistant/home_assistant_*.whl 1> /dev/null 2>&1; then \
|
||||||
|
uv pip install homeassistant/home_assistant_*.whl; \
|
||||||
|
fi \
|
||||||
|
&& uv pip install \
|
||||||
|
--no-build \
|
||||||
|
-r homeassistant/requirements_all.txt
|
||||||
|
|
||||||
|
## Setup Home Assistant Core
|
||||||
|
COPY . homeassistant/
|
||||||
|
RUN \
|
||||||
|
uv pip install \
|
||||||
|
-e ./homeassistant \
|
||||||
|
&& python3 -m compileall \
|
||||||
|
homeassistant/homeassistant
|
||||||
|
|
||||||
|
# Home Assistant S6-Overlay
|
||||||
|
COPY rootfs /
|
||||||
|
|
||||||
|
# Needs to be redefined inside the FROM statement to be set for RUN commands
|
||||||
|
ARG BUILD_ARCH
|
||||||
|
# Get go2rtc binary
|
||||||
|
RUN \
|
||||||
|
case "${BUILD_ARCH}" in \
|
||||||
|
"aarch64") go2rtc_suffix='arm64' ;; \
|
||||||
|
"armhf") go2rtc_suffix='armv6' ;; \
|
||||||
|
"armv7") go2rtc_suffix='arm' ;; \
|
||||||
|
*) go2rtc_suffix=${BUILD_ARCH} ;; \
|
||||||
|
esac \
|
||||||
|
&& curl -L https://github.com/AlexxIT/go2rtc/releases/download/v1.9.7/go2rtc_linux_${go2rtc_suffix} --output /bin/go2rtc \
|
||||||
|
&& chmod +x /bin/go2rtc \
|
||||||
|
# Verify go2rtc can be executed
|
||||||
|
&& go2rtc --version
|
||||||
|
|
||||||
|
WORKDIR /config
|
||||||
68
home-assistant/Dockerfile.dev
Normal file
68
home-assistant/Dockerfile.dev
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
FROM mcr.microsoft.com/devcontainers/python:1-3.13
|
||||||
|
|
||||||
|
SHELL ["/bin/bash", "-o", "pipefail", "-c"]
|
||||||
|
|
||||||
|
# Uninstall pre-installed formatting and linting tools
|
||||||
|
# They would conflict with our pinned versions
|
||||||
|
RUN \
|
||||||
|
pipx uninstall pydocstyle \
|
||||||
|
&& pipx uninstall pycodestyle \
|
||||||
|
&& pipx uninstall mypy \
|
||||||
|
&& pipx uninstall pylint
|
||||||
|
|
||||||
|
RUN \
|
||||||
|
curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - \
|
||||||
|
&& apt-get update \
|
||||||
|
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
|
||||||
|
# Additional library needed by some tests and accordingly by VScode Tests Discovery
|
||||||
|
bluez \
|
||||||
|
ffmpeg \
|
||||||
|
libudev-dev \
|
||||||
|
libavformat-dev \
|
||||||
|
libavcodec-dev \
|
||||||
|
libavdevice-dev \
|
||||||
|
libavutil-dev \
|
||||||
|
libgammu-dev \
|
||||||
|
libswscale-dev \
|
||||||
|
libswresample-dev \
|
||||||
|
libavfilter-dev \
|
||||||
|
libpcap-dev \
|
||||||
|
libturbojpeg0 \
|
||||||
|
libyaml-dev \
|
||||||
|
libxml2 \
|
||||||
|
git \
|
||||||
|
cmake \
|
||||||
|
&& apt-get clean \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
# Add go2rtc binary
|
||||||
|
COPY --from=ghcr.io/alexxit/go2rtc:latest /usr/local/bin/go2rtc /bin/go2rtc
|
||||||
|
|
||||||
|
# Install uv
|
||||||
|
RUN pip3 install uv
|
||||||
|
|
||||||
|
WORKDIR /usr/src
|
||||||
|
|
||||||
|
# Setup hass-release
|
||||||
|
RUN git clone --depth 1 https://github.com/home-assistant/hass-release \
|
||||||
|
&& uv pip install --system -e hass-release/ \
|
||||||
|
&& chown -R vscode /usr/src/hass-release/data
|
||||||
|
|
||||||
|
USER vscode
|
||||||
|
ENV VIRTUAL_ENV="/home/vscode/.local/ha-venv"
|
||||||
|
RUN uv venv $VIRTUAL_ENV
|
||||||
|
ENV PATH="$VIRTUAL_ENV/bin:$PATH"
|
||||||
|
|
||||||
|
WORKDIR /tmp
|
||||||
|
|
||||||
|
# Install Python dependencies from requirements
|
||||||
|
COPY requirements.txt ./
|
||||||
|
COPY homeassistant/package_constraints.txt homeassistant/package_constraints.txt
|
||||||
|
RUN uv pip install -r requirements.txt
|
||||||
|
COPY requirements_test.txt requirements_test_pre_commit.txt ./
|
||||||
|
RUN uv pip install -r requirements_test.txt
|
||||||
|
|
||||||
|
WORKDIR /workspaces
|
||||||
|
|
||||||
|
# Set the default shell to bash instead of sh
|
||||||
|
ENV SHELL /bin/bash
|
||||||
201
home-assistant/LICENSE.md
Normal file
201
home-assistant/LICENSE.md
Normal file
@@ -0,0 +1,201 @@
|
|||||||
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
|
1. Definitions.
|
||||||
|
|
||||||
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
|
||||||
|
"Object" form shall mean any form resulting from mechanical
|
||||||
|
transformation or translation of a Source form, including but
|
||||||
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
|
||||||
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
|
Object form, made available under the License, as indicated by a
|
||||||
|
copyright notice that is included in or attached to the work
|
||||||
|
(an example is provided in the Appendix below).
|
||||||
|
|
||||||
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
|
form, that is based on (or derived from) the Work and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
|
"Contribution" shall mean any work of authorship, including
|
||||||
|
the original version of the Work and any modifications or additions
|
||||||
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
|
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||||
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
|
means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems,
|
||||||
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
|
excluding communication that is conspicuously marked or otherwise
|
||||||
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
|
||||||
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
|
or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate
|
||||||
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
|
||||||
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
|
||||||
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
|
||||||
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, then any Derivative Works that You distribute must
|
||||||
|
include a readable copy of the attribution notices contained
|
||||||
|
within such NOTICE file, excluding those notices that do not
|
||||||
|
pertain to any part of the Derivative Works, in at least one
|
||||||
|
of the following places: within a NOTICE text file distributed
|
||||||
|
as part of the Derivative Works; within the Source form or
|
||||||
|
documentation, if provided along with the Derivative Works; or,
|
||||||
|
within a display generated by the Derivative Works, if and
|
||||||
|
wherever such third-party notices normally appear. The contents
|
||||||
|
of the NOTICE file are for informational purposes only and
|
||||||
|
do not modify the License. You may add Your own attribution
|
||||||
|
notices within Derivative Works that You distribute, alongside
|
||||||
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
|
that such additional attribution notices cannot be construed
|
||||||
|
as modifying the License.
|
||||||
|
|
||||||
|
You may add Your own copyright statement to Your modifications and
|
||||||
|
may provide additional or different license terms and conditions
|
||||||
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
|
the conditions stated in this License.
|
||||||
|
|
||||||
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
|
except as required for reasonable and customary use in describing the
|
||||||
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or consequential damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses), even if such Contributor
|
||||||
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
|
||||||
|
To apply the Apache License to your work, attach the following
|
||||||
|
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||||
|
replaced with your own identifying information. (Don't include
|
||||||
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
|
comment syntax for the file format. We also recommend that a
|
||||||
|
file or class name and description of purpose be included on the
|
||||||
|
same "printed page" as the copyright notice for easier
|
||||||
|
identification within third-party archives.
|
||||||
|
|
||||||
|
Copyright [yyyy] [name of copyright owner]
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
||||||
3
home-assistant/MANIFEST.in
Normal file
3
home-assistant/MANIFEST.in
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
include README.rst
|
||||||
|
graft homeassistant
|
||||||
|
recursive-exclude * *.py[co]
|
||||||
33
home-assistant/README.rst
Normal file
33
home-assistant/README.rst
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
Home Assistant |Chat Status|
|
||||||
|
=================================================================================
|
||||||
|
|
||||||
|
Open source home automation that puts local control and privacy first. Powered by a worldwide community of tinkerers and DIY enthusiasts. Perfect to run on a Raspberry Pi or a local server.
|
||||||
|
|
||||||
|
Check out `home-assistant.io <https://home-assistant.io>`__ for `a
|
||||||
|
demo <https://demo.home-assistant.io>`__, `installation instructions <https://home-assistant.io/getting-started/>`__,
|
||||||
|
`tutorials <https://home-assistant.io/getting-started/automation/>`__ and `documentation <https://home-assistant.io/docs/>`__.
|
||||||
|
|
||||||
|
|screenshot-states|
|
||||||
|
|
||||||
|
Featured integrations
|
||||||
|
---------------------
|
||||||
|
|
||||||
|
|screenshot-integrations|
|
||||||
|
|
||||||
|
The system is built using a modular approach so support for other devices or actions can be implemented easily. See also the `section on architecture <https://developers.home-assistant.io/docs/architecture_index/>`__ and the `section on creating your own
|
||||||
|
components <https://developers.home-assistant.io/docs/creating_component_index/>`__.
|
||||||
|
|
||||||
|
If you run into issues while using Home Assistant or during development
|
||||||
|
of a component, check the `Home Assistant help section <https://home-assistant.io/help/>`__ of our website for further help and information.
|
||||||
|
|
||||||
|
|ohf-logo|
|
||||||
|
|
||||||
|
.. |Chat Status| image:: https://img.shields.io/discord/330944238910963714.svg
|
||||||
|
:target: https://www.home-assistant.io/join-chat/
|
||||||
|
.. |screenshot-states| image:: https://raw.githubusercontent.com/home-assistant/core/dev/.github/assets/screenshot-states.png
|
||||||
|
:target: https://demo.home-assistant.io
|
||||||
|
.. |screenshot-integrations| image:: https://raw.githubusercontent.com/home-assistant/core/dev/.github/assets/screenshot-integrations.png
|
||||||
|
:target: https://home-assistant.io/integrations/
|
||||||
|
.. |ohf-logo| image:: https://www.openhomefoundation.org/badges/home-assistant.png
|
||||||
|
:alt: Home Assistant - A project from the Open Home Foundation
|
||||||
|
:target: https://www.openhomefoundation.org/
|
||||||
22
home-assistant/build.yaml
Normal file
22
home-assistant/build.yaml
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
image: ghcr.io/home-assistant/{arch}-homeassistant
|
||||||
|
build_from:
|
||||||
|
aarch64: ghcr.io/home-assistant/aarch64-homeassistant-base:2024.12.0
|
||||||
|
armhf: ghcr.io/home-assistant/armhf-homeassistant-base:2024.12.0
|
||||||
|
armv7: ghcr.io/home-assistant/armv7-homeassistant-base:2024.12.0
|
||||||
|
amd64: ghcr.io/home-assistant/amd64-homeassistant-base:2024.12.0
|
||||||
|
i386: ghcr.io/home-assistant/i386-homeassistant-base:2024.12.0
|
||||||
|
codenotary:
|
||||||
|
signer: notary@home-assistant.io
|
||||||
|
base_image: notary@home-assistant.io
|
||||||
|
cosign:
|
||||||
|
base_identity: https://github.com/home-assistant/docker/.*
|
||||||
|
identity: https://github.com/home-assistant/core/.*
|
||||||
|
labels:
|
||||||
|
io.hass.type: core
|
||||||
|
org.opencontainers.image.title: Home Assistant
|
||||||
|
org.opencontainers.image.description: Open-source home automation platform running on Python 3
|
||||||
|
org.opencontainers.image.source: https://github.com/home-assistant/core
|
||||||
|
org.opencontainers.image.authors: The Home Assistant Authors
|
||||||
|
org.opencontainers.image.url: https://www.home-assistant.io/
|
||||||
|
org.opencontainers.image.documentation: https://www.home-assistant.io/docs/
|
||||||
|
org.opencontainers.image.licenses: Apache License 2.0
|
||||||
53
home-assistant/codecov.yml
Normal file
53
home-assistant/codecov.yml
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
codecov:
|
||||||
|
branch: dev
|
||||||
|
coverage:
|
||||||
|
status:
|
||||||
|
project:
|
||||||
|
default:
|
||||||
|
target: auto
|
||||||
|
threshold: 0.09
|
||||||
|
required:
|
||||||
|
target: auto
|
||||||
|
threshold: 1
|
||||||
|
paths:
|
||||||
|
- homeassistant/components/*/config_flow.py
|
||||||
|
- homeassistant/components/*/device_action.py
|
||||||
|
- homeassistant/components/*/device_condition.py
|
||||||
|
- homeassistant/components/*/device_trigger.py
|
||||||
|
- homeassistant/components/*/diagnostics.py
|
||||||
|
- homeassistant/components/*/group.py
|
||||||
|
- homeassistant/components/*/intent.py
|
||||||
|
- homeassistant/components/*/logbook.py
|
||||||
|
- homeassistant/components/*/media_source.py
|
||||||
|
- homeassistant/components/*/recorder.py
|
||||||
|
- homeassistant/components/*/scene.py
|
||||||
|
patch:
|
||||||
|
default:
|
||||||
|
target: auto
|
||||||
|
required:
|
||||||
|
target: 100
|
||||||
|
threshold: 0
|
||||||
|
paths:
|
||||||
|
- homeassistant/components/*/config_flow.py
|
||||||
|
- homeassistant/components/*/device_action.py
|
||||||
|
- homeassistant/components/*/device_condition.py
|
||||||
|
- homeassistant/components/*/device_trigger.py
|
||||||
|
- homeassistant/components/*/diagnostics.py
|
||||||
|
- homeassistant/components/*/group.py
|
||||||
|
- homeassistant/components/*/intent.py
|
||||||
|
- homeassistant/components/*/logbook.py
|
||||||
|
- homeassistant/components/*/media_source.py
|
||||||
|
- homeassistant/components/*/recorder.py
|
||||||
|
- homeassistant/components/*/scene.py
|
||||||
|
comment: false
|
||||||
|
|
||||||
|
# To make partial tests possible,
|
||||||
|
# we need to carry forward.
|
||||||
|
flag_management:
|
||||||
|
default_rules:
|
||||||
|
carryforward: false
|
||||||
|
individual_flags:
|
||||||
|
- name: full-suite
|
||||||
|
paths:
|
||||||
|
- ".*"
|
||||||
|
carryforward: true
|
||||||
1
home-assistant/homeassistant/__init__.py
Normal file
1
home-assistant/homeassistant/__init__.py
Normal file
@@ -0,0 +1 @@
|
|||||||
|
"""Init file for Home Assistant."""
|
||||||
227
home-assistant/homeassistant/__main__.py
Normal file
227
home-assistant/homeassistant/__main__.py
Normal file
@@ -0,0 +1,227 @@
|
|||||||
|
"""Start Home Assistant."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
from contextlib import suppress
|
||||||
|
import faulthandler
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
|
||||||
|
from .backup_restore import restore_backup
|
||||||
|
from .const import REQUIRED_PYTHON_VER, RESTART_EXIT_CODE, __version__
|
||||||
|
|
||||||
|
FAULT_LOG_FILENAME = "home-assistant.log.fault"
|
||||||
|
|
||||||
|
|
||||||
|
def validate_os() -> None:
|
||||||
|
"""Validate that Home Assistant is running in a supported operating system."""
|
||||||
|
if not sys.platform.startswith(("darwin", "linux")):
|
||||||
|
print(
|
||||||
|
"Home Assistant only supports Linux, OSX and Windows using WSL",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
|
||||||
|
def validate_python() -> None:
|
||||||
|
"""Validate that the right Python version is running."""
|
||||||
|
if sys.version_info[:3] < REQUIRED_PYTHON_VER:
|
||||||
|
print(
|
||||||
|
"Home Assistant requires at least Python "
|
||||||
|
f"{REQUIRED_PYTHON_VER[0]}.{REQUIRED_PYTHON_VER[1]}.{REQUIRED_PYTHON_VER[2]}",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
|
||||||
|
def ensure_config_path(config_dir: str) -> None:
|
||||||
|
"""Validate the configuration directory."""
|
||||||
|
# pylint: disable-next=import-outside-toplevel
|
||||||
|
from . import config as config_util
|
||||||
|
|
||||||
|
lib_dir = os.path.join(config_dir, "deps")
|
||||||
|
|
||||||
|
# Test if configuration directory exists
|
||||||
|
if not os.path.isdir(config_dir):
|
||||||
|
if config_dir != config_util.get_default_config_dir():
|
||||||
|
if os.path.exists(config_dir):
|
||||||
|
reason = "is not a directory"
|
||||||
|
else:
|
||||||
|
reason = "does not exist"
|
||||||
|
print(
|
||||||
|
f"Fatal Error: Specified configuration directory {config_dir} {reason}",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
try:
|
||||||
|
os.mkdir(config_dir)
|
||||||
|
except OSError as ex:
|
||||||
|
print(
|
||||||
|
"Fatal Error: Unable to create default configuration "
|
||||||
|
f"directory {config_dir}: {ex}",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
# Test if library directory exists
|
||||||
|
if not os.path.isdir(lib_dir):
|
||||||
|
try:
|
||||||
|
os.mkdir(lib_dir)
|
||||||
|
except OSError as ex:
|
||||||
|
print(
|
||||||
|
f"Fatal Error: Unable to create library directory {lib_dir}: {ex}",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
|
||||||
|
def get_arguments() -> argparse.Namespace:
|
||||||
|
"""Get parsed passed in arguments."""
|
||||||
|
# pylint: disable-next=import-outside-toplevel
|
||||||
|
from . import config as config_util
|
||||||
|
|
||||||
|
parser = argparse.ArgumentParser(
|
||||||
|
description="Home Assistant: Observe, Control, Automate.",
|
||||||
|
epilog=f"If restart is requested, exits with code {RESTART_EXIT_CODE}",
|
||||||
|
)
|
||||||
|
parser.add_argument("--version", action="version", version=__version__)
|
||||||
|
parser.add_argument(
|
||||||
|
"-c",
|
||||||
|
"--config",
|
||||||
|
metavar="path_to_config_dir",
|
||||||
|
default=config_util.get_default_config_dir(),
|
||||||
|
help="Directory that contains the Home Assistant configuration",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--recovery-mode",
|
||||||
|
action="store_true",
|
||||||
|
help="Start Home Assistant in recovery mode",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--debug", action="store_true", help="Start Home Assistant in debug mode"
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--open-ui", action="store_true", help="Open the webinterface in a browser"
|
||||||
|
)
|
||||||
|
|
||||||
|
skip_pip_group = parser.add_mutually_exclusive_group()
|
||||||
|
skip_pip_group.add_argument(
|
||||||
|
"--skip-pip",
|
||||||
|
action="store_true",
|
||||||
|
help="Skips pip install of required packages on startup",
|
||||||
|
)
|
||||||
|
skip_pip_group.add_argument(
|
||||||
|
"--skip-pip-packages",
|
||||||
|
metavar="package_names",
|
||||||
|
type=lambda arg: arg.split(","),
|
||||||
|
default=[],
|
||||||
|
help="Skip pip install of specific packages on startup",
|
||||||
|
)
|
||||||
|
|
||||||
|
parser.add_argument(
|
||||||
|
"-v", "--verbose", action="store_true", help="Enable verbose logging to file."
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--log-rotate-days",
|
||||||
|
type=int,
|
||||||
|
default=None,
|
||||||
|
help="Enables daily log rotation and keeps up to the specified days",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--log-file",
|
||||||
|
type=str,
|
||||||
|
default=None,
|
||||||
|
help="Log file to write to. If not set, CONFIG/home-assistant.log is used",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--log-no-color", action="store_true", help="Disable color logs"
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--script", nargs=argparse.REMAINDER, help="Run one of the embedded scripts"
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--ignore-os-check",
|
||||||
|
action="store_true",
|
||||||
|
help="Skips validation of operating system",
|
||||||
|
)
|
||||||
|
|
||||||
|
return parser.parse_args()
|
||||||
|
|
||||||
|
|
||||||
|
def check_threads() -> None:
|
||||||
|
"""Check if there are any lingering threads."""
|
||||||
|
try:
|
||||||
|
nthreads = sum(
|
||||||
|
thread.is_alive() and not thread.daemon for thread in threading.enumerate()
|
||||||
|
)
|
||||||
|
if nthreads > 1:
|
||||||
|
sys.stderr.write(f"Found {nthreads} non-daemonic threads.\n")
|
||||||
|
|
||||||
|
# Somehow we sometimes seem to trigger an assertion in the python threading
|
||||||
|
# module. It seems we find threads that have no associated OS level thread
|
||||||
|
# which are not marked as stopped at the python level.
|
||||||
|
except AssertionError:
|
||||||
|
sys.stderr.write("Failed to count non-daemonic threads.\n")
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
"""Start Home Assistant."""
|
||||||
|
validate_python()
|
||||||
|
|
||||||
|
args = get_arguments()
|
||||||
|
|
||||||
|
if not args.ignore_os_check:
|
||||||
|
validate_os()
|
||||||
|
|
||||||
|
if args.script is not None:
|
||||||
|
# pylint: disable-next=import-outside-toplevel
|
||||||
|
from . import scripts
|
||||||
|
|
||||||
|
return scripts.run(args.script)
|
||||||
|
|
||||||
|
config_dir = os.path.abspath(os.path.join(os.getcwd(), args.config))
|
||||||
|
if restore_backup(config_dir):
|
||||||
|
return RESTART_EXIT_CODE
|
||||||
|
|
||||||
|
ensure_config_path(config_dir)
|
||||||
|
|
||||||
|
# pylint: disable-next=import-outside-toplevel
|
||||||
|
from . import config, runner
|
||||||
|
|
||||||
|
safe_mode = config.safe_mode_enabled(config_dir)
|
||||||
|
|
||||||
|
runtime_conf = runner.RuntimeConfig(
|
||||||
|
config_dir=config_dir,
|
||||||
|
verbose=args.verbose,
|
||||||
|
log_rotate_days=args.log_rotate_days,
|
||||||
|
log_file=args.log_file,
|
||||||
|
log_no_color=args.log_no_color,
|
||||||
|
skip_pip=args.skip_pip,
|
||||||
|
skip_pip_packages=args.skip_pip_packages,
|
||||||
|
recovery_mode=args.recovery_mode,
|
||||||
|
debug=args.debug,
|
||||||
|
open_ui=args.open_ui,
|
||||||
|
safe_mode=safe_mode,
|
||||||
|
)
|
||||||
|
|
||||||
|
fault_file_name = os.path.join(config_dir, FAULT_LOG_FILENAME)
|
||||||
|
with open(fault_file_name, mode="a", encoding="utf8") as fault_file:
|
||||||
|
faulthandler.enable(fault_file)
|
||||||
|
exit_code = runner.run(runtime_conf)
|
||||||
|
faulthandler.disable()
|
||||||
|
|
||||||
|
# It's possible for the fault file to disappear, so suppress obvious errors
|
||||||
|
with suppress(FileNotFoundError):
|
||||||
|
if os.path.getsize(fault_file_name) == 0:
|
||||||
|
os.remove(fault_file_name)
|
||||||
|
|
||||||
|
check_threads()
|
||||||
|
|
||||||
|
return exit_code
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
703
home-assistant/homeassistant/auth/__init__.py
Normal file
703
home-assistant/homeassistant/auth/__init__.py
Normal file
@@ -0,0 +1,703 @@
|
|||||||
|
"""Provide an authentication layer for Home Assistant."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
from collections import OrderedDict
|
||||||
|
from collections.abc import Mapping
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
from functools import partial
|
||||||
|
import time
|
||||||
|
from typing import Any, cast
|
||||||
|
|
||||||
|
import jwt
|
||||||
|
|
||||||
|
from homeassistant.core import (
|
||||||
|
CALLBACK_TYPE,
|
||||||
|
HassJob,
|
||||||
|
HassJobType,
|
||||||
|
HomeAssistant,
|
||||||
|
callback,
|
||||||
|
)
|
||||||
|
from homeassistant.data_entry_flow import FlowHandler, FlowManager, FlowResultType
|
||||||
|
from homeassistant.helpers.event import async_track_point_in_utc_time
|
||||||
|
from homeassistant.util import dt as dt_util
|
||||||
|
|
||||||
|
from . import auth_store, jwt_wrapper, models
|
||||||
|
from .const import ACCESS_TOKEN_EXPIRATION, GROUP_ID_ADMIN, REFRESH_TOKEN_EXPIRATION
|
||||||
|
from .mfa_modules import MultiFactorAuthModule, auth_mfa_module_from_config
|
||||||
|
from .models import AuthFlowContext, AuthFlowResult
|
||||||
|
from .providers import AuthProvider, LoginFlow, auth_provider_from_config
|
||||||
|
from .providers.homeassistant import HassAuthProvider
|
||||||
|
|
||||||
|
EVENT_USER_ADDED = "user_added"
|
||||||
|
EVENT_USER_UPDATED = "user_updated"
|
||||||
|
EVENT_USER_REMOVED = "user_removed"
|
||||||
|
|
||||||
|
type _MfaModuleDict = dict[str, MultiFactorAuthModule]
|
||||||
|
type _ProviderKey = tuple[str, str | None]
|
||||||
|
type _ProviderDict = dict[_ProviderKey, AuthProvider]
|
||||||
|
|
||||||
|
|
||||||
|
class InvalidAuthError(Exception):
|
||||||
|
"""Raised when a authentication error occurs."""
|
||||||
|
|
||||||
|
|
||||||
|
class InvalidProvider(Exception):
|
||||||
|
"""Authentication provider not found."""
|
||||||
|
|
||||||
|
|
||||||
|
async def auth_manager_from_config(
|
||||||
|
hass: HomeAssistant,
|
||||||
|
provider_configs: list[dict[str, Any]],
|
||||||
|
module_configs: list[dict[str, Any]],
|
||||||
|
) -> AuthManager:
|
||||||
|
"""Initialize an auth manager from config.
|
||||||
|
|
||||||
|
CORE_CONFIG_SCHEMA will make sure no duplicated auth providers or
|
||||||
|
mfa modules exist in configs.
|
||||||
|
"""
|
||||||
|
store = auth_store.AuthStore(hass)
|
||||||
|
await store.async_load()
|
||||||
|
if provider_configs:
|
||||||
|
providers = await asyncio.gather(
|
||||||
|
*(
|
||||||
|
auth_provider_from_config(hass, store, config)
|
||||||
|
for config in provider_configs
|
||||||
|
)
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
providers = []
|
||||||
|
# So returned auth providers are in same order as config
|
||||||
|
provider_hash: _ProviderDict = OrderedDict()
|
||||||
|
for provider in providers:
|
||||||
|
key = (provider.type, provider.id)
|
||||||
|
provider_hash[key] = provider
|
||||||
|
|
||||||
|
if isinstance(provider, HassAuthProvider):
|
||||||
|
# Can be removed in 2026.7 with the legacy mode of homeassistant auth provider
|
||||||
|
# We need to initialize the provider to create the repair if needed as otherwise
|
||||||
|
# the provider will be initialized on first use, which could be rare as users
|
||||||
|
# don't frequently change auth settings
|
||||||
|
await provider.async_initialize()
|
||||||
|
|
||||||
|
if module_configs:
|
||||||
|
modules = await asyncio.gather(
|
||||||
|
*(auth_mfa_module_from_config(hass, config) for config in module_configs)
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
modules = []
|
||||||
|
# So returned auth modules are in same order as config
|
||||||
|
module_hash: _MfaModuleDict = OrderedDict()
|
||||||
|
for module in modules:
|
||||||
|
module_hash[module.id] = module
|
||||||
|
|
||||||
|
manager = AuthManager(hass, store, provider_hash, module_hash)
|
||||||
|
await manager.async_setup()
|
||||||
|
return manager
|
||||||
|
|
||||||
|
|
||||||
|
class AuthManagerFlowManager(
|
||||||
|
FlowManager[AuthFlowContext, AuthFlowResult, tuple[str, str]]
|
||||||
|
):
|
||||||
|
"""Manage authentication flows."""
|
||||||
|
|
||||||
|
_flow_result = AuthFlowResult
|
||||||
|
|
||||||
|
def __init__(self, hass: HomeAssistant, auth_manager: AuthManager) -> None:
|
||||||
|
"""Init auth manager flows."""
|
||||||
|
super().__init__(hass)
|
||||||
|
self.auth_manager = auth_manager
|
||||||
|
|
||||||
|
async def async_create_flow(
|
||||||
|
self,
|
||||||
|
handler_key: tuple[str, str],
|
||||||
|
*,
|
||||||
|
context: AuthFlowContext | None = None,
|
||||||
|
data: dict[str, Any] | None = None,
|
||||||
|
) -> LoginFlow[Any]:
|
||||||
|
"""Create a login flow."""
|
||||||
|
auth_provider = self.auth_manager.get_auth_provider(*handler_key)
|
||||||
|
if not auth_provider:
|
||||||
|
raise KeyError(f"Unknown auth provider {handler_key}")
|
||||||
|
return await auth_provider.async_login_flow(context)
|
||||||
|
|
||||||
|
async def async_finish_flow(
|
||||||
|
self,
|
||||||
|
flow: FlowHandler[AuthFlowContext, AuthFlowResult, tuple[str, str]],
|
||||||
|
result: AuthFlowResult,
|
||||||
|
) -> AuthFlowResult:
|
||||||
|
"""Return a user as result of login flow.
|
||||||
|
|
||||||
|
This method is called when a flow step returns FlowResultType.ABORT or
|
||||||
|
FlowResultType.CREATE_ENTRY.
|
||||||
|
"""
|
||||||
|
flow = cast(LoginFlow, flow)
|
||||||
|
|
||||||
|
if result["type"] != FlowResultType.CREATE_ENTRY:
|
||||||
|
return result
|
||||||
|
|
||||||
|
# we got final result
|
||||||
|
if isinstance(result["data"], models.Credentials):
|
||||||
|
result["result"] = result["data"]
|
||||||
|
return result
|
||||||
|
|
||||||
|
auth_provider = self.auth_manager.get_auth_provider(*result["handler"])
|
||||||
|
if not auth_provider:
|
||||||
|
raise KeyError(f"Unknown auth provider {result['handler']}")
|
||||||
|
|
||||||
|
credentials = await auth_provider.async_get_or_create_credentials(
|
||||||
|
cast(Mapping[str, str], result["data"]),
|
||||||
|
)
|
||||||
|
|
||||||
|
if flow.context.get("credential_only"):
|
||||||
|
result["result"] = credentials
|
||||||
|
return result
|
||||||
|
|
||||||
|
# multi-factor module cannot enabled for new credential
|
||||||
|
# which has not linked to a user yet
|
||||||
|
if auth_provider.support_mfa and not credentials.is_new:
|
||||||
|
user = await self.auth_manager.async_get_user_by_credentials(credentials)
|
||||||
|
if user is not None:
|
||||||
|
modules = await self.auth_manager.async_get_enabled_mfa(user)
|
||||||
|
|
||||||
|
if modules:
|
||||||
|
flow.credential = credentials
|
||||||
|
flow.user = user
|
||||||
|
flow.available_mfa_modules = modules
|
||||||
|
return await flow.async_step_select_mfa_module()
|
||||||
|
|
||||||
|
result["result"] = credentials
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
class AuthManager:
|
||||||
|
"""Manage the authentication for Home Assistant."""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
hass: HomeAssistant,
|
||||||
|
store: auth_store.AuthStore,
|
||||||
|
providers: _ProviderDict,
|
||||||
|
mfa_modules: _MfaModuleDict,
|
||||||
|
) -> None:
|
||||||
|
"""Initialize the auth manager."""
|
||||||
|
self.hass = hass
|
||||||
|
self._store = store
|
||||||
|
self._providers = providers
|
||||||
|
self._mfa_modules = mfa_modules
|
||||||
|
self.login_flow = AuthManagerFlowManager(hass, self)
|
||||||
|
self._revoke_callbacks: dict[str, set[CALLBACK_TYPE]] = {}
|
||||||
|
self._expire_callback: CALLBACK_TYPE | None = None
|
||||||
|
self._remove_expired_job = HassJob(
|
||||||
|
self._async_remove_expired_refresh_tokens, job_type=HassJobType.Callback
|
||||||
|
)
|
||||||
|
|
||||||
|
async def async_setup(self) -> None:
|
||||||
|
"""Set up the auth manager."""
|
||||||
|
hass = self.hass
|
||||||
|
hass.async_add_shutdown_job(
|
||||||
|
HassJob(
|
||||||
|
self._async_cancel_expiration_schedule, job_type=HassJobType.Callback
|
||||||
|
)
|
||||||
|
)
|
||||||
|
self._async_track_next_refresh_token_expiration()
|
||||||
|
|
||||||
|
@property
|
||||||
|
def auth_providers(self) -> list[AuthProvider]:
|
||||||
|
"""Return a list of available auth providers."""
|
||||||
|
return list(self._providers.values())
|
||||||
|
|
||||||
|
@property
|
||||||
|
def auth_mfa_modules(self) -> list[MultiFactorAuthModule]:
|
||||||
|
"""Return a list of available auth modules."""
|
||||||
|
return list(self._mfa_modules.values())
|
||||||
|
|
||||||
|
def get_auth_provider(
|
||||||
|
self, provider_type: str, provider_id: str | None
|
||||||
|
) -> AuthProvider | None:
|
||||||
|
"""Return an auth provider, None if not found."""
|
||||||
|
return self._providers.get((provider_type, provider_id))
|
||||||
|
|
||||||
|
def get_auth_providers(self, provider_type: str) -> list[AuthProvider]:
|
||||||
|
"""Return a List of auth provider of one type, Empty if not found."""
|
||||||
|
return [
|
||||||
|
provider
|
||||||
|
for (p_type, _), provider in self._providers.items()
|
||||||
|
if p_type == provider_type
|
||||||
|
]
|
||||||
|
|
||||||
|
def get_auth_mfa_module(self, module_id: str) -> MultiFactorAuthModule | None:
|
||||||
|
"""Return a multi-factor auth module, None if not found."""
|
||||||
|
return self._mfa_modules.get(module_id)
|
||||||
|
|
||||||
|
async def async_get_users(self) -> list[models.User]:
|
||||||
|
"""Retrieve all users."""
|
||||||
|
return await self._store.async_get_users()
|
||||||
|
|
||||||
|
async def async_get_user(self, user_id: str) -> models.User | None:
|
||||||
|
"""Retrieve a user."""
|
||||||
|
return await self._store.async_get_user(user_id)
|
||||||
|
|
||||||
|
async def async_get_owner(self) -> models.User | None:
|
||||||
|
"""Retrieve the owner."""
|
||||||
|
users = await self.async_get_users()
|
||||||
|
return next((user for user in users if user.is_owner), None)
|
||||||
|
|
||||||
|
async def async_get_group(self, group_id: str) -> models.Group | None:
|
||||||
|
"""Retrieve all groups."""
|
||||||
|
return await self._store.async_get_group(group_id)
|
||||||
|
|
||||||
|
async def async_get_user_by_credentials(
|
||||||
|
self, credentials: models.Credentials
|
||||||
|
) -> models.User | None:
|
||||||
|
"""Get a user by credential, return None if not found."""
|
||||||
|
for user in await self.async_get_users():
|
||||||
|
for creds in user.credentials:
|
||||||
|
if creds.id == credentials.id:
|
||||||
|
return user
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def async_create_system_user(
|
||||||
|
self,
|
||||||
|
name: str,
|
||||||
|
*,
|
||||||
|
group_ids: list[str] | None = None,
|
||||||
|
local_only: bool | None = None,
|
||||||
|
) -> models.User:
|
||||||
|
"""Create a system user."""
|
||||||
|
user = await self._store.async_create_user(
|
||||||
|
name=name,
|
||||||
|
system_generated=True,
|
||||||
|
is_active=True,
|
||||||
|
group_ids=group_ids or [],
|
||||||
|
local_only=local_only,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.hass.bus.async_fire(EVENT_USER_ADDED, {"user_id": user.id})
|
||||||
|
|
||||||
|
return user
|
||||||
|
|
||||||
|
async def async_create_user(
|
||||||
|
self,
|
||||||
|
name: str,
|
||||||
|
*,
|
||||||
|
group_ids: list[str] | None = None,
|
||||||
|
local_only: bool | None = None,
|
||||||
|
) -> models.User:
|
||||||
|
"""Create a user."""
|
||||||
|
kwargs: dict[str, Any] = {
|
||||||
|
"name": name,
|
||||||
|
"is_active": True,
|
||||||
|
"group_ids": group_ids or [],
|
||||||
|
"local_only": local_only,
|
||||||
|
}
|
||||||
|
|
||||||
|
if await self._user_should_be_owner():
|
||||||
|
kwargs["is_owner"] = True
|
||||||
|
|
||||||
|
user = await self._store.async_create_user(**kwargs)
|
||||||
|
|
||||||
|
self.hass.bus.async_fire(EVENT_USER_ADDED, {"user_id": user.id})
|
||||||
|
|
||||||
|
return user
|
||||||
|
|
||||||
|
async def async_get_or_create_user(
|
||||||
|
self, credentials: models.Credentials
|
||||||
|
) -> models.User:
|
||||||
|
"""Get or create a user."""
|
||||||
|
if not credentials.is_new:
|
||||||
|
user = await self.async_get_user_by_credentials(credentials)
|
||||||
|
if user is None:
|
||||||
|
raise ValueError("Unable to find the user.")
|
||||||
|
return user
|
||||||
|
|
||||||
|
auth_provider = self._async_get_auth_provider(credentials)
|
||||||
|
|
||||||
|
if auth_provider is None:
|
||||||
|
raise RuntimeError("Credential with unknown provider encountered")
|
||||||
|
|
||||||
|
info = await auth_provider.async_user_meta_for_credentials(credentials)
|
||||||
|
|
||||||
|
user = await self._store.async_create_user(
|
||||||
|
credentials=credentials,
|
||||||
|
name=info.name,
|
||||||
|
is_active=info.is_active,
|
||||||
|
group_ids=[GROUP_ID_ADMIN if info.group is None else info.group],
|
||||||
|
local_only=info.local_only,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.hass.bus.async_fire(EVENT_USER_ADDED, {"user_id": user.id})
|
||||||
|
|
||||||
|
return user
|
||||||
|
|
||||||
|
async def async_link_user(
|
||||||
|
self, user: models.User, credentials: models.Credentials
|
||||||
|
) -> None:
|
||||||
|
"""Link credentials to an existing user."""
|
||||||
|
linked_user = await self.async_get_user_by_credentials(credentials)
|
||||||
|
if linked_user == user:
|
||||||
|
return
|
||||||
|
if linked_user is not None:
|
||||||
|
raise ValueError("Credential is already linked to a user")
|
||||||
|
|
||||||
|
await self._store.async_link_user(user, credentials)
|
||||||
|
|
||||||
|
async def async_remove_user(self, user: models.User) -> None:
|
||||||
|
"""Remove a user."""
|
||||||
|
tasks = [
|
||||||
|
self.async_remove_credentials(credentials)
|
||||||
|
for credentials in user.credentials
|
||||||
|
]
|
||||||
|
|
||||||
|
if tasks:
|
||||||
|
await asyncio.gather(*tasks)
|
||||||
|
|
||||||
|
await self._store.async_remove_user(user)
|
||||||
|
|
||||||
|
self.hass.bus.async_fire(EVENT_USER_REMOVED, {"user_id": user.id})
|
||||||
|
|
||||||
|
async def async_update_user(
|
||||||
|
self,
|
||||||
|
user: models.User,
|
||||||
|
name: str | None = None,
|
||||||
|
is_active: bool | None = None,
|
||||||
|
group_ids: list[str] | None = None,
|
||||||
|
local_only: bool | None = None,
|
||||||
|
) -> None:
|
||||||
|
"""Update a user."""
|
||||||
|
kwargs: dict[str, Any] = {
|
||||||
|
attr_name: value
|
||||||
|
for attr_name, value in (
|
||||||
|
("name", name),
|
||||||
|
("group_ids", group_ids),
|
||||||
|
("local_only", local_only),
|
||||||
|
)
|
||||||
|
if value is not None
|
||||||
|
}
|
||||||
|
await self._store.async_update_user(user, **kwargs)
|
||||||
|
|
||||||
|
if is_active is not None:
|
||||||
|
if is_active is True:
|
||||||
|
await self.async_activate_user(user)
|
||||||
|
else:
|
||||||
|
await self.async_deactivate_user(user)
|
||||||
|
|
||||||
|
self.hass.bus.async_fire(EVENT_USER_UPDATED, {"user_id": user.id})
|
||||||
|
|
||||||
|
@callback
|
||||||
|
def async_update_user_credentials_data(
|
||||||
|
self, credentials: models.Credentials, data: dict[str, Any]
|
||||||
|
) -> None:
|
||||||
|
"""Update credentials data."""
|
||||||
|
self._store.async_update_user_credentials_data(credentials, data=data)
|
||||||
|
|
||||||
|
async def async_activate_user(self, user: models.User) -> None:
|
||||||
|
"""Activate a user."""
|
||||||
|
await self._store.async_activate_user(user)
|
||||||
|
|
||||||
|
async def async_deactivate_user(self, user: models.User) -> None:
|
||||||
|
"""Deactivate a user."""
|
||||||
|
if user.is_owner:
|
||||||
|
raise ValueError("Unable to deactivate the owner")
|
||||||
|
await self._store.async_deactivate_user(user)
|
||||||
|
|
||||||
|
async def async_remove_credentials(self, credentials: models.Credentials) -> None:
|
||||||
|
"""Remove credentials."""
|
||||||
|
provider = self._async_get_auth_provider(credentials)
|
||||||
|
|
||||||
|
if provider is not None and hasattr(provider, "async_will_remove_credentials"):
|
||||||
|
await provider.async_will_remove_credentials(credentials)
|
||||||
|
|
||||||
|
await self._store.async_remove_credentials(credentials)
|
||||||
|
|
||||||
|
async def async_enable_user_mfa(
|
||||||
|
self, user: models.User, mfa_module_id: str, data: Any
|
||||||
|
) -> None:
|
||||||
|
"""Enable a multi-factor auth module for user."""
|
||||||
|
if user.system_generated:
|
||||||
|
raise ValueError(
|
||||||
|
"System generated users cannot enable multi-factor auth module."
|
||||||
|
)
|
||||||
|
|
||||||
|
if (module := self.get_auth_mfa_module(mfa_module_id)) is None:
|
||||||
|
raise ValueError(f"Unable find multi-factor auth module: {mfa_module_id}")
|
||||||
|
|
||||||
|
await module.async_setup_user(user.id, data)
|
||||||
|
|
||||||
|
async def async_disable_user_mfa(
|
||||||
|
self, user: models.User, mfa_module_id: str
|
||||||
|
) -> None:
|
||||||
|
"""Disable a multi-factor auth module for user."""
|
||||||
|
if user.system_generated:
|
||||||
|
raise ValueError(
|
||||||
|
"System generated users cannot disable multi-factor auth module."
|
||||||
|
)
|
||||||
|
|
||||||
|
if (module := self.get_auth_mfa_module(mfa_module_id)) is None:
|
||||||
|
raise ValueError(f"Unable find multi-factor auth module: {mfa_module_id}")
|
||||||
|
|
||||||
|
await module.async_depose_user(user.id)
|
||||||
|
|
||||||
|
async def async_get_enabled_mfa(self, user: models.User) -> dict[str, str]:
|
||||||
|
"""List enabled mfa modules for user."""
|
||||||
|
modules: dict[str, str] = OrderedDict()
|
||||||
|
for module_id, module in self._mfa_modules.items():
|
||||||
|
if await module.async_is_user_setup(user.id):
|
||||||
|
modules[module_id] = module.name
|
||||||
|
return modules
|
||||||
|
|
||||||
|
async def async_create_refresh_token(
|
||||||
|
self,
|
||||||
|
user: models.User,
|
||||||
|
client_id: str | None = None,
|
||||||
|
client_name: str | None = None,
|
||||||
|
client_icon: str | None = None,
|
||||||
|
token_type: str | None = None,
|
||||||
|
access_token_expiration: timedelta = ACCESS_TOKEN_EXPIRATION,
|
||||||
|
credential: models.Credentials | None = None,
|
||||||
|
) -> models.RefreshToken:
|
||||||
|
"""Create a new refresh token for a user."""
|
||||||
|
if not user.is_active:
|
||||||
|
raise ValueError("User is not active")
|
||||||
|
|
||||||
|
if user.system_generated and client_id is not None:
|
||||||
|
raise ValueError(
|
||||||
|
"System generated users cannot have refresh tokens connected "
|
||||||
|
"to a client."
|
||||||
|
)
|
||||||
|
|
||||||
|
if token_type is None:
|
||||||
|
if user.system_generated:
|
||||||
|
token_type = models.TOKEN_TYPE_SYSTEM
|
||||||
|
else:
|
||||||
|
token_type = models.TOKEN_TYPE_NORMAL
|
||||||
|
|
||||||
|
if token_type is models.TOKEN_TYPE_NORMAL:
|
||||||
|
expire_at = time.time() + REFRESH_TOKEN_EXPIRATION
|
||||||
|
else:
|
||||||
|
expire_at = None
|
||||||
|
|
||||||
|
if user.system_generated != (token_type == models.TOKEN_TYPE_SYSTEM):
|
||||||
|
raise ValueError(
|
||||||
|
"System generated users can only have system type refresh tokens"
|
||||||
|
)
|
||||||
|
|
||||||
|
if token_type == models.TOKEN_TYPE_NORMAL and client_id is None:
|
||||||
|
raise ValueError("Client is required to generate a refresh token.")
|
||||||
|
|
||||||
|
if (
|
||||||
|
token_type == models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN
|
||||||
|
and client_name is None
|
||||||
|
):
|
||||||
|
raise ValueError("Client_name is required for long-lived access token")
|
||||||
|
|
||||||
|
if token_type == models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN:
|
||||||
|
for token in user.refresh_tokens.values():
|
||||||
|
if (
|
||||||
|
token.client_name == client_name
|
||||||
|
and token.token_type == models.TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN
|
||||||
|
):
|
||||||
|
# Each client_name can only have one
|
||||||
|
# long_lived_access_token type of refresh token
|
||||||
|
raise ValueError(f"{client_name} already exists")
|
||||||
|
|
||||||
|
return await self._store.async_create_refresh_token(
|
||||||
|
user,
|
||||||
|
client_id,
|
||||||
|
client_name,
|
||||||
|
client_icon,
|
||||||
|
token_type,
|
||||||
|
access_token_expiration,
|
||||||
|
expire_at,
|
||||||
|
credential,
|
||||||
|
)
|
||||||
|
|
||||||
|
@callback
|
||||||
|
def async_get_refresh_token(self, token_id: str) -> models.RefreshToken | None:
|
||||||
|
"""Get refresh token by id."""
|
||||||
|
return self._store.async_get_refresh_token(token_id)
|
||||||
|
|
||||||
|
@callback
|
||||||
|
def async_get_refresh_token_by_token(
|
||||||
|
self, token: str
|
||||||
|
) -> models.RefreshToken | None:
|
||||||
|
"""Get refresh token by token."""
|
||||||
|
return self._store.async_get_refresh_token_by_token(token)
|
||||||
|
|
||||||
|
@callback
|
||||||
|
def async_remove_refresh_token(self, refresh_token: models.RefreshToken) -> None:
|
||||||
|
"""Delete a refresh token."""
|
||||||
|
self._store.async_remove_refresh_token(refresh_token)
|
||||||
|
|
||||||
|
callbacks = self._revoke_callbacks.pop(refresh_token.id, ())
|
||||||
|
for revoke_callback in callbacks:
|
||||||
|
revoke_callback()
|
||||||
|
|
||||||
|
@callback
|
||||||
|
def async_set_expiry(
|
||||||
|
self, refresh_token: models.RefreshToken, *, enable_expiry: bool
|
||||||
|
) -> None:
|
||||||
|
"""Enable or disable expiry of a refresh token."""
|
||||||
|
self._store.async_set_expiry(refresh_token, enable_expiry=enable_expiry)
|
||||||
|
|
||||||
|
@callback
|
||||||
|
def _async_remove_expired_refresh_tokens(self, _: datetime | None = None) -> None:
|
||||||
|
"""Remove expired refresh tokens."""
|
||||||
|
now = time.time()
|
||||||
|
for token in self._store.async_get_refresh_tokens():
|
||||||
|
if (expire_at := token.expire_at) is not None and expire_at <= now:
|
||||||
|
self.async_remove_refresh_token(token)
|
||||||
|
self._async_track_next_refresh_token_expiration()
|
||||||
|
|
||||||
|
@callback
|
||||||
|
def _async_track_next_refresh_token_expiration(self) -> None:
|
||||||
|
"""Initialise all token expiration scheduled tasks."""
|
||||||
|
next_expiration = time.time() + REFRESH_TOKEN_EXPIRATION
|
||||||
|
for token in self._store.async_get_refresh_tokens():
|
||||||
|
if (
|
||||||
|
expire_at := token.expire_at
|
||||||
|
) is not None and expire_at < next_expiration:
|
||||||
|
next_expiration = expire_at
|
||||||
|
|
||||||
|
self._expire_callback = async_track_point_in_utc_time(
|
||||||
|
self.hass,
|
||||||
|
self._remove_expired_job,
|
||||||
|
dt_util.utc_from_timestamp(next_expiration),
|
||||||
|
)
|
||||||
|
|
||||||
|
@callback
|
||||||
|
def _async_cancel_expiration_schedule(self) -> None:
|
||||||
|
"""Cancel tracking of expired refresh tokens."""
|
||||||
|
if self._expire_callback:
|
||||||
|
self._expire_callback()
|
||||||
|
self._expire_callback = None
|
||||||
|
|
||||||
|
@callback
|
||||||
|
def _async_unregister(
|
||||||
|
self, callbacks: set[CALLBACK_TYPE], callback_: CALLBACK_TYPE
|
||||||
|
) -> None:
|
||||||
|
"""Unregister a callback."""
|
||||||
|
callbacks.remove(callback_)
|
||||||
|
|
||||||
|
@callback
|
||||||
|
def async_register_revoke_token_callback(
|
||||||
|
self, refresh_token_id: str, revoke_callback: CALLBACK_TYPE
|
||||||
|
) -> CALLBACK_TYPE:
|
||||||
|
"""Register a callback to be called when the refresh token id is revoked."""
|
||||||
|
if refresh_token_id not in self._revoke_callbacks:
|
||||||
|
self._revoke_callbacks[refresh_token_id] = set()
|
||||||
|
|
||||||
|
callbacks = self._revoke_callbacks[refresh_token_id]
|
||||||
|
callbacks.add(revoke_callback)
|
||||||
|
return partial(self._async_unregister, callbacks, revoke_callback)
|
||||||
|
|
||||||
|
@callback
|
||||||
|
def async_create_access_token(
|
||||||
|
self, refresh_token: models.RefreshToken, remote_ip: str | None = None
|
||||||
|
) -> str:
|
||||||
|
"""Create a new access token."""
|
||||||
|
self.async_validate_refresh_token(refresh_token, remote_ip)
|
||||||
|
|
||||||
|
self._store.async_log_refresh_token_usage(refresh_token, remote_ip)
|
||||||
|
|
||||||
|
now = int(time.time())
|
||||||
|
expire_seconds = int(refresh_token.access_token_expiration.total_seconds())
|
||||||
|
return jwt.encode(
|
||||||
|
{
|
||||||
|
"iss": refresh_token.id,
|
||||||
|
"iat": now,
|
||||||
|
"exp": now + expire_seconds,
|
||||||
|
},
|
||||||
|
refresh_token.jwt_key,
|
||||||
|
algorithm="HS256",
|
||||||
|
)
|
||||||
|
|
||||||
|
@callback
|
||||||
|
def _async_resolve_provider(
|
||||||
|
self, refresh_token: models.RefreshToken
|
||||||
|
) -> AuthProvider | None:
|
||||||
|
"""Get the auth provider for the given refresh token.
|
||||||
|
|
||||||
|
Raises an exception if the expected provider is no longer available or return
|
||||||
|
None if no provider was expected for this refresh token.
|
||||||
|
"""
|
||||||
|
if refresh_token.credential is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
provider = self.get_auth_provider(
|
||||||
|
refresh_token.credential.auth_provider_type,
|
||||||
|
refresh_token.credential.auth_provider_id,
|
||||||
|
)
|
||||||
|
if provider is None:
|
||||||
|
raise InvalidProvider(
|
||||||
|
f"Auth provider {refresh_token.credential.auth_provider_type},"
|
||||||
|
f" {refresh_token.credential.auth_provider_id} not available"
|
||||||
|
)
|
||||||
|
return provider
|
||||||
|
|
||||||
|
@callback
|
||||||
|
def async_validate_refresh_token(
|
||||||
|
self, refresh_token: models.RefreshToken, remote_ip: str | None = None
|
||||||
|
) -> None:
|
||||||
|
"""Validate that a refresh token is usable.
|
||||||
|
|
||||||
|
Will raise InvalidAuthError on errors.
|
||||||
|
"""
|
||||||
|
if provider := self._async_resolve_provider(refresh_token):
|
||||||
|
provider.async_validate_refresh_token(refresh_token, remote_ip)
|
||||||
|
|
||||||
|
@callback
|
||||||
|
def async_validate_access_token(self, token: str) -> models.RefreshToken | None:
|
||||||
|
"""Return refresh token if an access token is valid."""
|
||||||
|
try:
|
||||||
|
unverif_claims = jwt_wrapper.unverified_hs256_token_decode(token)
|
||||||
|
except jwt.InvalidTokenError:
|
||||||
|
return None
|
||||||
|
|
||||||
|
refresh_token = self.async_get_refresh_token(
|
||||||
|
cast(str, unverif_claims.get("iss"))
|
||||||
|
)
|
||||||
|
|
||||||
|
if refresh_token is None:
|
||||||
|
jwt_key = ""
|
||||||
|
issuer = ""
|
||||||
|
else:
|
||||||
|
jwt_key = refresh_token.jwt_key
|
||||||
|
issuer = refresh_token.id
|
||||||
|
|
||||||
|
try:
|
||||||
|
jwt_wrapper.verify_and_decode(
|
||||||
|
token, jwt_key, leeway=10, issuer=issuer, algorithms=["HS256"]
|
||||||
|
)
|
||||||
|
except jwt.InvalidTokenError:
|
||||||
|
return None
|
||||||
|
|
||||||
|
if refresh_token is None or not refresh_token.user.is_active:
|
||||||
|
return None
|
||||||
|
|
||||||
|
return refresh_token
|
||||||
|
|
||||||
|
@callback
|
||||||
|
def _async_get_auth_provider(
|
||||||
|
self, credentials: models.Credentials
|
||||||
|
) -> AuthProvider | None:
|
||||||
|
"""Get auth provider from a set of credentials."""
|
||||||
|
auth_provider_key = (
|
||||||
|
credentials.auth_provider_type,
|
||||||
|
credentials.auth_provider_id,
|
||||||
|
)
|
||||||
|
return self._providers.get(auth_provider_key)
|
||||||
|
|
||||||
|
async def _user_should_be_owner(self) -> bool:
|
||||||
|
"""Determine if user should be owner.
|
||||||
|
|
||||||
|
A user should be an owner if it is the first non-system user that is
|
||||||
|
being created.
|
||||||
|
"""
|
||||||
|
for user in await self._store.async_get_users():
|
||||||
|
if not user.system_generated:
|
||||||
|
return False
|
||||||
|
|
||||||
|
return True
|
||||||
637
home-assistant/homeassistant/auth/auth_store.py
Normal file
637
home-assistant/homeassistant/auth/auth_store.py
Normal file
@@ -0,0 +1,637 @@
|
|||||||
|
"""Storage for auth models."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import timedelta
|
||||||
|
import hmac
|
||||||
|
import itertools
|
||||||
|
from logging import getLogger
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from homeassistant.core import HomeAssistant, callback
|
||||||
|
from homeassistant.helpers import device_registry as dr, entity_registry as er
|
||||||
|
from homeassistant.helpers.storage import Store
|
||||||
|
from homeassistant.util import dt as dt_util
|
||||||
|
|
||||||
|
from . import models
|
||||||
|
from .const import (
|
||||||
|
ACCESS_TOKEN_EXPIRATION,
|
||||||
|
GROUP_ID_ADMIN,
|
||||||
|
GROUP_ID_READ_ONLY,
|
||||||
|
GROUP_ID_USER,
|
||||||
|
REFRESH_TOKEN_EXPIRATION,
|
||||||
|
)
|
||||||
|
from .permissions import system_policies
|
||||||
|
from .permissions.models import PermissionLookup
|
||||||
|
from .permissions.types import PolicyType
|
||||||
|
|
||||||
|
STORAGE_VERSION = 1
|
||||||
|
STORAGE_KEY = "auth"
|
||||||
|
GROUP_NAME_ADMIN = "Administrators"
|
||||||
|
GROUP_NAME_USER = "Users"
|
||||||
|
GROUP_NAME_READ_ONLY = "Read Only"
|
||||||
|
|
||||||
|
# We always save the auth store after we load it since
|
||||||
|
# we may migrate data and do not want to have to do it again
|
||||||
|
# but we don't want to do it during startup so we schedule
|
||||||
|
# the first save 5 minutes out knowing something else may
|
||||||
|
# want to save the auth store before then, and since Storage
|
||||||
|
# will honor the lower of the two delays, it will save it
|
||||||
|
# faster if something else saves it.
|
||||||
|
INITIAL_LOAD_SAVE_DELAY = 300
|
||||||
|
|
||||||
|
DEFAULT_SAVE_DELAY = 1
|
||||||
|
|
||||||
|
|
||||||
|
class AuthStore:
|
||||||
|
"""Stores authentication info.
|
||||||
|
|
||||||
|
Any mutation to an object should happen inside the auth store.
|
||||||
|
|
||||||
|
The auth store is lazy. It won't load the data from disk until a method is
|
||||||
|
called that needs it.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, hass: HomeAssistant) -> None:
|
||||||
|
"""Initialize the auth store."""
|
||||||
|
self.hass = hass
|
||||||
|
self._loaded = False
|
||||||
|
self._users: dict[str, models.User] = None # type: ignore[assignment]
|
||||||
|
self._groups: dict[str, models.Group] = None # type: ignore[assignment]
|
||||||
|
self._perm_lookup: PermissionLookup = None # type: ignore[assignment]
|
||||||
|
self._store = Store[dict[str, list[dict[str, Any]]]](
|
||||||
|
hass, STORAGE_VERSION, STORAGE_KEY, private=True, atomic_writes=True
|
||||||
|
)
|
||||||
|
self._token_id_to_user_id: dict[str, str] = {}
|
||||||
|
|
||||||
|
async def async_get_groups(self) -> list[models.Group]:
|
||||||
|
"""Retrieve all users."""
|
||||||
|
return list(self._groups.values())
|
||||||
|
|
||||||
|
async def async_get_group(self, group_id: str) -> models.Group | None:
|
||||||
|
"""Retrieve all users."""
|
||||||
|
return self._groups.get(group_id)
|
||||||
|
|
||||||
|
async def async_get_users(self) -> list[models.User]:
|
||||||
|
"""Retrieve all users."""
|
||||||
|
return list(self._users.values())
|
||||||
|
|
||||||
|
async def async_get_user(self, user_id: str) -> models.User | None:
|
||||||
|
"""Retrieve a user by id."""
|
||||||
|
return self._users.get(user_id)
|
||||||
|
|
||||||
|
async def async_create_user(
|
||||||
|
self,
|
||||||
|
name: str | None,
|
||||||
|
is_owner: bool | None = None,
|
||||||
|
is_active: bool | None = None,
|
||||||
|
system_generated: bool | None = None,
|
||||||
|
credentials: models.Credentials | None = None,
|
||||||
|
group_ids: list[str] | None = None,
|
||||||
|
local_only: bool | None = None,
|
||||||
|
) -> models.User:
|
||||||
|
"""Create a new user."""
|
||||||
|
groups = []
|
||||||
|
for group_id in group_ids or []:
|
||||||
|
if (group := self._groups.get(group_id)) is None:
|
||||||
|
raise ValueError(f"Invalid group specified {group_id}")
|
||||||
|
groups.append(group)
|
||||||
|
|
||||||
|
kwargs: dict[str, Any] = {
|
||||||
|
"name": name,
|
||||||
|
# Until we get group management, we just put everyone in the
|
||||||
|
# same group.
|
||||||
|
"groups": groups,
|
||||||
|
"perm_lookup": self._perm_lookup,
|
||||||
|
}
|
||||||
|
|
||||||
|
kwargs.update(
|
||||||
|
{
|
||||||
|
attr_name: value
|
||||||
|
for attr_name, value in (
|
||||||
|
("is_owner", is_owner),
|
||||||
|
("is_active", is_active),
|
||||||
|
("local_only", local_only),
|
||||||
|
("system_generated", system_generated),
|
||||||
|
)
|
||||||
|
if value is not None
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
new_user = models.User(**kwargs)
|
||||||
|
|
||||||
|
self._users[new_user.id] = new_user
|
||||||
|
|
||||||
|
if credentials is None:
|
||||||
|
self._async_schedule_save()
|
||||||
|
return new_user
|
||||||
|
|
||||||
|
# Saving is done inside the link.
|
||||||
|
await self.async_link_user(new_user, credentials)
|
||||||
|
return new_user
|
||||||
|
|
||||||
|
async def async_link_user(
|
||||||
|
self, user: models.User, credentials: models.Credentials
|
||||||
|
) -> None:
|
||||||
|
"""Add credentials to an existing user."""
|
||||||
|
user.credentials.append(credentials)
|
||||||
|
self._async_schedule_save()
|
||||||
|
credentials.is_new = False
|
||||||
|
|
||||||
|
async def async_remove_user(self, user: models.User) -> None:
|
||||||
|
"""Remove a user."""
|
||||||
|
user = self._users.pop(user.id)
|
||||||
|
for refresh_token_id in user.refresh_tokens:
|
||||||
|
del self._token_id_to_user_id[refresh_token_id]
|
||||||
|
user.refresh_tokens.clear()
|
||||||
|
self._async_schedule_save()
|
||||||
|
|
||||||
|
async def async_update_user(
|
||||||
|
self,
|
||||||
|
user: models.User,
|
||||||
|
name: str | None = None,
|
||||||
|
is_active: bool | None = None,
|
||||||
|
group_ids: list[str] | None = None,
|
||||||
|
local_only: bool | None = None,
|
||||||
|
) -> None:
|
||||||
|
"""Update a user."""
|
||||||
|
if group_ids is not None:
|
||||||
|
groups = []
|
||||||
|
for grid in group_ids:
|
||||||
|
if (group := self._groups.get(grid)) is None:
|
||||||
|
raise ValueError("Invalid group specified.")
|
||||||
|
groups.append(group)
|
||||||
|
|
||||||
|
user.groups = groups
|
||||||
|
|
||||||
|
for attr_name, value in (
|
||||||
|
("name", name),
|
||||||
|
("is_active", is_active),
|
||||||
|
("local_only", local_only),
|
||||||
|
):
|
||||||
|
if value is not None:
|
||||||
|
setattr(user, attr_name, value)
|
||||||
|
|
||||||
|
self._async_schedule_save()
|
||||||
|
|
||||||
|
async def async_activate_user(self, user: models.User) -> None:
|
||||||
|
"""Activate a user."""
|
||||||
|
user.is_active = True
|
||||||
|
self._async_schedule_save()
|
||||||
|
|
||||||
|
async def async_deactivate_user(self, user: models.User) -> None:
|
||||||
|
"""Activate a user."""
|
||||||
|
user.is_active = False
|
||||||
|
self._async_schedule_save()
|
||||||
|
|
||||||
|
async def async_remove_credentials(self, credentials: models.Credentials) -> None:
|
||||||
|
"""Remove credentials."""
|
||||||
|
for user in self._users.values():
|
||||||
|
found = None
|
||||||
|
|
||||||
|
for index, cred in enumerate(user.credentials):
|
||||||
|
if cred is credentials:
|
||||||
|
found = index
|
||||||
|
break
|
||||||
|
|
||||||
|
if found is not None:
|
||||||
|
user.credentials.pop(found)
|
||||||
|
break
|
||||||
|
|
||||||
|
self._async_schedule_save()
|
||||||
|
|
||||||
|
async def async_create_refresh_token(
|
||||||
|
self,
|
||||||
|
user: models.User,
|
||||||
|
client_id: str | None = None,
|
||||||
|
client_name: str | None = None,
|
||||||
|
client_icon: str | None = None,
|
||||||
|
token_type: str = models.TOKEN_TYPE_NORMAL,
|
||||||
|
access_token_expiration: timedelta = ACCESS_TOKEN_EXPIRATION,
|
||||||
|
expire_at: float | None = None,
|
||||||
|
credential: models.Credentials | None = None,
|
||||||
|
) -> models.RefreshToken:
|
||||||
|
"""Create a new token for a user."""
|
||||||
|
kwargs: dict[str, Any] = {
|
||||||
|
"user": user,
|
||||||
|
"client_id": client_id,
|
||||||
|
"token_type": token_type,
|
||||||
|
"access_token_expiration": access_token_expiration,
|
||||||
|
"expire_at": expire_at,
|
||||||
|
"credential": credential,
|
||||||
|
}
|
||||||
|
if client_name:
|
||||||
|
kwargs["client_name"] = client_name
|
||||||
|
if client_icon:
|
||||||
|
kwargs["client_icon"] = client_icon
|
||||||
|
|
||||||
|
refresh_token = models.RefreshToken(**kwargs)
|
||||||
|
token_id = refresh_token.id
|
||||||
|
user.refresh_tokens[token_id] = refresh_token
|
||||||
|
self._token_id_to_user_id[token_id] = user.id
|
||||||
|
|
||||||
|
self._async_schedule_save()
|
||||||
|
return refresh_token
|
||||||
|
|
||||||
|
@callback
|
||||||
|
def async_remove_refresh_token(self, refresh_token: models.RefreshToken) -> None:
|
||||||
|
"""Remove a refresh token."""
|
||||||
|
refresh_token_id = refresh_token.id
|
||||||
|
if user_id := self._token_id_to_user_id.get(refresh_token_id):
|
||||||
|
del self._users[user_id].refresh_tokens[refresh_token_id]
|
||||||
|
del self._token_id_to_user_id[refresh_token_id]
|
||||||
|
self._async_schedule_save()
|
||||||
|
|
||||||
|
@callback
|
||||||
|
def async_get_refresh_token(self, token_id: str) -> models.RefreshToken | None:
|
||||||
|
"""Get refresh token by id."""
|
||||||
|
if user_id := self._token_id_to_user_id.get(token_id):
|
||||||
|
return self._users[user_id].refresh_tokens.get(token_id)
|
||||||
|
return None
|
||||||
|
|
||||||
|
@callback
|
||||||
|
def async_get_refresh_token_by_token(
|
||||||
|
self, token: str
|
||||||
|
) -> models.RefreshToken | None:
|
||||||
|
"""Get refresh token by token."""
|
||||||
|
found = None
|
||||||
|
|
||||||
|
for user in self._users.values():
|
||||||
|
for refresh_token in user.refresh_tokens.values():
|
||||||
|
if hmac.compare_digest(refresh_token.token, token):
|
||||||
|
found = refresh_token
|
||||||
|
|
||||||
|
return found
|
||||||
|
|
||||||
|
@callback
|
||||||
|
def async_get_refresh_tokens(self) -> list[models.RefreshToken]:
|
||||||
|
"""Get all refresh tokens."""
|
||||||
|
return list(
|
||||||
|
itertools.chain.from_iterable(
|
||||||
|
user.refresh_tokens.values() for user in self._users.values()
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
@callback
|
||||||
|
def async_log_refresh_token_usage(
|
||||||
|
self, refresh_token: models.RefreshToken, remote_ip: str | None = None
|
||||||
|
) -> None:
|
||||||
|
"""Update refresh token last used information."""
|
||||||
|
refresh_token.last_used_at = dt_util.utcnow()
|
||||||
|
refresh_token.last_used_ip = remote_ip
|
||||||
|
if refresh_token.expire_at:
|
||||||
|
refresh_token.expire_at = (
|
||||||
|
refresh_token.last_used_at.timestamp() + REFRESH_TOKEN_EXPIRATION
|
||||||
|
)
|
||||||
|
self._async_schedule_save()
|
||||||
|
|
||||||
|
@callback
|
||||||
|
def async_set_expiry(
|
||||||
|
self, refresh_token: models.RefreshToken, *, enable_expiry: bool
|
||||||
|
) -> None:
|
||||||
|
"""Enable or disable expiry of a refresh token."""
|
||||||
|
if enable_expiry:
|
||||||
|
if refresh_token.expire_at is None:
|
||||||
|
refresh_token.expire_at = (
|
||||||
|
refresh_token.last_used_at or dt_util.utcnow()
|
||||||
|
).timestamp() + REFRESH_TOKEN_EXPIRATION
|
||||||
|
self._async_schedule_save()
|
||||||
|
else:
|
||||||
|
refresh_token.expire_at = None
|
||||||
|
self._async_schedule_save()
|
||||||
|
|
||||||
|
@callback
|
||||||
|
def async_update_user_credentials_data(
|
||||||
|
self, credentials: models.Credentials, data: dict[str, Any]
|
||||||
|
) -> None:
|
||||||
|
"""Update credentials data."""
|
||||||
|
credentials.data = data
|
||||||
|
self._async_schedule_save()
|
||||||
|
|
||||||
|
async def async_load(self) -> None: # noqa: C901
|
||||||
|
"""Load the users."""
|
||||||
|
if self._loaded:
|
||||||
|
raise RuntimeError("Auth storage is already loaded")
|
||||||
|
self._loaded = True
|
||||||
|
|
||||||
|
dev_reg = dr.async_get(self.hass)
|
||||||
|
ent_reg = er.async_get(self.hass)
|
||||||
|
data = await self._store.async_load()
|
||||||
|
|
||||||
|
perm_lookup = PermissionLookup(ent_reg, dev_reg)
|
||||||
|
self._perm_lookup = perm_lookup
|
||||||
|
|
||||||
|
if data is None or not isinstance(data, dict):
|
||||||
|
self._set_defaults()
|
||||||
|
return
|
||||||
|
|
||||||
|
users: dict[str, models.User] = {}
|
||||||
|
groups: dict[str, models.Group] = {}
|
||||||
|
credentials: dict[str, models.Credentials] = {}
|
||||||
|
|
||||||
|
# Soft-migrating data as we load. We are going to make sure we have a
|
||||||
|
# read only group and an admin group. There are two states that we can
|
||||||
|
# migrate from:
|
||||||
|
# 1. Data from a recent version which has a single group without policy
|
||||||
|
# 2. Data from old version which has no groups
|
||||||
|
has_admin_group = False
|
||||||
|
has_user_group = False
|
||||||
|
has_read_only_group = False
|
||||||
|
group_without_policy = None
|
||||||
|
|
||||||
|
# When creating objects we mention each attribute explicitly. This
|
||||||
|
# prevents crashing if user rolls back HA version after a new property
|
||||||
|
# was added.
|
||||||
|
|
||||||
|
for group_dict in data.get("groups", []):
|
||||||
|
policy: PolicyType | None = None
|
||||||
|
|
||||||
|
if group_dict["id"] == GROUP_ID_ADMIN:
|
||||||
|
has_admin_group = True
|
||||||
|
|
||||||
|
name = GROUP_NAME_ADMIN
|
||||||
|
policy = system_policies.ADMIN_POLICY
|
||||||
|
system_generated = True
|
||||||
|
|
||||||
|
elif group_dict["id"] == GROUP_ID_USER:
|
||||||
|
has_user_group = True
|
||||||
|
|
||||||
|
name = GROUP_NAME_USER
|
||||||
|
policy = system_policies.USER_POLICY
|
||||||
|
system_generated = True
|
||||||
|
|
||||||
|
elif group_dict["id"] == GROUP_ID_READ_ONLY:
|
||||||
|
has_read_only_group = True
|
||||||
|
|
||||||
|
name = GROUP_NAME_READ_ONLY
|
||||||
|
policy = system_policies.READ_ONLY_POLICY
|
||||||
|
system_generated = True
|
||||||
|
|
||||||
|
else:
|
||||||
|
name = group_dict["name"]
|
||||||
|
policy = group_dict.get("policy")
|
||||||
|
system_generated = False
|
||||||
|
|
||||||
|
# We don't want groups without a policy that are not system groups
|
||||||
|
# This is part of migrating from state 1
|
||||||
|
if policy is None:
|
||||||
|
group_without_policy = group_dict["id"]
|
||||||
|
continue
|
||||||
|
|
||||||
|
groups[group_dict["id"]] = models.Group(
|
||||||
|
id=group_dict["id"],
|
||||||
|
name=name,
|
||||||
|
policy=policy,
|
||||||
|
system_generated=system_generated,
|
||||||
|
)
|
||||||
|
|
||||||
|
# If there are no groups, add all existing users to the admin group.
|
||||||
|
# This is part of migrating from state 2
|
||||||
|
migrate_users_to_admin_group = not groups and group_without_policy is None
|
||||||
|
|
||||||
|
# If we find a no_policy_group, we need to migrate all users to the
|
||||||
|
# admin group. We only do this if there are no other groups, as is
|
||||||
|
# the expected state. If not expected state, not marking people admin.
|
||||||
|
# This is part of migrating from state 1
|
||||||
|
if groups and group_without_policy is not None:
|
||||||
|
group_without_policy = None
|
||||||
|
|
||||||
|
# This is part of migrating from state 1 and 2
|
||||||
|
if not has_admin_group:
|
||||||
|
admin_group = _system_admin_group()
|
||||||
|
groups[admin_group.id] = admin_group
|
||||||
|
|
||||||
|
# This is part of migrating from state 1 and 2
|
||||||
|
if not has_read_only_group:
|
||||||
|
read_only_group = _system_read_only_group()
|
||||||
|
groups[read_only_group.id] = read_only_group
|
||||||
|
|
||||||
|
if not has_user_group:
|
||||||
|
user_group = _system_user_group()
|
||||||
|
groups[user_group.id] = user_group
|
||||||
|
|
||||||
|
for user_dict in data["users"]:
|
||||||
|
# Collect the users group.
|
||||||
|
user_groups = []
|
||||||
|
for group_id in user_dict.get("group_ids", []):
|
||||||
|
# This is part of migrating from state 1
|
||||||
|
if group_id == group_without_policy:
|
||||||
|
group_id = GROUP_ID_ADMIN
|
||||||
|
user_groups.append(groups[group_id])
|
||||||
|
|
||||||
|
# This is part of migrating from state 2
|
||||||
|
if not user_dict["system_generated"] and migrate_users_to_admin_group:
|
||||||
|
user_groups.append(groups[GROUP_ID_ADMIN])
|
||||||
|
|
||||||
|
users[user_dict["id"]] = models.User(
|
||||||
|
name=user_dict["name"],
|
||||||
|
groups=user_groups,
|
||||||
|
id=user_dict["id"],
|
||||||
|
is_owner=user_dict["is_owner"],
|
||||||
|
is_active=user_dict["is_active"],
|
||||||
|
system_generated=user_dict["system_generated"],
|
||||||
|
perm_lookup=perm_lookup,
|
||||||
|
# New in 2021.11
|
||||||
|
local_only=user_dict.get("local_only", False),
|
||||||
|
)
|
||||||
|
|
||||||
|
for cred_dict in data["credentials"]:
|
||||||
|
credential = models.Credentials(
|
||||||
|
id=cred_dict["id"],
|
||||||
|
is_new=False,
|
||||||
|
auth_provider_type=cred_dict["auth_provider_type"],
|
||||||
|
auth_provider_id=cred_dict["auth_provider_id"],
|
||||||
|
data=cred_dict["data"],
|
||||||
|
)
|
||||||
|
credentials[cred_dict["id"]] = credential
|
||||||
|
users[cred_dict["user_id"]].credentials.append(credential)
|
||||||
|
|
||||||
|
for rt_dict in data["refresh_tokens"]:
|
||||||
|
# Filter out the old keys that don't have jwt_key (pre-0.76)
|
||||||
|
if "jwt_key" not in rt_dict:
|
||||||
|
continue
|
||||||
|
|
||||||
|
created_at = dt_util.parse_datetime(rt_dict["created_at"])
|
||||||
|
if created_at is None:
|
||||||
|
getLogger(__name__).error(
|
||||||
|
(
|
||||||
|
"Ignoring refresh token %(id)s with invalid created_at "
|
||||||
|
"%(created_at)s for user_id %(user_id)s"
|
||||||
|
),
|
||||||
|
rt_dict,
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
|
||||||
|
if (token_type := rt_dict.get("token_type")) is None:
|
||||||
|
if rt_dict["client_id"] is None:
|
||||||
|
token_type = models.TOKEN_TYPE_SYSTEM
|
||||||
|
else:
|
||||||
|
token_type = models.TOKEN_TYPE_NORMAL
|
||||||
|
|
||||||
|
# old refresh_token don't have last_used_at (pre-0.78)
|
||||||
|
if last_used_at_str := rt_dict.get("last_used_at"):
|
||||||
|
last_used_at = dt_util.parse_datetime(last_used_at_str)
|
||||||
|
else:
|
||||||
|
last_used_at = None
|
||||||
|
|
||||||
|
token = models.RefreshToken(
|
||||||
|
id=rt_dict["id"],
|
||||||
|
user=users[rt_dict["user_id"]],
|
||||||
|
client_id=rt_dict["client_id"],
|
||||||
|
# use dict.get to keep backward compatibility
|
||||||
|
client_name=rt_dict.get("client_name"),
|
||||||
|
client_icon=rt_dict.get("client_icon"),
|
||||||
|
token_type=token_type,
|
||||||
|
created_at=created_at,
|
||||||
|
access_token_expiration=timedelta(
|
||||||
|
seconds=rt_dict["access_token_expiration"]
|
||||||
|
),
|
||||||
|
token=rt_dict["token"],
|
||||||
|
jwt_key=rt_dict["jwt_key"],
|
||||||
|
last_used_at=last_used_at,
|
||||||
|
last_used_ip=rt_dict.get("last_used_ip"),
|
||||||
|
expire_at=rt_dict.get("expire_at"),
|
||||||
|
version=rt_dict.get("version"),
|
||||||
|
)
|
||||||
|
if "credential_id" in rt_dict:
|
||||||
|
token.credential = credentials.get(rt_dict["credential_id"])
|
||||||
|
users[rt_dict["user_id"]].refresh_tokens[token.id] = token
|
||||||
|
|
||||||
|
self._groups = groups
|
||||||
|
self._users = users
|
||||||
|
self._build_token_id_to_user_id()
|
||||||
|
self._async_schedule_save(INITIAL_LOAD_SAVE_DELAY)
|
||||||
|
|
||||||
|
@callback
|
||||||
|
def _build_token_id_to_user_id(self) -> None:
|
||||||
|
"""Build a map of token id to user id."""
|
||||||
|
self._token_id_to_user_id = {
|
||||||
|
token_id: user_id
|
||||||
|
for user_id, user in self._users.items()
|
||||||
|
for token_id in user.refresh_tokens
|
||||||
|
}
|
||||||
|
|
||||||
|
@callback
|
||||||
|
def _async_schedule_save(self, delay: float = DEFAULT_SAVE_DELAY) -> None:
|
||||||
|
"""Save users."""
|
||||||
|
self._store.async_delay_save(self._data_to_save, delay)
|
||||||
|
|
||||||
|
@callback
|
||||||
|
def _data_to_save(self) -> dict[str, list[dict[str, Any]]]:
|
||||||
|
"""Return the data to store."""
|
||||||
|
users = [
|
||||||
|
{
|
||||||
|
"id": user.id,
|
||||||
|
"group_ids": [group.id for group in user.groups],
|
||||||
|
"is_owner": user.is_owner,
|
||||||
|
"is_active": user.is_active,
|
||||||
|
"name": user.name,
|
||||||
|
"system_generated": user.system_generated,
|
||||||
|
"local_only": user.local_only,
|
||||||
|
}
|
||||||
|
for user in self._users.values()
|
||||||
|
]
|
||||||
|
|
||||||
|
groups = []
|
||||||
|
for group in self._groups.values():
|
||||||
|
g_dict: dict[str, Any] = {
|
||||||
|
"id": group.id,
|
||||||
|
# Name not read for sys groups. Kept here for backwards compat
|
||||||
|
"name": group.name,
|
||||||
|
}
|
||||||
|
|
||||||
|
if not group.system_generated:
|
||||||
|
g_dict["policy"] = group.policy
|
||||||
|
|
||||||
|
groups.append(g_dict)
|
||||||
|
|
||||||
|
credentials = [
|
||||||
|
{
|
||||||
|
"id": credential.id,
|
||||||
|
"user_id": user.id,
|
||||||
|
"auth_provider_type": credential.auth_provider_type,
|
||||||
|
"auth_provider_id": credential.auth_provider_id,
|
||||||
|
"data": credential.data,
|
||||||
|
}
|
||||||
|
for user in self._users.values()
|
||||||
|
for credential in user.credentials
|
||||||
|
]
|
||||||
|
|
||||||
|
refresh_tokens = [
|
||||||
|
{
|
||||||
|
"id": refresh_token.id,
|
||||||
|
"user_id": user.id,
|
||||||
|
"client_id": refresh_token.client_id,
|
||||||
|
"client_name": refresh_token.client_name,
|
||||||
|
"client_icon": refresh_token.client_icon,
|
||||||
|
"token_type": refresh_token.token_type,
|
||||||
|
"created_at": refresh_token.created_at.isoformat(),
|
||||||
|
"access_token_expiration": (
|
||||||
|
refresh_token.access_token_expiration.total_seconds()
|
||||||
|
),
|
||||||
|
"token": refresh_token.token,
|
||||||
|
"jwt_key": refresh_token.jwt_key,
|
||||||
|
"last_used_at": refresh_token.last_used_at.isoformat()
|
||||||
|
if refresh_token.last_used_at
|
||||||
|
else None,
|
||||||
|
"last_used_ip": refresh_token.last_used_ip,
|
||||||
|
"expire_at": refresh_token.expire_at,
|
||||||
|
"credential_id": refresh_token.credential.id
|
||||||
|
if refresh_token.credential
|
||||||
|
else None,
|
||||||
|
"version": refresh_token.version,
|
||||||
|
}
|
||||||
|
for user in self._users.values()
|
||||||
|
for refresh_token in user.refresh_tokens.values()
|
||||||
|
]
|
||||||
|
|
||||||
|
return {
|
||||||
|
"users": users,
|
||||||
|
"groups": groups,
|
||||||
|
"credentials": credentials,
|
||||||
|
"refresh_tokens": refresh_tokens,
|
||||||
|
}
|
||||||
|
|
||||||
|
def _set_defaults(self) -> None:
|
||||||
|
"""Set default values for auth store."""
|
||||||
|
self._users = {}
|
||||||
|
|
||||||
|
groups: dict[str, models.Group] = {}
|
||||||
|
admin_group = _system_admin_group()
|
||||||
|
groups[admin_group.id] = admin_group
|
||||||
|
user_group = _system_user_group()
|
||||||
|
groups[user_group.id] = user_group
|
||||||
|
read_only_group = _system_read_only_group()
|
||||||
|
groups[read_only_group.id] = read_only_group
|
||||||
|
self._groups = groups
|
||||||
|
self._build_token_id_to_user_id()
|
||||||
|
|
||||||
|
|
||||||
|
def _system_admin_group() -> models.Group:
|
||||||
|
"""Create system admin group."""
|
||||||
|
return models.Group(
|
||||||
|
name=GROUP_NAME_ADMIN,
|
||||||
|
id=GROUP_ID_ADMIN,
|
||||||
|
policy=system_policies.ADMIN_POLICY,
|
||||||
|
system_generated=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _system_user_group() -> models.Group:
|
||||||
|
"""Create system user group."""
|
||||||
|
return models.Group(
|
||||||
|
name=GROUP_NAME_USER,
|
||||||
|
id=GROUP_ID_USER,
|
||||||
|
policy=system_policies.USER_POLICY,
|
||||||
|
system_generated=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _system_read_only_group() -> models.Group:
|
||||||
|
"""Create read only group."""
|
||||||
|
return models.Group(
|
||||||
|
name=GROUP_NAME_READ_ONLY,
|
||||||
|
id=GROUP_ID_READ_ONLY,
|
||||||
|
policy=system_policies.READ_ONLY_POLICY,
|
||||||
|
system_generated=True,
|
||||||
|
)
|
||||||
11
home-assistant/homeassistant/auth/const.py
Normal file
11
home-assistant/homeassistant/auth/const.py
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
"""Constants for the auth module."""
|
||||||
|
|
||||||
|
from datetime import timedelta
|
||||||
|
|
||||||
|
ACCESS_TOKEN_EXPIRATION = timedelta(minutes=30)
|
||||||
|
MFA_SESSION_EXPIRATION = timedelta(minutes=5)
|
||||||
|
REFRESH_TOKEN_EXPIRATION = timedelta(days=90).total_seconds()
|
||||||
|
|
||||||
|
GROUP_ID_ADMIN = "system-admin"
|
||||||
|
GROUP_ID_USER = "system-users"
|
||||||
|
GROUP_ID_READ_ONLY = "system-read-only"
|
||||||
117
home-assistant/homeassistant/auth/jwt_wrapper.py
Normal file
117
home-assistant/homeassistant/auth/jwt_wrapper.py
Normal file
@@ -0,0 +1,117 @@
|
|||||||
|
"""Provide a wrapper around JWT that caches decoding tokens.
|
||||||
|
|
||||||
|
Since we decode the same tokens over and over again
|
||||||
|
we can cache the result of the decode of valid tokens
|
||||||
|
to speed up the process.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import timedelta
|
||||||
|
from functools import lru_cache, partial
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from jwt import DecodeError, PyJWS, PyJWT
|
||||||
|
|
||||||
|
from homeassistant.util.json import json_loads
|
||||||
|
|
||||||
|
JWT_TOKEN_CACHE_SIZE = 16
|
||||||
|
MAX_TOKEN_SIZE = 8192
|
||||||
|
|
||||||
|
_VERIFY_KEYS = ("signature", "exp", "nbf", "iat", "aud", "iss", "sub", "jti")
|
||||||
|
|
||||||
|
_VERIFY_OPTIONS: dict[str, Any] = {f"verify_{key}": True for key in _VERIFY_KEYS} | {
|
||||||
|
"require": []
|
||||||
|
}
|
||||||
|
_NO_VERIFY_OPTIONS = {f"verify_{key}": False for key in _VERIFY_KEYS}
|
||||||
|
|
||||||
|
|
||||||
|
class _PyJWSWithLoadCache(PyJWS):
|
||||||
|
"""PyJWS with a dedicated load implementation."""
|
||||||
|
|
||||||
|
@lru_cache(maxsize=JWT_TOKEN_CACHE_SIZE)
|
||||||
|
# We only ever have a global instance of this class
|
||||||
|
# so we do not have to worry about the LRU growing
|
||||||
|
# each time we create a new instance.
|
||||||
|
def _load(self, jwt: str | bytes) -> tuple[bytes, bytes, dict, bytes]:
|
||||||
|
"""Load a JWS."""
|
||||||
|
return super()._load(jwt)
|
||||||
|
|
||||||
|
|
||||||
|
_jws = _PyJWSWithLoadCache()
|
||||||
|
|
||||||
|
|
||||||
|
@lru_cache(maxsize=JWT_TOKEN_CACHE_SIZE)
|
||||||
|
def _decode_payload(json_payload: str) -> dict[str, Any]:
|
||||||
|
"""Decode the payload from a JWS dictionary."""
|
||||||
|
try:
|
||||||
|
payload = json_loads(json_payload)
|
||||||
|
except ValueError as err:
|
||||||
|
raise DecodeError(f"Invalid payload string: {err}") from err
|
||||||
|
if not isinstance(payload, dict):
|
||||||
|
raise DecodeError("Invalid payload string: must be a json object")
|
||||||
|
return payload
|
||||||
|
|
||||||
|
|
||||||
|
class _PyJWTWithVerify(PyJWT):
|
||||||
|
"""PyJWT with a fast decode implementation."""
|
||||||
|
|
||||||
|
def decode_payload(
|
||||||
|
self, jwt: str, key: str, options: dict[str, Any], algorithms: list[str]
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""Decode a JWT's payload."""
|
||||||
|
if len(jwt) > MAX_TOKEN_SIZE:
|
||||||
|
# Avoid caching impossible tokens
|
||||||
|
raise DecodeError("Token too large")
|
||||||
|
return _decode_payload(
|
||||||
|
_jws.decode_complete(
|
||||||
|
jwt=jwt,
|
||||||
|
key=key,
|
||||||
|
algorithms=algorithms,
|
||||||
|
options=options,
|
||||||
|
)["payload"]
|
||||||
|
)
|
||||||
|
|
||||||
|
def verify_and_decode(
|
||||||
|
self,
|
||||||
|
jwt: str,
|
||||||
|
key: str,
|
||||||
|
algorithms: list[str],
|
||||||
|
issuer: str | None = None,
|
||||||
|
leeway: float | timedelta = 0,
|
||||||
|
options: dict[str, Any] | None = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""Verify a JWT's signature and claims."""
|
||||||
|
merged_options = {**_VERIFY_OPTIONS, **(options or {})}
|
||||||
|
payload = self.decode_payload(
|
||||||
|
jwt=jwt,
|
||||||
|
key=key,
|
||||||
|
options=merged_options,
|
||||||
|
algorithms=algorithms,
|
||||||
|
)
|
||||||
|
# These should never be missing since we verify them
|
||||||
|
# but this is an additional safeguard to make sure
|
||||||
|
# nothing slips through.
|
||||||
|
assert "exp" in payload, "exp claim is required"
|
||||||
|
assert "iat" in payload, "iat claim is required"
|
||||||
|
self._validate_claims(
|
||||||
|
payload=payload,
|
||||||
|
options=merged_options,
|
||||||
|
issuer=issuer,
|
||||||
|
leeway=leeway,
|
||||||
|
)
|
||||||
|
return payload
|
||||||
|
|
||||||
|
|
||||||
|
_jwt = _PyJWTWithVerify()
|
||||||
|
verify_and_decode = _jwt.verify_and_decode
|
||||||
|
unverified_hs256_token_decode = lru_cache(maxsize=JWT_TOKEN_CACHE_SIZE)(
|
||||||
|
partial(
|
||||||
|
_jwt.decode_payload, key="", algorithms=["HS256"], options=_NO_VERIFY_OPTIONS
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"unverified_hs256_token_decode",
|
||||||
|
"verify_and_decode",
|
||||||
|
]
|
||||||
184
home-assistant/homeassistant/auth/mfa_modules/__init__.py
Normal file
184
home-assistant/homeassistant/auth/mfa_modules/__init__.py
Normal file
@@ -0,0 +1,184 @@
|
|||||||
|
"""Pluggable auth modules for Home Assistant."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import types
|
||||||
|
from typing import Any, Generic
|
||||||
|
|
||||||
|
from typing_extensions import TypeVar
|
||||||
|
import voluptuous as vol
|
||||||
|
from voluptuous.humanize import humanize_error
|
||||||
|
|
||||||
|
from homeassistant import data_entry_flow, requirements
|
||||||
|
from homeassistant.const import CONF_ID, CONF_NAME, CONF_TYPE
|
||||||
|
from homeassistant.core import HomeAssistant
|
||||||
|
from homeassistant.data_entry_flow import FlowResult
|
||||||
|
from homeassistant.exceptions import HomeAssistantError
|
||||||
|
from homeassistant.helpers.importlib import async_import_module
|
||||||
|
from homeassistant.util.decorator import Registry
|
||||||
|
from homeassistant.util.hass_dict import HassKey
|
||||||
|
|
||||||
|
MULTI_FACTOR_AUTH_MODULES: Registry[str, type[MultiFactorAuthModule]] = Registry()
|
||||||
|
|
||||||
|
MULTI_FACTOR_AUTH_MODULE_SCHEMA = vol.Schema(
|
||||||
|
{
|
||||||
|
vol.Required(CONF_TYPE): str,
|
||||||
|
vol.Optional(CONF_NAME): str,
|
||||||
|
# Specify ID if you have two mfa auth module for same type.
|
||||||
|
vol.Optional(CONF_ID): str,
|
||||||
|
},
|
||||||
|
extra=vol.ALLOW_EXTRA,
|
||||||
|
)
|
||||||
|
|
||||||
|
DATA_REQS: HassKey[set[str]] = HassKey("mfa_auth_module_reqs_processed")
|
||||||
|
|
||||||
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
_MultiFactorAuthModuleT = TypeVar(
|
||||||
|
"_MultiFactorAuthModuleT",
|
||||||
|
bound="MultiFactorAuthModule",
|
||||||
|
default="MultiFactorAuthModule",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class MultiFactorAuthModule:
|
||||||
|
"""Multi-factor Auth Module of validation function."""
|
||||||
|
|
||||||
|
DEFAULT_TITLE = "Unnamed auth module"
|
||||||
|
MAX_RETRY_TIME = 3
|
||||||
|
|
||||||
|
def __init__(self, hass: HomeAssistant, config: dict[str, Any]) -> None:
|
||||||
|
"""Initialize an auth module."""
|
||||||
|
self.hass = hass
|
||||||
|
self.config = config
|
||||||
|
|
||||||
|
@property
|
||||||
|
def id(self) -> str:
|
||||||
|
"""Return id of the auth module.
|
||||||
|
|
||||||
|
Default is same as type
|
||||||
|
"""
|
||||||
|
return self.config.get(CONF_ID, self.type) # type: ignore[no-any-return]
|
||||||
|
|
||||||
|
@property
|
||||||
|
def type(self) -> str:
|
||||||
|
"""Return type of the module."""
|
||||||
|
return self.config[CONF_TYPE] # type: ignore[no-any-return]
|
||||||
|
|
||||||
|
@property
|
||||||
|
def name(self) -> str:
|
||||||
|
"""Return the name of the auth module."""
|
||||||
|
return self.config.get(CONF_NAME, self.DEFAULT_TITLE) # type: ignore[no-any-return]
|
||||||
|
|
||||||
|
# Implement by extending class
|
||||||
|
|
||||||
|
@property
|
||||||
|
def input_schema(self) -> vol.Schema:
|
||||||
|
"""Return a voluptuous schema to define mfa auth module's input."""
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
async def async_setup_flow(self, user_id: str) -> SetupFlow[Any]:
|
||||||
|
"""Return a data entry flow handler for setup module.
|
||||||
|
|
||||||
|
Mfa module should extend SetupFlow
|
||||||
|
"""
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
async def async_setup_user(self, user_id: str, setup_data: Any) -> Any:
|
||||||
|
"""Set up user for mfa auth module."""
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
async def async_depose_user(self, user_id: str) -> None:
|
||||||
|
"""Remove user from mfa module."""
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
async def async_is_user_setup(self, user_id: str) -> bool:
|
||||||
|
"""Return whether user is setup."""
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
async def async_validate(self, user_id: str, user_input: dict[str, Any]) -> bool:
|
||||||
|
"""Return True if validation passed."""
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
|
||||||
|
class SetupFlow(data_entry_flow.FlowHandler, Generic[_MultiFactorAuthModuleT]):
|
||||||
|
"""Handler for the setup flow."""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
auth_module: _MultiFactorAuthModuleT,
|
||||||
|
setup_schema: vol.Schema,
|
||||||
|
user_id: str,
|
||||||
|
) -> None:
|
||||||
|
"""Initialize the setup flow."""
|
||||||
|
self._auth_module = auth_module
|
||||||
|
self._setup_schema = setup_schema
|
||||||
|
self._user_id = user_id
|
||||||
|
|
||||||
|
async def async_step_init(
|
||||||
|
self, user_input: dict[str, str] | None = None
|
||||||
|
) -> FlowResult:
|
||||||
|
"""Handle the first step of setup flow.
|
||||||
|
|
||||||
|
Return self.async_show_form(step_id='init') if user_input is None.
|
||||||
|
Return self.async_create_entry(data={'result': result}) if finish.
|
||||||
|
"""
|
||||||
|
errors: dict[str, str] = {}
|
||||||
|
|
||||||
|
if user_input:
|
||||||
|
result = await self._auth_module.async_setup_user(self._user_id, user_input)
|
||||||
|
return self.async_create_entry(data={"result": result})
|
||||||
|
|
||||||
|
return self.async_show_form(
|
||||||
|
step_id="init", data_schema=self._setup_schema, errors=errors
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def auth_mfa_module_from_config(
|
||||||
|
hass: HomeAssistant, config: dict[str, Any]
|
||||||
|
) -> MultiFactorAuthModule:
|
||||||
|
"""Initialize an auth module from a config."""
|
||||||
|
module_name: str = config[CONF_TYPE]
|
||||||
|
module = await _load_mfa_module(hass, module_name)
|
||||||
|
|
||||||
|
try:
|
||||||
|
config = module.CONFIG_SCHEMA(config)
|
||||||
|
except vol.Invalid as err:
|
||||||
|
_LOGGER.error(
|
||||||
|
"Invalid configuration for multi-factor module %s: %s",
|
||||||
|
module_name,
|
||||||
|
humanize_error(config, err),
|
||||||
|
)
|
||||||
|
raise
|
||||||
|
|
||||||
|
return MULTI_FACTOR_AUTH_MODULES[module_name](hass, config)
|
||||||
|
|
||||||
|
|
||||||
|
async def _load_mfa_module(hass: HomeAssistant, module_name: str) -> types.ModuleType:
|
||||||
|
"""Load an mfa auth module."""
|
||||||
|
module_path = f"homeassistant.auth.mfa_modules.{module_name}"
|
||||||
|
|
||||||
|
try:
|
||||||
|
module = await async_import_module(hass, module_path)
|
||||||
|
except ImportError as err:
|
||||||
|
_LOGGER.error("Unable to load mfa module %s: %s", module_name, err)
|
||||||
|
raise HomeAssistantError(
|
||||||
|
f"Unable to load mfa module {module_name}: {err}"
|
||||||
|
) from err
|
||||||
|
|
||||||
|
if hass.config.skip_pip or not hasattr(module, "REQUIREMENTS"):
|
||||||
|
return module
|
||||||
|
|
||||||
|
processed = hass.data.get(DATA_REQS)
|
||||||
|
if processed and module_name in processed:
|
||||||
|
return module
|
||||||
|
|
||||||
|
processed = hass.data[DATA_REQS] = set()
|
||||||
|
|
||||||
|
await requirements.async_process_requirements(
|
||||||
|
hass, module_path, module.REQUIREMENTS
|
||||||
|
)
|
||||||
|
|
||||||
|
processed.add(module_name)
|
||||||
|
return module
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
"""Example auth module."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import voluptuous as vol
|
||||||
|
|
||||||
|
from homeassistant.core import HomeAssistant
|
||||||
|
|
||||||
|
from . import (
|
||||||
|
MULTI_FACTOR_AUTH_MODULE_SCHEMA,
|
||||||
|
MULTI_FACTOR_AUTH_MODULES,
|
||||||
|
MultiFactorAuthModule,
|
||||||
|
SetupFlow,
|
||||||
|
)
|
||||||
|
|
||||||
|
CONFIG_SCHEMA = MULTI_FACTOR_AUTH_MODULE_SCHEMA.extend(
|
||||||
|
{
|
||||||
|
vol.Required("data"): [
|
||||||
|
vol.Schema({vol.Required("user_id"): str, vol.Required("pin"): str})
|
||||||
|
]
|
||||||
|
},
|
||||||
|
extra=vol.PREVENT_EXTRA,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@MULTI_FACTOR_AUTH_MODULES.register("insecure_example")
|
||||||
|
class InsecureExampleModule(MultiFactorAuthModule):
|
||||||
|
"""Example auth module validate pin."""
|
||||||
|
|
||||||
|
DEFAULT_TITLE = "Insecure Personal Identify Number"
|
||||||
|
|
||||||
|
def __init__(self, hass: HomeAssistant, config: dict[str, Any]) -> None:
|
||||||
|
"""Initialize the user data store."""
|
||||||
|
super().__init__(hass, config)
|
||||||
|
self._data = config["data"]
|
||||||
|
|
||||||
|
@property
|
||||||
|
def input_schema(self) -> vol.Schema:
|
||||||
|
"""Validate login flow input data."""
|
||||||
|
return vol.Schema({vol.Required("pin"): str})
|
||||||
|
|
||||||
|
@property
|
||||||
|
def setup_schema(self) -> vol.Schema:
|
||||||
|
"""Validate async_setup_user input data."""
|
||||||
|
return vol.Schema({vol.Required("pin"): str})
|
||||||
|
|
||||||
|
async def async_setup_flow(self, user_id: str) -> SetupFlow:
|
||||||
|
"""Return a data entry flow handler for setup module.
|
||||||
|
|
||||||
|
Mfa module should extend SetupFlow
|
||||||
|
"""
|
||||||
|
return SetupFlow(self, self.setup_schema, user_id)
|
||||||
|
|
||||||
|
async def async_setup_user(self, user_id: str, setup_data: Any) -> Any:
|
||||||
|
"""Set up user to use mfa module."""
|
||||||
|
# data shall has been validate in caller
|
||||||
|
pin = setup_data["pin"]
|
||||||
|
|
||||||
|
for data in self._data:
|
||||||
|
if data["user_id"] == user_id:
|
||||||
|
# already setup, override
|
||||||
|
data["pin"] = pin
|
||||||
|
return
|
||||||
|
|
||||||
|
self._data.append({"user_id": user_id, "pin": pin})
|
||||||
|
|
||||||
|
async def async_depose_user(self, user_id: str) -> None:
|
||||||
|
"""Remove user from mfa module."""
|
||||||
|
found = None
|
||||||
|
for data in self._data:
|
||||||
|
if data["user_id"] == user_id:
|
||||||
|
found = data
|
||||||
|
break
|
||||||
|
if found:
|
||||||
|
self._data.remove(found)
|
||||||
|
|
||||||
|
async def async_is_user_setup(self, user_id: str) -> bool:
|
||||||
|
"""Return whether user is setup."""
|
||||||
|
return any(data["user_id"] == user_id for data in self._data)
|
||||||
|
|
||||||
|
async def async_validate(self, user_id: str, user_input: dict[str, Any]) -> bool:
|
||||||
|
"""Return True if validation passed."""
|
||||||
|
return any(
|
||||||
|
data["user_id"] == user_id and data["pin"] == user_input["pin"]
|
||||||
|
for data in self._data
|
||||||
|
)
|
||||||
354
home-assistant/homeassistant/auth/mfa_modules/notify.py
Normal file
354
home-assistant/homeassistant/auth/mfa_modules/notify.py
Normal file
@@ -0,0 +1,354 @@
|
|||||||
|
"""HMAC-based One-time Password auth module.
|
||||||
|
|
||||||
|
Sending HOTP through notify service
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
from collections import OrderedDict
|
||||||
|
import logging
|
||||||
|
from typing import Any, cast
|
||||||
|
|
||||||
|
import attr
|
||||||
|
import voluptuous as vol
|
||||||
|
|
||||||
|
from homeassistant.const import CONF_EXCLUDE, CONF_INCLUDE
|
||||||
|
from homeassistant.core import HomeAssistant, callback
|
||||||
|
from homeassistant.data_entry_flow import FlowResult
|
||||||
|
from homeassistant.exceptions import ServiceNotFound
|
||||||
|
from homeassistant.helpers import config_validation as cv
|
||||||
|
from homeassistant.helpers.storage import Store
|
||||||
|
|
||||||
|
from . import (
|
||||||
|
MULTI_FACTOR_AUTH_MODULE_SCHEMA,
|
||||||
|
MULTI_FACTOR_AUTH_MODULES,
|
||||||
|
MultiFactorAuthModule,
|
||||||
|
SetupFlow,
|
||||||
|
)
|
||||||
|
|
||||||
|
REQUIREMENTS = ["pyotp==2.8.0"]
|
||||||
|
|
||||||
|
CONF_MESSAGE = "message"
|
||||||
|
|
||||||
|
CONFIG_SCHEMA = MULTI_FACTOR_AUTH_MODULE_SCHEMA.extend(
|
||||||
|
{
|
||||||
|
vol.Optional(CONF_INCLUDE): vol.All(cv.ensure_list, [cv.string]),
|
||||||
|
vol.Optional(CONF_EXCLUDE): vol.All(cv.ensure_list, [cv.string]),
|
||||||
|
vol.Optional(CONF_MESSAGE, default="{} is your Home Assistant login code"): str,
|
||||||
|
},
|
||||||
|
extra=vol.PREVENT_EXTRA,
|
||||||
|
)
|
||||||
|
|
||||||
|
STORAGE_VERSION = 1
|
||||||
|
STORAGE_KEY = "auth_module.notify"
|
||||||
|
STORAGE_USERS = "users"
|
||||||
|
STORAGE_USER_ID = "user_id"
|
||||||
|
|
||||||
|
INPUT_FIELD_CODE = "code"
|
||||||
|
|
||||||
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def _generate_secret() -> str:
|
||||||
|
"""Generate a secret."""
|
||||||
|
import pyotp # pylint: disable=import-outside-toplevel
|
||||||
|
|
||||||
|
return str(pyotp.random_base32())
|
||||||
|
|
||||||
|
|
||||||
|
def _generate_random() -> int:
|
||||||
|
"""Generate a 32 digit number."""
|
||||||
|
import pyotp # pylint: disable=import-outside-toplevel
|
||||||
|
|
||||||
|
return int(pyotp.random_base32(length=32, chars=list("1234567890")))
|
||||||
|
|
||||||
|
|
||||||
|
def _generate_otp(secret: str, count: int) -> str:
|
||||||
|
"""Generate one time password."""
|
||||||
|
import pyotp # pylint: disable=import-outside-toplevel
|
||||||
|
|
||||||
|
return str(pyotp.HOTP(secret).at(count))
|
||||||
|
|
||||||
|
|
||||||
|
def _verify_otp(secret: str, otp: str, count: int) -> bool:
|
||||||
|
"""Verify one time password."""
|
||||||
|
import pyotp # pylint: disable=import-outside-toplevel
|
||||||
|
|
||||||
|
return bool(pyotp.HOTP(secret).verify(otp, count))
|
||||||
|
|
||||||
|
|
||||||
|
@attr.s(slots=True)
|
||||||
|
class NotifySetting:
|
||||||
|
"""Store notify setting for one user."""
|
||||||
|
|
||||||
|
secret: str = attr.ib(factory=_generate_secret) # not persistent
|
||||||
|
counter: int = attr.ib(factory=_generate_random) # not persistent
|
||||||
|
notify_service: str | None = attr.ib(default=None)
|
||||||
|
target: str | None = attr.ib(default=None)
|
||||||
|
|
||||||
|
|
||||||
|
type _UsersDict = dict[str, NotifySetting]
|
||||||
|
|
||||||
|
|
||||||
|
@MULTI_FACTOR_AUTH_MODULES.register("notify")
|
||||||
|
class NotifyAuthModule(MultiFactorAuthModule):
|
||||||
|
"""Auth module send hmac-based one time password by notify service."""
|
||||||
|
|
||||||
|
DEFAULT_TITLE = "Notify One-Time Password"
|
||||||
|
|
||||||
|
def __init__(self, hass: HomeAssistant, config: dict[str, Any]) -> None:
|
||||||
|
"""Initialize the user data store."""
|
||||||
|
super().__init__(hass, config)
|
||||||
|
self._user_settings: _UsersDict | None = None
|
||||||
|
self._user_store = Store[dict[str, dict[str, Any]]](
|
||||||
|
hass, STORAGE_VERSION, STORAGE_KEY, private=True, atomic_writes=True
|
||||||
|
)
|
||||||
|
self._include = config.get(CONF_INCLUDE, [])
|
||||||
|
self._exclude = config.get(CONF_EXCLUDE, [])
|
||||||
|
self._message_template = config[CONF_MESSAGE]
|
||||||
|
self._init_lock = asyncio.Lock()
|
||||||
|
|
||||||
|
@property
|
||||||
|
def input_schema(self) -> vol.Schema:
|
||||||
|
"""Validate login flow input data."""
|
||||||
|
return vol.Schema({vol.Required(INPUT_FIELD_CODE): str})
|
||||||
|
|
||||||
|
async def _async_load(self) -> None:
|
||||||
|
"""Load stored data."""
|
||||||
|
async with self._init_lock:
|
||||||
|
if self._user_settings is not None:
|
||||||
|
return
|
||||||
|
|
||||||
|
if (data := await self._user_store.async_load()) is None:
|
||||||
|
data = cast(dict[str, dict[str, Any]], {STORAGE_USERS: {}})
|
||||||
|
|
||||||
|
self._user_settings = {
|
||||||
|
user_id: NotifySetting(**setting)
|
||||||
|
for user_id, setting in data.get(STORAGE_USERS, {}).items()
|
||||||
|
}
|
||||||
|
|
||||||
|
async def _async_save(self) -> None:
|
||||||
|
"""Save data."""
|
||||||
|
if self._user_settings is None:
|
||||||
|
return
|
||||||
|
|
||||||
|
await self._user_store.async_save(
|
||||||
|
{
|
||||||
|
STORAGE_USERS: {
|
||||||
|
user_id: attr.asdict(
|
||||||
|
notify_setting,
|
||||||
|
filter=attr.filters.exclude(
|
||||||
|
attr.fields(NotifySetting).secret,
|
||||||
|
attr.fields(NotifySetting).counter,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
for user_id, notify_setting in self._user_settings.items()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
@callback
|
||||||
|
def aync_get_available_notify_services(self) -> list[str]:
|
||||||
|
"""Return list of notify services."""
|
||||||
|
unordered_services = set()
|
||||||
|
|
||||||
|
for service in self.hass.services.async_services_for_domain("notify"):
|
||||||
|
if service not in self._exclude:
|
||||||
|
unordered_services.add(service)
|
||||||
|
|
||||||
|
if self._include:
|
||||||
|
unordered_services &= set(self._include)
|
||||||
|
|
||||||
|
return sorted(unordered_services)
|
||||||
|
|
||||||
|
async def async_setup_flow(self, user_id: str) -> NotifySetupFlow:
|
||||||
|
"""Return a data entry flow handler for setup module.
|
||||||
|
|
||||||
|
Mfa module should extend SetupFlow
|
||||||
|
"""
|
||||||
|
return NotifySetupFlow(
|
||||||
|
self, self.input_schema, user_id, self.aync_get_available_notify_services()
|
||||||
|
)
|
||||||
|
|
||||||
|
async def async_setup_user(self, user_id: str, setup_data: Any) -> Any:
|
||||||
|
"""Set up auth module for user."""
|
||||||
|
if self._user_settings is None:
|
||||||
|
await self._async_load()
|
||||||
|
assert self._user_settings is not None
|
||||||
|
|
||||||
|
self._user_settings[user_id] = NotifySetting(
|
||||||
|
notify_service=setup_data.get("notify_service"),
|
||||||
|
target=setup_data.get("target"),
|
||||||
|
)
|
||||||
|
|
||||||
|
await self._async_save()
|
||||||
|
|
||||||
|
async def async_depose_user(self, user_id: str) -> None:
|
||||||
|
"""Depose auth module for user."""
|
||||||
|
if self._user_settings is None:
|
||||||
|
await self._async_load()
|
||||||
|
assert self._user_settings is not None
|
||||||
|
|
||||||
|
if self._user_settings.pop(user_id, None):
|
||||||
|
await self._async_save()
|
||||||
|
|
||||||
|
async def async_is_user_setup(self, user_id: str) -> bool:
|
||||||
|
"""Return whether user is setup."""
|
||||||
|
if self._user_settings is None:
|
||||||
|
await self._async_load()
|
||||||
|
assert self._user_settings is not None
|
||||||
|
|
||||||
|
return user_id in self._user_settings
|
||||||
|
|
||||||
|
async def async_validate(self, user_id: str, user_input: dict[str, Any]) -> bool:
|
||||||
|
"""Return True if validation passed."""
|
||||||
|
if self._user_settings is None:
|
||||||
|
await self._async_load()
|
||||||
|
assert self._user_settings is not None
|
||||||
|
|
||||||
|
if (notify_setting := self._user_settings.get(user_id)) is None:
|
||||||
|
return False
|
||||||
|
|
||||||
|
# user_input has been validate in caller
|
||||||
|
return await self.hass.async_add_executor_job(
|
||||||
|
_verify_otp,
|
||||||
|
notify_setting.secret,
|
||||||
|
user_input.get(INPUT_FIELD_CODE, ""),
|
||||||
|
notify_setting.counter,
|
||||||
|
)
|
||||||
|
|
||||||
|
async def async_initialize_login_mfa_step(self, user_id: str) -> None:
|
||||||
|
"""Generate code and notify user."""
|
||||||
|
if self._user_settings is None:
|
||||||
|
await self._async_load()
|
||||||
|
assert self._user_settings is not None
|
||||||
|
|
||||||
|
if (notify_setting := self._user_settings.get(user_id)) is None:
|
||||||
|
raise ValueError("Cannot find user_id")
|
||||||
|
|
||||||
|
def generate_secret_and_one_time_password() -> str:
|
||||||
|
"""Generate and send one time password."""
|
||||||
|
assert notify_setting
|
||||||
|
# secret and counter are not persistent
|
||||||
|
notify_setting.secret = _generate_secret()
|
||||||
|
notify_setting.counter = _generate_random()
|
||||||
|
return _generate_otp(notify_setting.secret, notify_setting.counter)
|
||||||
|
|
||||||
|
code = await self.hass.async_add_executor_job(
|
||||||
|
generate_secret_and_one_time_password
|
||||||
|
)
|
||||||
|
|
||||||
|
await self.async_notify_user(user_id, code)
|
||||||
|
|
||||||
|
async def async_notify_user(self, user_id: str, code: str) -> None:
|
||||||
|
"""Send code by user's notify service."""
|
||||||
|
if self._user_settings is None:
|
||||||
|
await self._async_load()
|
||||||
|
assert self._user_settings is not None
|
||||||
|
|
||||||
|
if (notify_setting := self._user_settings.get(user_id)) is None:
|
||||||
|
_LOGGER.error("Cannot find user %s", user_id)
|
||||||
|
return
|
||||||
|
|
||||||
|
await self.async_notify(
|
||||||
|
code,
|
||||||
|
notify_setting.notify_service, # type: ignore[arg-type]
|
||||||
|
notify_setting.target,
|
||||||
|
)
|
||||||
|
|
||||||
|
async def async_notify(
|
||||||
|
self, code: str, notify_service: str, target: str | None = None
|
||||||
|
) -> None:
|
||||||
|
"""Send code by notify service."""
|
||||||
|
data = {"message": self._message_template.format(code)}
|
||||||
|
if target:
|
||||||
|
data["target"] = [target]
|
||||||
|
|
||||||
|
await self.hass.services.async_call("notify", notify_service, data)
|
||||||
|
|
||||||
|
|
||||||
|
class NotifySetupFlow(SetupFlow[NotifyAuthModule]):
|
||||||
|
"""Handler for the setup flow."""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
auth_module: NotifyAuthModule,
|
||||||
|
setup_schema: vol.Schema,
|
||||||
|
user_id: str,
|
||||||
|
available_notify_services: list[str],
|
||||||
|
) -> None:
|
||||||
|
"""Initialize the setup flow."""
|
||||||
|
super().__init__(auth_module, setup_schema, user_id)
|
||||||
|
self._available_notify_services = available_notify_services
|
||||||
|
self._secret: str | None = None
|
||||||
|
self._count: int | None = None
|
||||||
|
self._notify_service: str | None = None
|
||||||
|
self._target: str | None = None
|
||||||
|
|
||||||
|
async def async_step_init(
|
||||||
|
self, user_input: dict[str, str] | None = None
|
||||||
|
) -> FlowResult:
|
||||||
|
"""Let user select available notify services."""
|
||||||
|
errors: dict[str, str] = {}
|
||||||
|
|
||||||
|
hass = self._auth_module.hass
|
||||||
|
if user_input:
|
||||||
|
self._notify_service = user_input["notify_service"]
|
||||||
|
self._target = user_input.get("target")
|
||||||
|
self._secret = await hass.async_add_executor_job(_generate_secret)
|
||||||
|
self._count = await hass.async_add_executor_job(_generate_random)
|
||||||
|
|
||||||
|
return await self.async_step_setup()
|
||||||
|
|
||||||
|
if not self._available_notify_services:
|
||||||
|
return self.async_abort(reason="no_available_service")
|
||||||
|
|
||||||
|
schema: dict[str, Any] = OrderedDict()
|
||||||
|
schema["notify_service"] = vol.In(self._available_notify_services)
|
||||||
|
schema["target"] = vol.Optional(str)
|
||||||
|
|
||||||
|
return self.async_show_form(
|
||||||
|
step_id="init", data_schema=vol.Schema(schema), errors=errors
|
||||||
|
)
|
||||||
|
|
||||||
|
async def async_step_setup(
|
||||||
|
self, user_input: dict[str, str] | None = None
|
||||||
|
) -> FlowResult:
|
||||||
|
"""Verify user can receive one-time password."""
|
||||||
|
errors: dict[str, str] = {}
|
||||||
|
|
||||||
|
hass = self._auth_module.hass
|
||||||
|
assert self._secret and self._count
|
||||||
|
if user_input:
|
||||||
|
verified = await hass.async_add_executor_job(
|
||||||
|
_verify_otp, self._secret, user_input["code"], self._count
|
||||||
|
)
|
||||||
|
if verified:
|
||||||
|
await self._auth_module.async_setup_user(
|
||||||
|
self._user_id,
|
||||||
|
{"notify_service": self._notify_service, "target": self._target},
|
||||||
|
)
|
||||||
|
return self.async_create_entry(data={})
|
||||||
|
|
||||||
|
errors["base"] = "invalid_code"
|
||||||
|
|
||||||
|
# generate code every time, no retry logic
|
||||||
|
code = await hass.async_add_executor_job(
|
||||||
|
_generate_otp, self._secret, self._count
|
||||||
|
)
|
||||||
|
|
||||||
|
assert self._notify_service
|
||||||
|
try:
|
||||||
|
await self._auth_module.async_notify(
|
||||||
|
code, self._notify_service, self._target
|
||||||
|
)
|
||||||
|
except ServiceNotFound:
|
||||||
|
return self.async_abort(reason="notify_service_not_exist")
|
||||||
|
|
||||||
|
return self.async_show_form(
|
||||||
|
step_id="setup",
|
||||||
|
data_schema=self._setup_schema,
|
||||||
|
description_placeholders={"notify_service": self._notify_service},
|
||||||
|
errors=errors,
|
||||||
|
)
|
||||||
234
home-assistant/homeassistant/auth/mfa_modules/totp.py
Normal file
234
home-assistant/homeassistant/auth/mfa_modules/totp.py
Normal file
@@ -0,0 +1,234 @@
|
|||||||
|
"""Time-based One Time Password auth module."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
from io import BytesIO
|
||||||
|
from typing import Any, cast
|
||||||
|
|
||||||
|
import voluptuous as vol
|
||||||
|
|
||||||
|
from homeassistant.auth.models import User
|
||||||
|
from homeassistant.core import HomeAssistant
|
||||||
|
from homeassistant.data_entry_flow import FlowResult
|
||||||
|
from homeassistant.helpers.storage import Store
|
||||||
|
|
||||||
|
from . import (
|
||||||
|
MULTI_FACTOR_AUTH_MODULE_SCHEMA,
|
||||||
|
MULTI_FACTOR_AUTH_MODULES,
|
||||||
|
MultiFactorAuthModule,
|
||||||
|
SetupFlow,
|
||||||
|
)
|
||||||
|
|
||||||
|
REQUIREMENTS = ["pyotp==2.8.0", "PyQRCode==1.2.1"]
|
||||||
|
|
||||||
|
CONFIG_SCHEMA = MULTI_FACTOR_AUTH_MODULE_SCHEMA.extend({}, extra=vol.PREVENT_EXTRA)
|
||||||
|
|
||||||
|
STORAGE_VERSION = 1
|
||||||
|
STORAGE_KEY = "auth_module.totp"
|
||||||
|
STORAGE_USERS = "users"
|
||||||
|
STORAGE_USER_ID = "user_id"
|
||||||
|
STORAGE_OTA_SECRET = "ota_secret"
|
||||||
|
|
||||||
|
INPUT_FIELD_CODE = "code"
|
||||||
|
|
||||||
|
DUMMY_SECRET = "FPPTH34D4E3MI2HG"
|
||||||
|
|
||||||
|
|
||||||
|
def _generate_qr_code(data: str) -> str:
|
||||||
|
"""Generate a base64 PNG string represent QR Code image of data."""
|
||||||
|
import pyqrcode # pylint: disable=import-outside-toplevel
|
||||||
|
|
||||||
|
qr_code = pyqrcode.create(data)
|
||||||
|
|
||||||
|
with BytesIO() as buffer:
|
||||||
|
qr_code.svg(file=buffer, scale=4)
|
||||||
|
return str(
|
||||||
|
buffer.getvalue()
|
||||||
|
.decode("ascii")
|
||||||
|
.replace("\n", "")
|
||||||
|
.replace(
|
||||||
|
(
|
||||||
|
'<?xml version="1.0" encoding="UTF-8"?>'
|
||||||
|
'<svg xmlns="http://www.w3.org/2000/svg"'
|
||||||
|
),
|
||||||
|
"<svg",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _generate_secret_and_qr_code(username: str) -> tuple[str, str, str]:
|
||||||
|
"""Generate a secret, url, and QR code."""
|
||||||
|
import pyotp # pylint: disable=import-outside-toplevel
|
||||||
|
|
||||||
|
ota_secret = pyotp.random_base32()
|
||||||
|
url = pyotp.totp.TOTP(ota_secret).provisioning_uri(
|
||||||
|
username, issuer_name="Home Assistant"
|
||||||
|
)
|
||||||
|
image = _generate_qr_code(url)
|
||||||
|
return ota_secret, url, image
|
||||||
|
|
||||||
|
|
||||||
|
@MULTI_FACTOR_AUTH_MODULES.register("totp")
|
||||||
|
class TotpAuthModule(MultiFactorAuthModule):
|
||||||
|
"""Auth module validate time-based one time password."""
|
||||||
|
|
||||||
|
DEFAULT_TITLE = "Time-based One Time Password"
|
||||||
|
MAX_RETRY_TIME = 5
|
||||||
|
|
||||||
|
def __init__(self, hass: HomeAssistant, config: dict[str, Any]) -> None:
|
||||||
|
"""Initialize the user data store."""
|
||||||
|
super().__init__(hass, config)
|
||||||
|
self._users: dict[str, str] | None = None
|
||||||
|
self._user_store = Store[dict[str, dict[str, str]]](
|
||||||
|
hass, STORAGE_VERSION, STORAGE_KEY, private=True, atomic_writes=True
|
||||||
|
)
|
||||||
|
self._init_lock = asyncio.Lock()
|
||||||
|
|
||||||
|
@property
|
||||||
|
def input_schema(self) -> vol.Schema:
|
||||||
|
"""Validate login flow input data."""
|
||||||
|
return vol.Schema({vol.Required(INPUT_FIELD_CODE): str})
|
||||||
|
|
||||||
|
async def _async_load(self) -> None:
|
||||||
|
"""Load stored data."""
|
||||||
|
async with self._init_lock:
|
||||||
|
if self._users is not None:
|
||||||
|
return
|
||||||
|
|
||||||
|
if (data := await self._user_store.async_load()) is None:
|
||||||
|
data = cast(dict[str, dict[str, str]], {STORAGE_USERS: {}})
|
||||||
|
|
||||||
|
self._users = data.get(STORAGE_USERS, {})
|
||||||
|
|
||||||
|
async def _async_save(self) -> None:
|
||||||
|
"""Save data."""
|
||||||
|
await self._user_store.async_save({STORAGE_USERS: self._users or {}})
|
||||||
|
|
||||||
|
def _add_ota_secret(self, user_id: str, secret: str | None = None) -> str:
|
||||||
|
"""Create a ota_secret for user."""
|
||||||
|
import pyotp # pylint: disable=import-outside-toplevel
|
||||||
|
|
||||||
|
ota_secret: str = secret or pyotp.random_base32()
|
||||||
|
|
||||||
|
self._users[user_id] = ota_secret # type: ignore[index]
|
||||||
|
return ota_secret
|
||||||
|
|
||||||
|
async def async_setup_flow(self, user_id: str) -> TotpSetupFlow:
|
||||||
|
"""Return a data entry flow handler for setup module.
|
||||||
|
|
||||||
|
Mfa module should extend SetupFlow
|
||||||
|
"""
|
||||||
|
user = await self.hass.auth.async_get_user(user_id)
|
||||||
|
assert user is not None
|
||||||
|
return TotpSetupFlow(self, self.input_schema, user)
|
||||||
|
|
||||||
|
async def async_setup_user(self, user_id: str, setup_data: Any) -> str:
|
||||||
|
"""Set up auth module for user."""
|
||||||
|
if self._users is None:
|
||||||
|
await self._async_load()
|
||||||
|
|
||||||
|
result = await self.hass.async_add_executor_job(
|
||||||
|
self._add_ota_secret, user_id, setup_data.get("secret")
|
||||||
|
)
|
||||||
|
|
||||||
|
await self._async_save()
|
||||||
|
return result
|
||||||
|
|
||||||
|
async def async_depose_user(self, user_id: str) -> None:
|
||||||
|
"""Depose auth module for user."""
|
||||||
|
if self._users is None:
|
||||||
|
await self._async_load()
|
||||||
|
|
||||||
|
if self._users.pop(user_id, None): # type: ignore[union-attr]
|
||||||
|
await self._async_save()
|
||||||
|
|
||||||
|
async def async_is_user_setup(self, user_id: str) -> bool:
|
||||||
|
"""Return whether user is setup."""
|
||||||
|
if self._users is None:
|
||||||
|
await self._async_load()
|
||||||
|
|
||||||
|
return user_id in self._users # type: ignore[operator]
|
||||||
|
|
||||||
|
async def async_validate(self, user_id: str, user_input: dict[str, Any]) -> bool:
|
||||||
|
"""Return True if validation passed."""
|
||||||
|
if self._users is None:
|
||||||
|
await self._async_load()
|
||||||
|
|
||||||
|
# user_input has been validate in caller
|
||||||
|
# set INPUT_FIELD_CODE as vol.Required is not user friendly
|
||||||
|
return await self.hass.async_add_executor_job(
|
||||||
|
self._validate_2fa, user_id, user_input.get(INPUT_FIELD_CODE, "")
|
||||||
|
)
|
||||||
|
|
||||||
|
def _validate_2fa(self, user_id: str, code: str) -> bool:
|
||||||
|
"""Validate two factor authentication code."""
|
||||||
|
import pyotp # pylint: disable=import-outside-toplevel
|
||||||
|
|
||||||
|
if (ota_secret := self._users.get(user_id)) is None: # type: ignore[union-attr]
|
||||||
|
# even we cannot find user, we still do verify
|
||||||
|
# to make timing the same as if user was found.
|
||||||
|
pyotp.TOTP(DUMMY_SECRET).verify(code, valid_window=1)
|
||||||
|
return False
|
||||||
|
|
||||||
|
return bool(pyotp.TOTP(ota_secret).verify(code, valid_window=1))
|
||||||
|
|
||||||
|
|
||||||
|
class TotpSetupFlow(SetupFlow[TotpAuthModule]):
|
||||||
|
"""Handler for the setup flow."""
|
||||||
|
|
||||||
|
_ota_secret: str
|
||||||
|
_url: str
|
||||||
|
_image: str
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self, auth_module: TotpAuthModule, setup_schema: vol.Schema, user: User
|
||||||
|
) -> None:
|
||||||
|
"""Initialize the setup flow."""
|
||||||
|
super().__init__(auth_module, setup_schema, user.id)
|
||||||
|
self._user = user
|
||||||
|
|
||||||
|
async def async_step_init(
|
||||||
|
self, user_input: dict[str, str] | None = None
|
||||||
|
) -> FlowResult:
|
||||||
|
"""Handle the first step of setup flow.
|
||||||
|
|
||||||
|
Return self.async_show_form(step_id='init') if user_input is None.
|
||||||
|
Return self.async_create_entry(data={'result': result}) if finish.
|
||||||
|
"""
|
||||||
|
import pyotp # pylint: disable=import-outside-toplevel
|
||||||
|
|
||||||
|
errors: dict[str, str] = {}
|
||||||
|
|
||||||
|
if user_input:
|
||||||
|
verified = await self.hass.async_add_executor_job(
|
||||||
|
pyotp.TOTP(self._ota_secret).verify, user_input["code"]
|
||||||
|
)
|
||||||
|
if verified:
|
||||||
|
result = await self._auth_module.async_setup_user(
|
||||||
|
self._user_id, {"secret": self._ota_secret}
|
||||||
|
)
|
||||||
|
return self.async_create_entry(data={"result": result})
|
||||||
|
|
||||||
|
errors["base"] = "invalid_code"
|
||||||
|
|
||||||
|
else:
|
||||||
|
(
|
||||||
|
self._ota_secret,
|
||||||
|
self._url,
|
||||||
|
self._image,
|
||||||
|
) = await self._auth_module.hass.async_add_executor_job(
|
||||||
|
_generate_secret_and_qr_code,
|
||||||
|
str(self._user.name),
|
||||||
|
)
|
||||||
|
|
||||||
|
return self.async_show_form(
|
||||||
|
step_id="init",
|
||||||
|
data_schema=self._setup_schema,
|
||||||
|
description_placeholders={
|
||||||
|
"code": self._ota_secret,
|
||||||
|
"url": self._url,
|
||||||
|
"qr_code": self._image,
|
||||||
|
},
|
||||||
|
errors=errors,
|
||||||
|
)
|
||||||
152
home-assistant/homeassistant/auth/models.py
Normal file
152
home-assistant/homeassistant/auth/models.py
Normal file
@@ -0,0 +1,152 @@
|
|||||||
|
"""Auth models."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
from ipaddress import IPv4Address, IPv6Address
|
||||||
|
import secrets
|
||||||
|
from typing import Any, NamedTuple
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
import attr
|
||||||
|
from attr import Attribute
|
||||||
|
from attr.setters import validate
|
||||||
|
from propcache import cached_property
|
||||||
|
|
||||||
|
from homeassistant.const import __version__
|
||||||
|
from homeassistant.data_entry_flow import FlowContext, FlowResult
|
||||||
|
from homeassistant.util import dt as dt_util
|
||||||
|
|
||||||
|
from . import permissions as perm_mdl
|
||||||
|
from .const import GROUP_ID_ADMIN
|
||||||
|
|
||||||
|
TOKEN_TYPE_NORMAL = "normal"
|
||||||
|
TOKEN_TYPE_SYSTEM = "system"
|
||||||
|
TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN = "long_lived_access_token"
|
||||||
|
|
||||||
|
|
||||||
|
class AuthFlowContext(FlowContext, total=False):
|
||||||
|
"""Typed context dict for auth flow."""
|
||||||
|
|
||||||
|
credential_only: bool
|
||||||
|
ip_address: IPv4Address | IPv6Address
|
||||||
|
redirect_uri: str
|
||||||
|
|
||||||
|
|
||||||
|
AuthFlowResult = FlowResult[AuthFlowContext, tuple[str, str]]
|
||||||
|
|
||||||
|
|
||||||
|
@attr.s(slots=True)
|
||||||
|
class Group:
|
||||||
|
"""A group."""
|
||||||
|
|
||||||
|
name: str | None = attr.ib()
|
||||||
|
policy: perm_mdl.PolicyType = attr.ib()
|
||||||
|
id: str = attr.ib(factory=lambda: uuid.uuid4().hex)
|
||||||
|
system_generated: bool = attr.ib(default=False)
|
||||||
|
|
||||||
|
|
||||||
|
def _handle_permissions_change(self: User, user_attr: Attribute, new: Any) -> Any:
|
||||||
|
"""Handle a change to a permissions."""
|
||||||
|
self.invalidate_cache()
|
||||||
|
return validate(self, user_attr, new)
|
||||||
|
|
||||||
|
|
||||||
|
@attr.s(slots=False)
|
||||||
|
class User:
|
||||||
|
"""A user."""
|
||||||
|
|
||||||
|
name: str | None = attr.ib()
|
||||||
|
perm_lookup: perm_mdl.PermissionLookup = attr.ib(eq=False, order=False)
|
||||||
|
id: str = attr.ib(factory=lambda: uuid.uuid4().hex)
|
||||||
|
is_owner: bool = attr.ib(default=False, on_setattr=_handle_permissions_change)
|
||||||
|
is_active: bool = attr.ib(default=False, on_setattr=_handle_permissions_change)
|
||||||
|
system_generated: bool = attr.ib(default=False)
|
||||||
|
local_only: bool = attr.ib(default=False)
|
||||||
|
|
||||||
|
groups: list[Group] = attr.ib(
|
||||||
|
factory=list, eq=False, order=False, on_setattr=_handle_permissions_change
|
||||||
|
)
|
||||||
|
|
||||||
|
# List of credentials of a user.
|
||||||
|
credentials: list[Credentials] = attr.ib(factory=list, eq=False, order=False)
|
||||||
|
|
||||||
|
# Tokens associated with a user.
|
||||||
|
refresh_tokens: dict[str, RefreshToken] = attr.ib(
|
||||||
|
factory=dict, eq=False, order=False
|
||||||
|
)
|
||||||
|
|
||||||
|
@cached_property
|
||||||
|
def permissions(self) -> perm_mdl.AbstractPermissions:
|
||||||
|
"""Return permissions object for user."""
|
||||||
|
if self.is_owner:
|
||||||
|
return perm_mdl.OwnerPermissions
|
||||||
|
return perm_mdl.PolicyPermissions(
|
||||||
|
perm_mdl.merge_policies([group.policy for group in self.groups]),
|
||||||
|
self.perm_lookup,
|
||||||
|
)
|
||||||
|
|
||||||
|
@cached_property
|
||||||
|
def is_admin(self) -> bool:
|
||||||
|
"""Return if user is part of the admin group."""
|
||||||
|
return self.is_owner or (
|
||||||
|
self.is_active and any(gr.id == GROUP_ID_ADMIN for gr in self.groups)
|
||||||
|
)
|
||||||
|
|
||||||
|
def invalidate_cache(self) -> None:
|
||||||
|
"""Invalidate permission and is_admin cache."""
|
||||||
|
for attr_to_invalidate in ("permissions", "is_admin"):
|
||||||
|
self.__dict__.pop(attr_to_invalidate, None)
|
||||||
|
|
||||||
|
|
||||||
|
@attr.s(slots=True)
|
||||||
|
class RefreshToken:
|
||||||
|
"""RefreshToken for a user to grant new access tokens."""
|
||||||
|
|
||||||
|
user: User = attr.ib()
|
||||||
|
client_id: str | None = attr.ib()
|
||||||
|
access_token_expiration: timedelta = attr.ib()
|
||||||
|
client_name: str | None = attr.ib(default=None)
|
||||||
|
client_icon: str | None = attr.ib(default=None)
|
||||||
|
token_type: str = attr.ib(
|
||||||
|
default=TOKEN_TYPE_NORMAL,
|
||||||
|
validator=attr.validators.in_(
|
||||||
|
(TOKEN_TYPE_NORMAL, TOKEN_TYPE_SYSTEM, TOKEN_TYPE_LONG_LIVED_ACCESS_TOKEN)
|
||||||
|
),
|
||||||
|
)
|
||||||
|
id: str = attr.ib(factory=lambda: uuid.uuid4().hex)
|
||||||
|
created_at: datetime = attr.ib(factory=dt_util.utcnow)
|
||||||
|
token: str = attr.ib(factory=lambda: secrets.token_hex(64))
|
||||||
|
jwt_key: str = attr.ib(factory=lambda: secrets.token_hex(64))
|
||||||
|
|
||||||
|
last_used_at: datetime | None = attr.ib(default=None)
|
||||||
|
last_used_ip: str | None = attr.ib(default=None)
|
||||||
|
|
||||||
|
expire_at: float | None = attr.ib(default=None)
|
||||||
|
|
||||||
|
credential: Credentials | None = attr.ib(default=None)
|
||||||
|
|
||||||
|
version: str | None = attr.ib(default=__version__)
|
||||||
|
|
||||||
|
|
||||||
|
@attr.s(slots=True)
|
||||||
|
class Credentials:
|
||||||
|
"""Credentials for a user on an auth provider."""
|
||||||
|
|
||||||
|
auth_provider_type: str = attr.ib()
|
||||||
|
auth_provider_id: str | None = attr.ib()
|
||||||
|
|
||||||
|
# Allow the auth provider to store data to represent their auth.
|
||||||
|
data: dict = attr.ib()
|
||||||
|
|
||||||
|
id: str = attr.ib(factory=lambda: uuid.uuid4().hex)
|
||||||
|
is_new: bool = attr.ib(default=True)
|
||||||
|
|
||||||
|
|
||||||
|
class UserMeta(NamedTuple):
|
||||||
|
"""User metadata."""
|
||||||
|
|
||||||
|
name: str | None
|
||||||
|
is_active: bool
|
||||||
|
group: str | None = None
|
||||||
|
local_only: bool | None = None
|
||||||
83
home-assistant/homeassistant/auth/permissions/__init__.py
Normal file
83
home-assistant/homeassistant/auth/permissions/__init__.py
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
"""Permissions for Home Assistant."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections.abc import Callable
|
||||||
|
|
||||||
|
import voluptuous as vol
|
||||||
|
|
||||||
|
from .const import CAT_ENTITIES
|
||||||
|
from .entities import ENTITY_POLICY_SCHEMA, compile_entities
|
||||||
|
from .merge import merge_policies
|
||||||
|
from .models import PermissionLookup
|
||||||
|
from .types import PolicyType
|
||||||
|
from .util import test_all
|
||||||
|
|
||||||
|
POLICY_SCHEMA = vol.Schema({vol.Optional(CAT_ENTITIES): ENTITY_POLICY_SCHEMA})
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"POLICY_SCHEMA",
|
||||||
|
"merge_policies",
|
||||||
|
"PermissionLookup",
|
||||||
|
"PolicyType",
|
||||||
|
"AbstractPermissions",
|
||||||
|
"PolicyPermissions",
|
||||||
|
"OwnerPermissions",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
class AbstractPermissions:
|
||||||
|
"""Default permissions class."""
|
||||||
|
|
||||||
|
_cached_entity_func: Callable[[str, str], bool] | None = None
|
||||||
|
|
||||||
|
def _entity_func(self) -> Callable[[str, str], bool]:
|
||||||
|
"""Return a function that can test entity access."""
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
def access_all_entities(self, key: str) -> bool:
|
||||||
|
"""Check if we have a certain access to all entities."""
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
def check_entity(self, entity_id: str, key: str) -> bool:
|
||||||
|
"""Check if we can access entity."""
|
||||||
|
if (entity_func := self._cached_entity_func) is None:
|
||||||
|
entity_func = self._cached_entity_func = self._entity_func()
|
||||||
|
|
||||||
|
return entity_func(entity_id, key)
|
||||||
|
|
||||||
|
|
||||||
|
class PolicyPermissions(AbstractPermissions):
|
||||||
|
"""Handle permissions."""
|
||||||
|
|
||||||
|
def __init__(self, policy: PolicyType, perm_lookup: PermissionLookup) -> None:
|
||||||
|
"""Initialize the permission class."""
|
||||||
|
self._policy = policy
|
||||||
|
self._perm_lookup = perm_lookup
|
||||||
|
|
||||||
|
def access_all_entities(self, key: str) -> bool:
|
||||||
|
"""Check if we have a certain access to all entities."""
|
||||||
|
return test_all(self._policy.get(CAT_ENTITIES), key)
|
||||||
|
|
||||||
|
def _entity_func(self) -> Callable[[str, str], bool]:
|
||||||
|
"""Return a function that can test entity access."""
|
||||||
|
return compile_entities(self._policy.get(CAT_ENTITIES), self._perm_lookup)
|
||||||
|
|
||||||
|
def __eq__(self, other: object) -> bool:
|
||||||
|
"""Equals check."""
|
||||||
|
return isinstance(other, PolicyPermissions) and other._policy == self._policy
|
||||||
|
|
||||||
|
|
||||||
|
class _OwnerPermissions(AbstractPermissions):
|
||||||
|
"""Owner permissions."""
|
||||||
|
|
||||||
|
def access_all_entities(self, key: str) -> bool:
|
||||||
|
"""Check if we have a certain access to all entities."""
|
||||||
|
return True
|
||||||
|
|
||||||
|
def _entity_func(self) -> Callable[[str, str], bool]:
|
||||||
|
"""Return a function that can test entity access."""
|
||||||
|
return lambda entity_id, key: True
|
||||||
|
|
||||||
|
|
||||||
|
OwnerPermissions = _OwnerPermissions()
|
||||||
9
home-assistant/homeassistant/auth/permissions/const.py
Normal file
9
home-assistant/homeassistant/auth/permissions/const.py
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
"""Permission constants."""
|
||||||
|
|
||||||
|
CAT_ENTITIES = "entities"
|
||||||
|
CAT_CONFIG_ENTRIES = "config_entries"
|
||||||
|
SUBCAT_ALL = "all"
|
||||||
|
|
||||||
|
POLICY_READ = "read"
|
||||||
|
POLICY_CONTROL = "control"
|
||||||
|
POLICY_EDIT = "edit"
|
||||||
101
home-assistant/homeassistant/auth/permissions/entities.py
Normal file
101
home-assistant/homeassistant/auth/permissions/entities.py
Normal file
@@ -0,0 +1,101 @@
|
|||||||
|
"""Entity permissions."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections import OrderedDict
|
||||||
|
from collections.abc import Callable
|
||||||
|
|
||||||
|
import voluptuous as vol
|
||||||
|
|
||||||
|
from .const import POLICY_CONTROL, POLICY_EDIT, POLICY_READ, SUBCAT_ALL
|
||||||
|
from .models import PermissionLookup
|
||||||
|
from .types import CategoryType, SubCategoryDict, ValueType
|
||||||
|
from .util import SubCatLookupType, compile_policy, lookup_all
|
||||||
|
|
||||||
|
SINGLE_ENTITY_SCHEMA = vol.Any(
|
||||||
|
True,
|
||||||
|
vol.Schema(
|
||||||
|
{
|
||||||
|
vol.Optional(POLICY_READ): True,
|
||||||
|
vol.Optional(POLICY_CONTROL): True,
|
||||||
|
vol.Optional(POLICY_EDIT): True,
|
||||||
|
}
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
ENTITY_DOMAINS = "domains"
|
||||||
|
ENTITY_AREAS = "area_ids"
|
||||||
|
ENTITY_DEVICE_IDS = "device_ids"
|
||||||
|
ENTITY_ENTITY_IDS = "entity_ids"
|
||||||
|
|
||||||
|
ENTITY_VALUES_SCHEMA = vol.Any(True, vol.Schema({str: SINGLE_ENTITY_SCHEMA}))
|
||||||
|
|
||||||
|
ENTITY_POLICY_SCHEMA = vol.Any(
|
||||||
|
True,
|
||||||
|
vol.Schema(
|
||||||
|
{
|
||||||
|
vol.Optional(SUBCAT_ALL): SINGLE_ENTITY_SCHEMA,
|
||||||
|
vol.Optional(ENTITY_AREAS): ENTITY_VALUES_SCHEMA,
|
||||||
|
vol.Optional(ENTITY_DEVICE_IDS): ENTITY_VALUES_SCHEMA,
|
||||||
|
vol.Optional(ENTITY_DOMAINS): ENTITY_VALUES_SCHEMA,
|
||||||
|
vol.Optional(ENTITY_ENTITY_IDS): ENTITY_VALUES_SCHEMA,
|
||||||
|
}
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _lookup_domain(
|
||||||
|
perm_lookup: PermissionLookup, domains_dict: SubCategoryDict, entity_id: str
|
||||||
|
) -> ValueType | None:
|
||||||
|
"""Look up entity permissions by domain."""
|
||||||
|
return domains_dict.get(entity_id.partition(".")[0])
|
||||||
|
|
||||||
|
|
||||||
|
def _lookup_area(
|
||||||
|
perm_lookup: PermissionLookup, area_dict: SubCategoryDict, entity_id: str
|
||||||
|
) -> ValueType | None:
|
||||||
|
"""Look up entity permissions by area."""
|
||||||
|
entity_entry = perm_lookup.entity_registry.async_get(entity_id)
|
||||||
|
|
||||||
|
if entity_entry is None or entity_entry.device_id is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
device_entry = perm_lookup.device_registry.async_get(entity_entry.device_id)
|
||||||
|
|
||||||
|
if device_entry is None or device_entry.area_id is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
return area_dict.get(device_entry.area_id)
|
||||||
|
|
||||||
|
|
||||||
|
def _lookup_device(
|
||||||
|
perm_lookup: PermissionLookup, devices_dict: SubCategoryDict, entity_id: str
|
||||||
|
) -> ValueType | None:
|
||||||
|
"""Look up entity permissions by device."""
|
||||||
|
entity_entry = perm_lookup.entity_registry.async_get(entity_id)
|
||||||
|
|
||||||
|
if entity_entry is None or entity_entry.device_id is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
return devices_dict.get(entity_entry.device_id)
|
||||||
|
|
||||||
|
|
||||||
|
def _lookup_entity_id(
|
||||||
|
perm_lookup: PermissionLookup, entities_dict: SubCategoryDict, entity_id: str
|
||||||
|
) -> ValueType | None:
|
||||||
|
"""Look up entity permission by entity id."""
|
||||||
|
return entities_dict.get(entity_id)
|
||||||
|
|
||||||
|
|
||||||
|
def compile_entities(
|
||||||
|
policy: CategoryType, perm_lookup: PermissionLookup
|
||||||
|
) -> Callable[[str, str], bool]:
|
||||||
|
"""Compile policy into a function that tests policy."""
|
||||||
|
subcategories: SubCatLookupType = OrderedDict()
|
||||||
|
subcategories[ENTITY_ENTITY_IDS] = _lookup_entity_id
|
||||||
|
subcategories[ENTITY_DEVICE_IDS] = _lookup_device
|
||||||
|
subcategories[ENTITY_AREAS] = _lookup_area
|
||||||
|
subcategories[ENTITY_DOMAINS] = _lookup_domain
|
||||||
|
subcategories[SUBCAT_ALL] = lookup_all
|
||||||
|
|
||||||
|
return compile_policy(policy, subcategories, perm_lookup)
|
||||||
50
home-assistant/homeassistant/auth/permissions/events.py
Normal file
50
home-assistant/homeassistant/auth/permissions/events.py
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
"""Permission for events."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any, Final
|
||||||
|
|
||||||
|
from homeassistant.const import (
|
||||||
|
EVENT_COMPONENT_LOADED,
|
||||||
|
EVENT_CORE_CONFIG_UPDATE,
|
||||||
|
EVENT_LOVELACE_UPDATED,
|
||||||
|
EVENT_PANELS_UPDATED,
|
||||||
|
EVENT_RECORDER_5MIN_STATISTICS_GENERATED,
|
||||||
|
EVENT_RECORDER_HOURLY_STATISTICS_GENERATED,
|
||||||
|
EVENT_SERVICE_REGISTERED,
|
||||||
|
EVENT_SERVICE_REMOVED,
|
||||||
|
EVENT_SHOPPING_LIST_UPDATED,
|
||||||
|
EVENT_STATE_CHANGED,
|
||||||
|
EVENT_THEMES_UPDATED,
|
||||||
|
)
|
||||||
|
from homeassistant.helpers.area_registry import EVENT_AREA_REGISTRY_UPDATED
|
||||||
|
from homeassistant.helpers.category_registry import EVENT_CATEGORY_REGISTRY_UPDATED
|
||||||
|
from homeassistant.helpers.device_registry import EVENT_DEVICE_REGISTRY_UPDATED
|
||||||
|
from homeassistant.helpers.entity_registry import EVENT_ENTITY_REGISTRY_UPDATED
|
||||||
|
from homeassistant.helpers.floor_registry import EVENT_FLOOR_REGISTRY_UPDATED
|
||||||
|
from homeassistant.helpers.issue_registry import EVENT_REPAIRS_ISSUE_REGISTRY_UPDATED
|
||||||
|
from homeassistant.helpers.label_registry import EVENT_LABEL_REGISTRY_UPDATED
|
||||||
|
from homeassistant.util.event_type import EventType
|
||||||
|
|
||||||
|
# These are events that do not contain any sensitive data
|
||||||
|
# Except for state_changed, which is handled accordingly.
|
||||||
|
SUBSCRIBE_ALLOWLIST: Final[set[EventType[Any] | str]] = {
|
||||||
|
EVENT_AREA_REGISTRY_UPDATED,
|
||||||
|
EVENT_COMPONENT_LOADED,
|
||||||
|
EVENT_CORE_CONFIG_UPDATE,
|
||||||
|
EVENT_DEVICE_REGISTRY_UPDATED,
|
||||||
|
EVENT_ENTITY_REGISTRY_UPDATED,
|
||||||
|
EVENT_REPAIRS_ISSUE_REGISTRY_UPDATED,
|
||||||
|
EVENT_LOVELACE_UPDATED,
|
||||||
|
EVENT_PANELS_UPDATED,
|
||||||
|
EVENT_RECORDER_5MIN_STATISTICS_GENERATED,
|
||||||
|
EVENT_RECORDER_HOURLY_STATISTICS_GENERATED,
|
||||||
|
EVENT_SERVICE_REGISTERED,
|
||||||
|
EVENT_SERVICE_REMOVED,
|
||||||
|
EVENT_SHOPPING_LIST_UPDATED,
|
||||||
|
EVENT_STATE_CHANGED,
|
||||||
|
EVENT_THEMES_UPDATED,
|
||||||
|
EVENT_LABEL_REGISTRY_UPDATED,
|
||||||
|
EVENT_CATEGORY_REGISTRY_UPDATED,
|
||||||
|
EVENT_FLOOR_REGISTRY_UPDATED,
|
||||||
|
}
|
||||||
65
home-assistant/homeassistant/auth/permissions/merge.py
Normal file
65
home-assistant/homeassistant/auth/permissions/merge.py
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
"""Merging of policies."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import cast
|
||||||
|
|
||||||
|
from .types import CategoryType, PolicyType
|
||||||
|
|
||||||
|
|
||||||
|
def merge_policies(policies: list[PolicyType]) -> PolicyType:
|
||||||
|
"""Merge policies."""
|
||||||
|
new_policy: dict[str, CategoryType] = {}
|
||||||
|
seen: set[str] = set()
|
||||||
|
for policy in policies:
|
||||||
|
for category in policy:
|
||||||
|
if category in seen:
|
||||||
|
continue
|
||||||
|
seen.add(category)
|
||||||
|
new_policy[category] = _merge_policies(
|
||||||
|
[policy.get(category) for policy in policies]
|
||||||
|
)
|
||||||
|
cast(PolicyType, new_policy)
|
||||||
|
return new_policy
|
||||||
|
|
||||||
|
|
||||||
|
def _merge_policies(sources: list[CategoryType]) -> CategoryType:
|
||||||
|
"""Merge a policy."""
|
||||||
|
# When merging policies, the most permissive wins.
|
||||||
|
# This means we order it like this:
|
||||||
|
# True > Dict > None
|
||||||
|
#
|
||||||
|
# True: allow everything
|
||||||
|
# Dict: specify more granular permissions
|
||||||
|
# None: no opinion
|
||||||
|
#
|
||||||
|
# If there are multiple sources with a dict as policy, we recursively
|
||||||
|
# merge each key in the source.
|
||||||
|
|
||||||
|
policy: CategoryType = None
|
||||||
|
seen: set[str] = set()
|
||||||
|
for source in sources:
|
||||||
|
if source is None:
|
||||||
|
continue
|
||||||
|
|
||||||
|
# A source that's True will always win. Shortcut return.
|
||||||
|
if source is True:
|
||||||
|
return True
|
||||||
|
|
||||||
|
assert isinstance(source, dict)
|
||||||
|
|
||||||
|
if policy is None:
|
||||||
|
policy = cast(CategoryType, {})
|
||||||
|
|
||||||
|
assert isinstance(policy, dict)
|
||||||
|
|
||||||
|
for key in source:
|
||||||
|
if key in seen:
|
||||||
|
continue
|
||||||
|
seen.add(key)
|
||||||
|
|
||||||
|
key_sources = [src.get(key) for src in sources if isinstance(src, dict)]
|
||||||
|
|
||||||
|
policy[key] = _merge_policies(key_sources)
|
||||||
|
|
||||||
|
return policy
|
||||||
18
home-assistant/homeassistant/auth/permissions/models.py
Normal file
18
home-assistant/homeassistant/auth/permissions/models.py
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
"""Models for permissions."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
import attr
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from homeassistant.helpers import device_registry as dr, entity_registry as er
|
||||||
|
|
||||||
|
|
||||||
|
@attr.s(slots=True)
|
||||||
|
class PermissionLookup:
|
||||||
|
"""Class to hold data for permission lookups."""
|
||||||
|
|
||||||
|
entity_registry: er.EntityRegistry = attr.ib()
|
||||||
|
device_registry: dr.DeviceRegistry = attr.ib()
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
"""System policies."""
|
||||||
|
|
||||||
|
from .const import CAT_ENTITIES, POLICY_READ, SUBCAT_ALL
|
||||||
|
|
||||||
|
ADMIN_POLICY = {CAT_ENTITIES: True}
|
||||||
|
|
||||||
|
USER_POLICY = {CAT_ENTITIES: True}
|
||||||
|
|
||||||
|
READ_ONLY_POLICY = {CAT_ENTITIES: {SUBCAT_ALL: {POLICY_READ: True}}}
|
||||||
27
home-assistant/homeassistant/auth/permissions/types.py
Normal file
27
home-assistant/homeassistant/auth/permissions/types.py
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
"""Common code for permissions."""
|
||||||
|
|
||||||
|
from collections.abc import Mapping
|
||||||
|
|
||||||
|
# MyPy doesn't support recursion yet. So writing it out as far as we need.
|
||||||
|
|
||||||
|
type ValueType = (
|
||||||
|
# Example: entities.all = { read: true, control: true }
|
||||||
|
Mapping[str, bool] | bool | None
|
||||||
|
)
|
||||||
|
|
||||||
|
# Example: entities.domains = { light: … }
|
||||||
|
type SubCategoryDict = Mapping[str, ValueType]
|
||||||
|
|
||||||
|
type SubCategoryType = SubCategoryDict | bool | None
|
||||||
|
|
||||||
|
type CategoryType = (
|
||||||
|
# Example: entities.domains
|
||||||
|
Mapping[str, SubCategoryType]
|
||||||
|
# Example: entities.all
|
||||||
|
| Mapping[str, ValueType]
|
||||||
|
| bool
|
||||||
|
| None
|
||||||
|
)
|
||||||
|
|
||||||
|
# Example: { entities: … }
|
||||||
|
type PolicyType = Mapping[str, CategoryType]
|
||||||
113
home-assistant/homeassistant/auth/permissions/util.py
Normal file
113
home-assistant/homeassistant/auth/permissions/util.py
Normal file
@@ -0,0 +1,113 @@
|
|||||||
|
"""Helpers to deal with permissions."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections.abc import Callable
|
||||||
|
from functools import wraps
|
||||||
|
from typing import cast
|
||||||
|
|
||||||
|
from .const import SUBCAT_ALL
|
||||||
|
from .models import PermissionLookup
|
||||||
|
from .types import CategoryType, SubCategoryDict, ValueType
|
||||||
|
|
||||||
|
type LookupFunc = Callable[[PermissionLookup, SubCategoryDict, str], ValueType | None]
|
||||||
|
type SubCatLookupType = dict[str, LookupFunc]
|
||||||
|
|
||||||
|
|
||||||
|
def lookup_all(
|
||||||
|
perm_lookup: PermissionLookup, lookup_dict: SubCategoryDict, object_id: str
|
||||||
|
) -> ValueType:
|
||||||
|
"""Look up permission for all."""
|
||||||
|
# In case of ALL category, lookup_dict IS the schema.
|
||||||
|
return cast(ValueType, lookup_dict)
|
||||||
|
|
||||||
|
|
||||||
|
def compile_policy(
|
||||||
|
policy: CategoryType, subcategories: SubCatLookupType, perm_lookup: PermissionLookup
|
||||||
|
) -> Callable[[str, str], bool]:
|
||||||
|
"""Compile policy into a function that tests policy.
|
||||||
|
|
||||||
|
Subcategories are mapping key -> lookup function, ordered by highest
|
||||||
|
priority first.
|
||||||
|
"""
|
||||||
|
# None, False, empty dict
|
||||||
|
if not policy:
|
||||||
|
|
||||||
|
def apply_policy_deny_all(entity_id: str, key: str) -> bool:
|
||||||
|
"""Decline all."""
|
||||||
|
return False
|
||||||
|
|
||||||
|
return apply_policy_deny_all
|
||||||
|
|
||||||
|
if policy is True:
|
||||||
|
|
||||||
|
def apply_policy_allow_all(entity_id: str, key: str) -> bool:
|
||||||
|
"""Approve all."""
|
||||||
|
return True
|
||||||
|
|
||||||
|
return apply_policy_allow_all
|
||||||
|
|
||||||
|
assert isinstance(policy, dict)
|
||||||
|
|
||||||
|
funcs: list[Callable[[str, str], bool | None]] = []
|
||||||
|
|
||||||
|
for key, lookup_func in subcategories.items():
|
||||||
|
lookup_value = policy.get(key)
|
||||||
|
|
||||||
|
# If any lookup value is `True`, it will always be positive
|
||||||
|
if isinstance(lookup_value, bool):
|
||||||
|
return lambda object_id, key: True
|
||||||
|
|
||||||
|
if lookup_value is not None:
|
||||||
|
funcs.append(_gen_dict_test_func(perm_lookup, lookup_func, lookup_value))
|
||||||
|
|
||||||
|
if len(funcs) == 1:
|
||||||
|
func = funcs[0]
|
||||||
|
|
||||||
|
@wraps(func)
|
||||||
|
def apply_policy_func(object_id: str, key: str) -> bool:
|
||||||
|
"""Apply a single policy function."""
|
||||||
|
return func(object_id, key) is True
|
||||||
|
|
||||||
|
return apply_policy_func
|
||||||
|
|
||||||
|
def apply_policy_funcs(object_id: str, key: str) -> bool:
|
||||||
|
"""Apply several policy functions."""
|
||||||
|
for func in funcs:
|
||||||
|
if (result := func(object_id, key)) is not None:
|
||||||
|
return result
|
||||||
|
return False
|
||||||
|
|
||||||
|
return apply_policy_funcs
|
||||||
|
|
||||||
|
|
||||||
|
def _gen_dict_test_func(
|
||||||
|
perm_lookup: PermissionLookup, lookup_func: LookupFunc, lookup_dict: SubCategoryDict
|
||||||
|
) -> Callable[[str, str], bool | None]:
|
||||||
|
"""Generate a lookup function."""
|
||||||
|
|
||||||
|
def test_value(object_id: str, key: str) -> bool | None:
|
||||||
|
"""Test if permission is allowed based on the keys."""
|
||||||
|
schema: ValueType = lookup_func(perm_lookup, lookup_dict, object_id)
|
||||||
|
|
||||||
|
if schema is None or isinstance(schema, bool):
|
||||||
|
return schema
|
||||||
|
|
||||||
|
assert isinstance(schema, dict)
|
||||||
|
|
||||||
|
return schema.get(key)
|
||||||
|
|
||||||
|
return test_value
|
||||||
|
|
||||||
|
|
||||||
|
def test_all(policy: CategoryType, key: str) -> bool:
|
||||||
|
"""Test if a policy has an ALL access for a specific key."""
|
||||||
|
if not isinstance(policy, dict):
|
||||||
|
return bool(policy)
|
||||||
|
|
||||||
|
all_policy = policy.get(SUBCAT_ALL)
|
||||||
|
|
||||||
|
if not isinstance(all_policy, dict):
|
||||||
|
return bool(all_policy)
|
||||||
|
|
||||||
|
return all_policy.get(key, False) # type: ignore[no-any-return]
|
||||||
306
home-assistant/homeassistant/auth/providers/__init__.py
Normal file
306
home-assistant/homeassistant/auth/providers/__init__.py
Normal file
@@ -0,0 +1,306 @@
|
|||||||
|
"""Auth providers for Home Assistant."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections.abc import Mapping
|
||||||
|
import logging
|
||||||
|
import types
|
||||||
|
from typing import Any, Generic
|
||||||
|
|
||||||
|
from typing_extensions import TypeVar
|
||||||
|
import voluptuous as vol
|
||||||
|
from voluptuous.humanize import humanize_error
|
||||||
|
|
||||||
|
from homeassistant import requirements
|
||||||
|
from homeassistant.const import CONF_ID, CONF_NAME, CONF_TYPE
|
||||||
|
from homeassistant.core import HomeAssistant, callback
|
||||||
|
from homeassistant.data_entry_flow import FlowHandler
|
||||||
|
from homeassistant.exceptions import HomeAssistantError
|
||||||
|
from homeassistant.helpers.importlib import async_import_module
|
||||||
|
from homeassistant.util import dt as dt_util
|
||||||
|
from homeassistant.util.decorator import Registry
|
||||||
|
from homeassistant.util.hass_dict import HassKey
|
||||||
|
|
||||||
|
from ..auth_store import AuthStore
|
||||||
|
from ..const import MFA_SESSION_EXPIRATION
|
||||||
|
from ..models import (
|
||||||
|
AuthFlowContext,
|
||||||
|
AuthFlowResult,
|
||||||
|
Credentials,
|
||||||
|
RefreshToken,
|
||||||
|
User,
|
||||||
|
UserMeta,
|
||||||
|
)
|
||||||
|
|
||||||
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
DATA_REQS: HassKey[set[str]] = HassKey("auth_prov_reqs_processed")
|
||||||
|
|
||||||
|
AUTH_PROVIDERS: Registry[str, type[AuthProvider]] = Registry()
|
||||||
|
|
||||||
|
AUTH_PROVIDER_SCHEMA = vol.Schema(
|
||||||
|
{
|
||||||
|
vol.Required(CONF_TYPE): str,
|
||||||
|
vol.Optional(CONF_NAME): str,
|
||||||
|
# Specify ID if you have two auth providers for same type.
|
||||||
|
vol.Optional(CONF_ID): str,
|
||||||
|
},
|
||||||
|
extra=vol.ALLOW_EXTRA,
|
||||||
|
)
|
||||||
|
|
||||||
|
_AuthProviderT = TypeVar("_AuthProviderT", bound="AuthProvider", default="AuthProvider")
|
||||||
|
|
||||||
|
|
||||||
|
class AuthProvider:
|
||||||
|
"""Provider of user authentication."""
|
||||||
|
|
||||||
|
DEFAULT_TITLE = "Unnamed auth provider"
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self, hass: HomeAssistant, store: AuthStore, config: dict[str, Any]
|
||||||
|
) -> None:
|
||||||
|
"""Initialize an auth provider."""
|
||||||
|
self.hass = hass
|
||||||
|
self.store = store
|
||||||
|
self.config = config
|
||||||
|
|
||||||
|
@property
|
||||||
|
def id(self) -> str | None:
|
||||||
|
"""Return id of the auth provider.
|
||||||
|
|
||||||
|
Optional, can be None.
|
||||||
|
"""
|
||||||
|
return self.config.get(CONF_ID)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def type(self) -> str:
|
||||||
|
"""Return type of the provider."""
|
||||||
|
return self.config[CONF_TYPE] # type: ignore[no-any-return]
|
||||||
|
|
||||||
|
@property
|
||||||
|
def name(self) -> str:
|
||||||
|
"""Return the name of the auth provider."""
|
||||||
|
return self.config.get(CONF_NAME, self.DEFAULT_TITLE) # type: ignore[no-any-return]
|
||||||
|
|
||||||
|
@property
|
||||||
|
def support_mfa(self) -> bool:
|
||||||
|
"""Return whether multi-factor auth supported by the auth provider."""
|
||||||
|
return True
|
||||||
|
|
||||||
|
async def async_credentials(self) -> list[Credentials]:
|
||||||
|
"""Return all credentials of this provider."""
|
||||||
|
users = await self.store.async_get_users()
|
||||||
|
return [
|
||||||
|
credentials
|
||||||
|
for user in users
|
||||||
|
for credentials in user.credentials
|
||||||
|
if (
|
||||||
|
credentials.auth_provider_type == self.type
|
||||||
|
and credentials.auth_provider_id == self.id
|
||||||
|
)
|
||||||
|
]
|
||||||
|
|
||||||
|
@callback
|
||||||
|
def async_create_credentials(self, data: dict[str, str]) -> Credentials:
|
||||||
|
"""Create credentials."""
|
||||||
|
return Credentials(
|
||||||
|
auth_provider_type=self.type, auth_provider_id=self.id, data=data
|
||||||
|
)
|
||||||
|
|
||||||
|
# Implement by extending class
|
||||||
|
|
||||||
|
async def async_login_flow(self, context: AuthFlowContext | None) -> LoginFlow[Any]:
|
||||||
|
"""Return the data flow for logging in with auth provider.
|
||||||
|
|
||||||
|
Auth provider should extend LoginFlow and return an instance.
|
||||||
|
"""
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
async def async_get_or_create_credentials(
|
||||||
|
self, flow_result: Mapping[str, str]
|
||||||
|
) -> Credentials:
|
||||||
|
"""Get credentials based on the flow result."""
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
async def async_user_meta_for_credentials(
|
||||||
|
self, credentials: Credentials
|
||||||
|
) -> UserMeta:
|
||||||
|
"""Return extra user metadata for credentials.
|
||||||
|
|
||||||
|
Will be used to populate info when creating a new user.
|
||||||
|
"""
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
async def async_initialize(self) -> None:
|
||||||
|
"""Initialize the auth provider."""
|
||||||
|
|
||||||
|
@callback
|
||||||
|
def async_validate_refresh_token(
|
||||||
|
self, refresh_token: RefreshToken, remote_ip: str | None = None
|
||||||
|
) -> None:
|
||||||
|
"""Verify a refresh token is still valid.
|
||||||
|
|
||||||
|
Optional hook for an auth provider to verify validity of a refresh token.
|
||||||
|
Should raise InvalidAuthError on errors.
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
async def auth_provider_from_config(
|
||||||
|
hass: HomeAssistant, store: AuthStore, config: dict[str, Any]
|
||||||
|
) -> AuthProvider:
|
||||||
|
"""Initialize an auth provider from a config."""
|
||||||
|
provider_name: str = config[CONF_TYPE]
|
||||||
|
module = await load_auth_provider_module(hass, provider_name)
|
||||||
|
|
||||||
|
try:
|
||||||
|
config = module.CONFIG_SCHEMA(config)
|
||||||
|
except vol.Invalid as err:
|
||||||
|
_LOGGER.error(
|
||||||
|
"Invalid configuration for auth provider %s: %s",
|
||||||
|
provider_name,
|
||||||
|
humanize_error(config, err),
|
||||||
|
)
|
||||||
|
raise
|
||||||
|
|
||||||
|
return AUTH_PROVIDERS[provider_name](hass, store, config)
|
||||||
|
|
||||||
|
|
||||||
|
async def load_auth_provider_module(
|
||||||
|
hass: HomeAssistant, provider: str
|
||||||
|
) -> types.ModuleType:
|
||||||
|
"""Load an auth provider."""
|
||||||
|
try:
|
||||||
|
module = await async_import_module(
|
||||||
|
hass, f"homeassistant.auth.providers.{provider}"
|
||||||
|
)
|
||||||
|
except ImportError as err:
|
||||||
|
_LOGGER.error("Unable to load auth provider %s: %s", provider, err)
|
||||||
|
raise HomeAssistantError(
|
||||||
|
f"Unable to load auth provider {provider}: {err}"
|
||||||
|
) from err
|
||||||
|
|
||||||
|
if hass.config.skip_pip or not hasattr(module, "REQUIREMENTS"):
|
||||||
|
return module
|
||||||
|
|
||||||
|
if (processed := hass.data.get(DATA_REQS)) is None:
|
||||||
|
processed = hass.data[DATA_REQS] = set()
|
||||||
|
elif provider in processed:
|
||||||
|
return module
|
||||||
|
|
||||||
|
reqs = module.REQUIREMENTS
|
||||||
|
await requirements.async_process_requirements(
|
||||||
|
hass, f"auth provider {provider}", reqs
|
||||||
|
)
|
||||||
|
|
||||||
|
processed.add(provider)
|
||||||
|
return module
|
||||||
|
|
||||||
|
|
||||||
|
class LoginFlow(
|
||||||
|
FlowHandler[AuthFlowContext, AuthFlowResult, tuple[str, str]],
|
||||||
|
Generic[_AuthProviderT],
|
||||||
|
):
|
||||||
|
"""Handler for the login flow."""
|
||||||
|
|
||||||
|
_flow_result = AuthFlowResult
|
||||||
|
|
||||||
|
def __init__(self, auth_provider: _AuthProviderT) -> None:
|
||||||
|
"""Initialize the login flow."""
|
||||||
|
self._auth_provider = auth_provider
|
||||||
|
self._auth_module_id: str | None = None
|
||||||
|
self._auth_manager = auth_provider.hass.auth
|
||||||
|
self.available_mfa_modules: dict[str, str] = {}
|
||||||
|
self.created_at = dt_util.utcnow()
|
||||||
|
self.invalid_mfa_times = 0
|
||||||
|
self.user: User | None = None
|
||||||
|
self.credential: Credentials | None = None
|
||||||
|
|
||||||
|
async def async_step_init(
|
||||||
|
self, user_input: dict[str, str] | None = None
|
||||||
|
) -> AuthFlowResult:
|
||||||
|
"""Handle the first step of login flow.
|
||||||
|
|
||||||
|
Return self.async_show_form(step_id='init') if user_input is None.
|
||||||
|
Return await self.async_finish(flow_result) if login init step pass.
|
||||||
|
"""
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
async def async_step_select_mfa_module(
|
||||||
|
self, user_input: dict[str, str] | None = None
|
||||||
|
) -> AuthFlowResult:
|
||||||
|
"""Handle the step of select mfa module."""
|
||||||
|
errors = {}
|
||||||
|
|
||||||
|
if user_input is not None:
|
||||||
|
auth_module = user_input.get("multi_factor_auth_module")
|
||||||
|
if auth_module in self.available_mfa_modules:
|
||||||
|
self._auth_module_id = auth_module
|
||||||
|
return await self.async_step_mfa()
|
||||||
|
errors["base"] = "invalid_auth_module"
|
||||||
|
|
||||||
|
if len(self.available_mfa_modules) == 1:
|
||||||
|
self._auth_module_id = list(self.available_mfa_modules)[0]
|
||||||
|
return await self.async_step_mfa()
|
||||||
|
|
||||||
|
return self.async_show_form(
|
||||||
|
step_id="select_mfa_module",
|
||||||
|
data_schema=vol.Schema(
|
||||||
|
{"multi_factor_auth_module": vol.In(self.available_mfa_modules)}
|
||||||
|
),
|
||||||
|
errors=errors,
|
||||||
|
)
|
||||||
|
|
||||||
|
async def async_step_mfa(
|
||||||
|
self, user_input: dict[str, str] | None = None
|
||||||
|
) -> AuthFlowResult:
|
||||||
|
"""Handle the step of mfa validation."""
|
||||||
|
assert self.credential
|
||||||
|
assert self.user
|
||||||
|
|
||||||
|
errors = {}
|
||||||
|
|
||||||
|
assert self._auth_module_id is not None
|
||||||
|
auth_module = self._auth_manager.get_auth_mfa_module(self._auth_module_id)
|
||||||
|
if auth_module is None:
|
||||||
|
# Given an invalid input to async_step_select_mfa_module
|
||||||
|
# will show invalid_auth_module error
|
||||||
|
return await self.async_step_select_mfa_module(user_input={})
|
||||||
|
|
||||||
|
if user_input is None and hasattr(
|
||||||
|
auth_module, "async_initialize_login_mfa_step"
|
||||||
|
):
|
||||||
|
try:
|
||||||
|
await auth_module.async_initialize_login_mfa_step(self.user.id)
|
||||||
|
except HomeAssistantError:
|
||||||
|
_LOGGER.exception("Error initializing MFA step")
|
||||||
|
return self.async_abort(reason="unknown_error")
|
||||||
|
|
||||||
|
if user_input is not None:
|
||||||
|
expires = self.created_at + MFA_SESSION_EXPIRATION
|
||||||
|
if dt_util.utcnow() > expires:
|
||||||
|
return self.async_abort(reason="login_expired")
|
||||||
|
|
||||||
|
result = await auth_module.async_validate(self.user.id, user_input)
|
||||||
|
if not result:
|
||||||
|
errors["base"] = "invalid_code"
|
||||||
|
self.invalid_mfa_times += 1
|
||||||
|
if self.invalid_mfa_times >= auth_module.MAX_RETRY_TIME > 0:
|
||||||
|
return self.async_abort(reason="too_many_retry")
|
||||||
|
|
||||||
|
if not errors:
|
||||||
|
return await self.async_finish(self.credential)
|
||||||
|
|
||||||
|
description_placeholders: dict[str, str] = {
|
||||||
|
"mfa_module_name": auth_module.name,
|
||||||
|
"mfa_module_id": auth_module.id,
|
||||||
|
}
|
||||||
|
|
||||||
|
return self.async_show_form(
|
||||||
|
step_id="mfa",
|
||||||
|
data_schema=auth_module.input_schema,
|
||||||
|
description_placeholders=description_placeholders,
|
||||||
|
errors=errors,
|
||||||
|
)
|
||||||
|
|
||||||
|
async def async_finish(self, flow_result: Any) -> AuthFlowResult:
|
||||||
|
"""Handle the pass of login flow."""
|
||||||
|
return self.async_create_entry(data=flow_result)
|
||||||
169
home-assistant/homeassistant/auth/providers/command_line.py
Normal file
169
home-assistant/homeassistant/auth/providers/command_line.py
Normal file
@@ -0,0 +1,169 @@
|
|||||||
|
"""Auth provider that validates credentials via an external command."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
from collections.abc import Mapping
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import voluptuous as vol
|
||||||
|
|
||||||
|
from homeassistant.const import CONF_COMMAND
|
||||||
|
from homeassistant.exceptions import HomeAssistantError
|
||||||
|
|
||||||
|
from ..models import AuthFlowContext, AuthFlowResult, Credentials, UserMeta
|
||||||
|
from . import AUTH_PROVIDER_SCHEMA, AUTH_PROVIDERS, AuthProvider, LoginFlow
|
||||||
|
|
||||||
|
CONF_ARGS = "args"
|
||||||
|
CONF_META = "meta"
|
||||||
|
|
||||||
|
CONFIG_SCHEMA = AUTH_PROVIDER_SCHEMA.extend(
|
||||||
|
{
|
||||||
|
vol.Required(CONF_COMMAND): vol.All(
|
||||||
|
str, os.path.normpath, msg="must be an absolute path"
|
||||||
|
),
|
||||||
|
vol.Optional(CONF_ARGS, default=None): vol.Any(vol.DefaultTo(list), [str]),
|
||||||
|
vol.Optional(CONF_META, default=False): bool,
|
||||||
|
},
|
||||||
|
extra=vol.PREVENT_EXTRA,
|
||||||
|
)
|
||||||
|
|
||||||
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class InvalidAuthError(HomeAssistantError):
|
||||||
|
"""Raised when authentication with given credentials fails."""
|
||||||
|
|
||||||
|
|
||||||
|
@AUTH_PROVIDERS.register("command_line")
|
||||||
|
class CommandLineAuthProvider(AuthProvider):
|
||||||
|
"""Auth provider validating credentials by calling a command."""
|
||||||
|
|
||||||
|
DEFAULT_TITLE = "Command Line Authentication"
|
||||||
|
|
||||||
|
# which keys to accept from a program's stdout
|
||||||
|
ALLOWED_META_KEYS = (
|
||||||
|
"name",
|
||||||
|
"group",
|
||||||
|
"local_only",
|
||||||
|
)
|
||||||
|
|
||||||
|
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
||||||
|
"""Extend parent's __init__.
|
||||||
|
|
||||||
|
Adds self._user_meta dictionary to hold the user-specific
|
||||||
|
attributes provided by external programs.
|
||||||
|
"""
|
||||||
|
super().__init__(*args, **kwargs)
|
||||||
|
self._user_meta: dict[str, dict[str, Any]] = {}
|
||||||
|
|
||||||
|
async def async_login_flow(
|
||||||
|
self, context: AuthFlowContext | None
|
||||||
|
) -> CommandLineLoginFlow:
|
||||||
|
"""Return a flow to login."""
|
||||||
|
return CommandLineLoginFlow(self)
|
||||||
|
|
||||||
|
async def async_validate_login(self, username: str, password: str) -> None:
|
||||||
|
"""Validate a username and password."""
|
||||||
|
env = {"username": username, "password": password}
|
||||||
|
try:
|
||||||
|
process = await asyncio.create_subprocess_exec(
|
||||||
|
self.config[CONF_COMMAND],
|
||||||
|
*self.config[CONF_ARGS],
|
||||||
|
env=env,
|
||||||
|
stdout=asyncio.subprocess.PIPE if self.config[CONF_META] else None,
|
||||||
|
close_fds=False, # required for posix_spawn
|
||||||
|
)
|
||||||
|
stdout, _ = await process.communicate()
|
||||||
|
except OSError as err:
|
||||||
|
# happens when command doesn't exist or permission is denied
|
||||||
|
_LOGGER.error("Error while authenticating %r: %s", username, err)
|
||||||
|
raise InvalidAuthError from err
|
||||||
|
|
||||||
|
if process.returncode != 0:
|
||||||
|
_LOGGER.error(
|
||||||
|
"User %r failed to authenticate, command exited with code %d",
|
||||||
|
username,
|
||||||
|
process.returncode,
|
||||||
|
)
|
||||||
|
raise InvalidAuthError
|
||||||
|
|
||||||
|
if self.config[CONF_META]:
|
||||||
|
meta: dict[str, str] = {}
|
||||||
|
for _line in stdout.splitlines():
|
||||||
|
try:
|
||||||
|
line = _line.decode().lstrip()
|
||||||
|
except ValueError:
|
||||||
|
# malformed line
|
||||||
|
continue
|
||||||
|
if line.startswith("#") or "=" not in line:
|
||||||
|
continue
|
||||||
|
key, _, value = line.partition("=")
|
||||||
|
key = key.strip()
|
||||||
|
value = value.strip()
|
||||||
|
if key in self.ALLOWED_META_KEYS:
|
||||||
|
meta[key] = value
|
||||||
|
self._user_meta[username] = meta
|
||||||
|
|
||||||
|
async def async_get_or_create_credentials(
|
||||||
|
self, flow_result: Mapping[str, str]
|
||||||
|
) -> Credentials:
|
||||||
|
"""Get credentials based on the flow result."""
|
||||||
|
username = flow_result["username"]
|
||||||
|
for credential in await self.async_credentials():
|
||||||
|
if credential.data["username"] == username:
|
||||||
|
return credential
|
||||||
|
|
||||||
|
# Create new credentials.
|
||||||
|
return self.async_create_credentials({"username": username})
|
||||||
|
|
||||||
|
async def async_user_meta_for_credentials(
|
||||||
|
self, credentials: Credentials
|
||||||
|
) -> UserMeta:
|
||||||
|
"""Return extra user metadata for credentials.
|
||||||
|
|
||||||
|
Currently, supports name, group and local_only.
|
||||||
|
"""
|
||||||
|
meta = self._user_meta.get(credentials.data["username"], {})
|
||||||
|
return UserMeta(
|
||||||
|
name=meta.get("name"),
|
||||||
|
is_active=True,
|
||||||
|
group=meta.get("group"),
|
||||||
|
local_only=meta.get("local_only") == "true",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class CommandLineLoginFlow(LoginFlow[CommandLineAuthProvider]):
|
||||||
|
"""Handler for the login flow."""
|
||||||
|
|
||||||
|
async def async_step_init(
|
||||||
|
self, user_input: dict[str, str] | None = None
|
||||||
|
) -> AuthFlowResult:
|
||||||
|
"""Handle the step of the form."""
|
||||||
|
errors = {}
|
||||||
|
|
||||||
|
if user_input is not None:
|
||||||
|
user_input["username"] = user_input["username"].strip()
|
||||||
|
try:
|
||||||
|
await self._auth_provider.async_validate_login(
|
||||||
|
user_input["username"], user_input["password"]
|
||||||
|
)
|
||||||
|
except InvalidAuthError:
|
||||||
|
errors["base"] = "invalid_auth"
|
||||||
|
|
||||||
|
if not errors:
|
||||||
|
user_input.pop("password")
|
||||||
|
return await self.async_finish(user_input)
|
||||||
|
|
||||||
|
return self.async_show_form(
|
||||||
|
step_id="init",
|
||||||
|
data_schema=vol.Schema(
|
||||||
|
{
|
||||||
|
vol.Required("username"): str,
|
||||||
|
vol.Required("password"): str,
|
||||||
|
}
|
||||||
|
),
|
||||||
|
errors=errors,
|
||||||
|
)
|
||||||
433
home-assistant/homeassistant/auth/providers/homeassistant.py
Normal file
433
home-assistant/homeassistant/auth/providers/homeassistant.py
Normal file
@@ -0,0 +1,433 @@
|
|||||||
|
"""Home Assistant auth provider."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import base64
|
||||||
|
from collections.abc import Mapping
|
||||||
|
import logging
|
||||||
|
from typing import Any, cast
|
||||||
|
|
||||||
|
import bcrypt
|
||||||
|
import voluptuous as vol
|
||||||
|
|
||||||
|
from homeassistant.const import CONF_ID
|
||||||
|
from homeassistant.core import HomeAssistant, callback
|
||||||
|
from homeassistant.exceptions import HomeAssistantError
|
||||||
|
from homeassistant.helpers import issue_registry as ir
|
||||||
|
from homeassistant.helpers.storage import Store
|
||||||
|
|
||||||
|
from ..models import AuthFlowContext, AuthFlowResult, Credentials, UserMeta
|
||||||
|
from . import AUTH_PROVIDER_SCHEMA, AUTH_PROVIDERS, AuthProvider, LoginFlow
|
||||||
|
|
||||||
|
STORAGE_VERSION = 1
|
||||||
|
STORAGE_KEY = "auth_provider.homeassistant"
|
||||||
|
|
||||||
|
|
||||||
|
def _disallow_id(conf: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
"""Disallow ID in config."""
|
||||||
|
if CONF_ID in conf:
|
||||||
|
raise vol.Invalid("ID is not allowed for the homeassistant auth provider.")
|
||||||
|
|
||||||
|
return conf
|
||||||
|
|
||||||
|
|
||||||
|
CONFIG_SCHEMA = vol.All(AUTH_PROVIDER_SCHEMA, _disallow_id)
|
||||||
|
|
||||||
|
|
||||||
|
@callback
|
||||||
|
def async_get_provider(hass: HomeAssistant) -> HassAuthProvider:
|
||||||
|
"""Get the provider."""
|
||||||
|
for prv in hass.auth.auth_providers:
|
||||||
|
if prv.type == "homeassistant":
|
||||||
|
return cast(HassAuthProvider, prv)
|
||||||
|
|
||||||
|
raise RuntimeError("Provider not found")
|
||||||
|
|
||||||
|
|
||||||
|
class InvalidAuth(HomeAssistantError):
|
||||||
|
"""Raised when we encounter invalid authentication."""
|
||||||
|
|
||||||
|
|
||||||
|
class InvalidUser(HomeAssistantError):
|
||||||
|
"""Raised when invalid user is specified.
|
||||||
|
|
||||||
|
Will not be raised when validating authentication.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
*args: object,
|
||||||
|
translation_key: str | None = None,
|
||||||
|
translation_placeholders: dict[str, str] | None = None,
|
||||||
|
) -> None:
|
||||||
|
"""Initialize exception."""
|
||||||
|
super().__init__(
|
||||||
|
*args,
|
||||||
|
translation_domain="auth",
|
||||||
|
translation_key=translation_key,
|
||||||
|
translation_placeholders=translation_placeholders,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class InvalidUsername(InvalidUser):
|
||||||
|
"""Raised when invalid username is specified.
|
||||||
|
|
||||||
|
Will not be raised when validating authentication.
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class Data:
|
||||||
|
"""Hold the user data."""
|
||||||
|
|
||||||
|
def __init__(self, hass: HomeAssistant) -> None:
|
||||||
|
"""Initialize the user data store."""
|
||||||
|
self.hass = hass
|
||||||
|
self._store = Store[dict[str, list[dict[str, str]]]](
|
||||||
|
hass, STORAGE_VERSION, STORAGE_KEY, private=True, atomic_writes=True
|
||||||
|
)
|
||||||
|
self._data: dict[str, list[dict[str, str]]] | None = None
|
||||||
|
# Legacy mode will allow usernames to start/end with whitespace
|
||||||
|
# and will compare usernames case-insensitive.
|
||||||
|
# Deprecated in June 2019 and will be removed in 2026.7
|
||||||
|
self.is_legacy = False
|
||||||
|
|
||||||
|
@callback
|
||||||
|
def normalize_username(
|
||||||
|
self, username: str, *, force_normalize: bool = False
|
||||||
|
) -> str:
|
||||||
|
"""Normalize a username based on the mode."""
|
||||||
|
if self.is_legacy and not force_normalize:
|
||||||
|
return username
|
||||||
|
|
||||||
|
return username.strip().casefold()
|
||||||
|
|
||||||
|
async def async_load(self) -> None:
|
||||||
|
"""Load stored data."""
|
||||||
|
if (data := await self._store.async_load()) is None:
|
||||||
|
data = cast(dict[str, list[dict[str, str]]], {"users": []})
|
||||||
|
|
||||||
|
self._async_check_for_not_normalized_usernames(data)
|
||||||
|
self._data = data
|
||||||
|
|
||||||
|
@callback
|
||||||
|
def _async_check_for_not_normalized_usernames(
|
||||||
|
self, data: dict[str, list[dict[str, str]]]
|
||||||
|
) -> None:
|
||||||
|
not_normalized_usernames: set[str] = set()
|
||||||
|
|
||||||
|
for user in data["users"]:
|
||||||
|
username = user["username"]
|
||||||
|
|
||||||
|
if self.normalize_username(username, force_normalize=True) != username:
|
||||||
|
logging.getLogger(__name__).warning(
|
||||||
|
(
|
||||||
|
"Home Assistant auth provider is running in legacy mode "
|
||||||
|
"because we detected usernames that are normalized (lowercase and without spaces)."
|
||||||
|
" Please change the username: '%s'."
|
||||||
|
),
|
||||||
|
username,
|
||||||
|
)
|
||||||
|
not_normalized_usernames.add(username)
|
||||||
|
|
||||||
|
if not_normalized_usernames:
|
||||||
|
self.is_legacy = True
|
||||||
|
ir.async_create_issue(
|
||||||
|
self.hass,
|
||||||
|
"auth",
|
||||||
|
"homeassistant_provider_not_normalized_usernames",
|
||||||
|
breaks_in_ha_version="2026.7.0",
|
||||||
|
is_fixable=False,
|
||||||
|
severity=ir.IssueSeverity.WARNING,
|
||||||
|
translation_key="homeassistant_provider_not_normalized_usernames",
|
||||||
|
translation_placeholders={
|
||||||
|
"usernames": f'- "{'"\n- "'.join(sorted(not_normalized_usernames))}"'
|
||||||
|
},
|
||||||
|
learn_more_url="homeassistant://config/users",
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
self.is_legacy = False
|
||||||
|
ir.async_delete_issue(
|
||||||
|
self.hass, "auth", "homeassistant_provider_not_normalized_usernames"
|
||||||
|
)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def users(self) -> list[dict[str, str]]:
|
||||||
|
"""Return users."""
|
||||||
|
assert self._data is not None
|
||||||
|
return self._data["users"]
|
||||||
|
|
||||||
|
def validate_login(self, username: str, password: str) -> None:
|
||||||
|
"""Validate a username and password.
|
||||||
|
|
||||||
|
Raises InvalidAuth if auth invalid.
|
||||||
|
"""
|
||||||
|
username = self.normalize_username(username)
|
||||||
|
dummy = b"$2b$12$CiuFGszHx9eNHxPuQcwBWez4CwDTOcLTX5CbOpV6gef2nYuXkY7BO"
|
||||||
|
found = None
|
||||||
|
|
||||||
|
# Compare all users to avoid timing attacks.
|
||||||
|
for user in self.users:
|
||||||
|
if self.normalize_username(user["username"]) == username:
|
||||||
|
found = user
|
||||||
|
|
||||||
|
if found is None:
|
||||||
|
# check a hash to make timing the same as if user was found
|
||||||
|
bcrypt.checkpw(b"foo", dummy)
|
||||||
|
raise InvalidAuth
|
||||||
|
|
||||||
|
user_hash = base64.b64decode(found["password"])
|
||||||
|
|
||||||
|
# bcrypt.checkpw is timing-safe
|
||||||
|
if not bcrypt.checkpw(password.encode(), user_hash):
|
||||||
|
raise InvalidAuth
|
||||||
|
|
||||||
|
def hash_password(self, password: str, for_storage: bool = False) -> bytes:
|
||||||
|
"""Encode a password."""
|
||||||
|
hashed: bytes = bcrypt.hashpw(password.encode(), bcrypt.gensalt(rounds=12))
|
||||||
|
|
||||||
|
if for_storage:
|
||||||
|
hashed = base64.b64encode(hashed)
|
||||||
|
return hashed
|
||||||
|
|
||||||
|
def add_auth(self, username: str, password: str) -> None:
|
||||||
|
"""Add a new authenticated user/pass.
|
||||||
|
|
||||||
|
Raises InvalidUsername if the new username is invalid.
|
||||||
|
"""
|
||||||
|
self._validate_new_username(username)
|
||||||
|
|
||||||
|
self.users.append(
|
||||||
|
{
|
||||||
|
"username": username,
|
||||||
|
"password": self.hash_password(password, True).decode(),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
@callback
|
||||||
|
def async_remove_auth(self, username: str) -> None:
|
||||||
|
"""Remove authentication."""
|
||||||
|
username = self.normalize_username(username)
|
||||||
|
|
||||||
|
index = None
|
||||||
|
for i, user in enumerate(self.users):
|
||||||
|
if self.normalize_username(user["username"]) == username:
|
||||||
|
index = i
|
||||||
|
break
|
||||||
|
|
||||||
|
if index is None:
|
||||||
|
raise InvalidUser(translation_key="user_not_found")
|
||||||
|
|
||||||
|
self.users.pop(index)
|
||||||
|
|
||||||
|
def change_password(self, username: str, new_password: str) -> None:
|
||||||
|
"""Update the password.
|
||||||
|
|
||||||
|
Raises InvalidUser if user cannot be found.
|
||||||
|
"""
|
||||||
|
username = self.normalize_username(username)
|
||||||
|
|
||||||
|
for user in self.users:
|
||||||
|
if self.normalize_username(user["username"]) == username:
|
||||||
|
user["password"] = self.hash_password(new_password, True).decode()
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
raise InvalidUser(translation_key="user_not_found")
|
||||||
|
|
||||||
|
@callback
|
||||||
|
def _validate_new_username(self, new_username: str) -> None:
|
||||||
|
"""Validate that username is normalized and unique.
|
||||||
|
|
||||||
|
Raises InvalidUsername if the new username is invalid.
|
||||||
|
"""
|
||||||
|
normalized_username = self.normalize_username(
|
||||||
|
new_username, force_normalize=True
|
||||||
|
)
|
||||||
|
if normalized_username != new_username:
|
||||||
|
raise InvalidUsername(
|
||||||
|
translation_key="username_not_normalized",
|
||||||
|
translation_placeholders={"new_username": new_username},
|
||||||
|
)
|
||||||
|
|
||||||
|
if any(
|
||||||
|
self.normalize_username(user["username"]) == normalized_username
|
||||||
|
for user in self.users
|
||||||
|
):
|
||||||
|
raise InvalidUsername(
|
||||||
|
translation_key="username_already_exists",
|
||||||
|
translation_placeholders={"username": new_username},
|
||||||
|
)
|
||||||
|
|
||||||
|
@callback
|
||||||
|
def change_username(self, username: str, new_username: str) -> None:
|
||||||
|
"""Update the username.
|
||||||
|
|
||||||
|
Raises InvalidUser if user cannot be found.
|
||||||
|
Raises InvalidUsername if the new username is invalid.
|
||||||
|
"""
|
||||||
|
username = self.normalize_username(username)
|
||||||
|
self._validate_new_username(new_username)
|
||||||
|
|
||||||
|
for user in self.users:
|
||||||
|
if self.normalize_username(user["username"]) == username:
|
||||||
|
user["username"] = new_username
|
||||||
|
assert self._data is not None
|
||||||
|
self._async_check_for_not_normalized_usernames(self._data)
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
raise InvalidUser(translation_key="user_not_found")
|
||||||
|
|
||||||
|
async def async_save(self) -> None:
|
||||||
|
"""Save data."""
|
||||||
|
if self._data is not None:
|
||||||
|
await self._store.async_save(self._data)
|
||||||
|
|
||||||
|
|
||||||
|
@AUTH_PROVIDERS.register("homeassistant")
|
||||||
|
class HassAuthProvider(AuthProvider):
|
||||||
|
"""Auth provider based on a local storage of users in Home Assistant config dir."""
|
||||||
|
|
||||||
|
DEFAULT_TITLE = "Home Assistant Local"
|
||||||
|
|
||||||
|
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
||||||
|
"""Initialize an Home Assistant auth provider."""
|
||||||
|
super().__init__(*args, **kwargs)
|
||||||
|
self.data: Data | None = None
|
||||||
|
self._init_lock = asyncio.Lock()
|
||||||
|
|
||||||
|
async def async_initialize(self) -> None:
|
||||||
|
"""Initialize the auth provider."""
|
||||||
|
async with self._init_lock:
|
||||||
|
if self.data is not None:
|
||||||
|
return
|
||||||
|
|
||||||
|
data = Data(self.hass)
|
||||||
|
await data.async_load()
|
||||||
|
self.data = data
|
||||||
|
|
||||||
|
async def async_login_flow(self, context: AuthFlowContext | None) -> HassLoginFlow:
|
||||||
|
"""Return a flow to login."""
|
||||||
|
return HassLoginFlow(self)
|
||||||
|
|
||||||
|
async def async_validate_login(self, username: str, password: str) -> None:
|
||||||
|
"""Validate a username and password."""
|
||||||
|
if self.data is None:
|
||||||
|
await self.async_initialize()
|
||||||
|
assert self.data is not None
|
||||||
|
|
||||||
|
await self.hass.async_add_executor_job(
|
||||||
|
self.data.validate_login, username, password
|
||||||
|
)
|
||||||
|
|
||||||
|
async def async_add_auth(self, username: str, password: str) -> None:
|
||||||
|
"""Call add_auth on data."""
|
||||||
|
if self.data is None:
|
||||||
|
await self.async_initialize()
|
||||||
|
assert self.data is not None
|
||||||
|
|
||||||
|
await self.hass.async_add_executor_job(self.data.add_auth, username, password)
|
||||||
|
await self.data.async_save()
|
||||||
|
|
||||||
|
async def async_remove_auth(self, username: str) -> None:
|
||||||
|
"""Call remove_auth on data."""
|
||||||
|
if self.data is None:
|
||||||
|
await self.async_initialize()
|
||||||
|
assert self.data is not None
|
||||||
|
|
||||||
|
self.data.async_remove_auth(username)
|
||||||
|
await self.data.async_save()
|
||||||
|
|
||||||
|
async def async_change_password(self, username: str, new_password: str) -> None:
|
||||||
|
"""Call change_password on data."""
|
||||||
|
if self.data is None:
|
||||||
|
await self.async_initialize()
|
||||||
|
assert self.data is not None
|
||||||
|
|
||||||
|
await self.hass.async_add_executor_job(
|
||||||
|
self.data.change_password, username, new_password
|
||||||
|
)
|
||||||
|
await self.data.async_save()
|
||||||
|
|
||||||
|
async def async_change_username(
|
||||||
|
self, credential: Credentials, new_username: str
|
||||||
|
) -> None:
|
||||||
|
"""Validate new username and change it including updating credentials object."""
|
||||||
|
if self.data is None:
|
||||||
|
await self.async_initialize()
|
||||||
|
assert self.data is not None
|
||||||
|
|
||||||
|
self.data.change_username(credential.data["username"], new_username)
|
||||||
|
self.hass.auth.async_update_user_credentials_data(
|
||||||
|
credential, {**credential.data, "username": new_username}
|
||||||
|
)
|
||||||
|
await self.data.async_save()
|
||||||
|
|
||||||
|
async def async_get_or_create_credentials(
|
||||||
|
self, flow_result: Mapping[str, str]
|
||||||
|
) -> Credentials:
|
||||||
|
"""Get credentials based on the flow result."""
|
||||||
|
if self.data is None:
|
||||||
|
await self.async_initialize()
|
||||||
|
assert self.data is not None
|
||||||
|
|
||||||
|
norm_username = self.data.normalize_username
|
||||||
|
username = norm_username(flow_result["username"])
|
||||||
|
|
||||||
|
for credential in await self.async_credentials():
|
||||||
|
if norm_username(credential.data["username"]) == username:
|
||||||
|
return credential
|
||||||
|
|
||||||
|
# Create new credentials.
|
||||||
|
return self.async_create_credentials({"username": username})
|
||||||
|
|
||||||
|
async def async_user_meta_for_credentials(
|
||||||
|
self, credentials: Credentials
|
||||||
|
) -> UserMeta:
|
||||||
|
"""Get extra info for this credential."""
|
||||||
|
return UserMeta(name=credentials.data["username"], is_active=True)
|
||||||
|
|
||||||
|
async def async_will_remove_credentials(self, credentials: Credentials) -> None:
|
||||||
|
"""When credentials get removed, also remove the auth."""
|
||||||
|
if self.data is None:
|
||||||
|
await self.async_initialize()
|
||||||
|
assert self.data is not None
|
||||||
|
|
||||||
|
try:
|
||||||
|
self.data.async_remove_auth(credentials.data["username"])
|
||||||
|
await self.data.async_save()
|
||||||
|
except InvalidUser:
|
||||||
|
# Can happen if somehow we didn't clean up a credential
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class HassLoginFlow(LoginFlow[HassAuthProvider]):
|
||||||
|
"""Handler for the login flow."""
|
||||||
|
|
||||||
|
async def async_step_init(
|
||||||
|
self, user_input: dict[str, str] | None = None
|
||||||
|
) -> AuthFlowResult:
|
||||||
|
"""Handle the step of the form."""
|
||||||
|
errors = {}
|
||||||
|
|
||||||
|
if user_input is not None:
|
||||||
|
try:
|
||||||
|
await self._auth_provider.async_validate_login(
|
||||||
|
user_input["username"], user_input["password"]
|
||||||
|
)
|
||||||
|
except InvalidAuth:
|
||||||
|
errors["base"] = "invalid_auth"
|
||||||
|
|
||||||
|
if not errors:
|
||||||
|
user_input.pop("password")
|
||||||
|
return await self.async_finish(user_input)
|
||||||
|
|
||||||
|
return self.async_show_form(
|
||||||
|
step_id="init",
|
||||||
|
data_schema=vol.Schema(
|
||||||
|
{
|
||||||
|
vol.Required("username"): str,
|
||||||
|
vol.Required("password"): str,
|
||||||
|
}
|
||||||
|
),
|
||||||
|
errors=errors,
|
||||||
|
)
|
||||||
127
home-assistant/homeassistant/auth/providers/insecure_example.py
Normal file
127
home-assistant/homeassistant/auth/providers/insecure_example.py
Normal file
@@ -0,0 +1,127 @@
|
|||||||
|
"""Example auth provider."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections.abc import Mapping
|
||||||
|
import hmac
|
||||||
|
|
||||||
|
import voluptuous as vol
|
||||||
|
|
||||||
|
from homeassistant.core import callback
|
||||||
|
from homeassistant.exceptions import HomeAssistantError
|
||||||
|
|
||||||
|
from ..models import AuthFlowContext, AuthFlowResult, Credentials, UserMeta
|
||||||
|
from . import AUTH_PROVIDER_SCHEMA, AUTH_PROVIDERS, AuthProvider, LoginFlow
|
||||||
|
|
||||||
|
USER_SCHEMA = vol.Schema(
|
||||||
|
{
|
||||||
|
vol.Required("username"): str,
|
||||||
|
vol.Required("password"): str,
|
||||||
|
vol.Optional("name"): str,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
CONFIG_SCHEMA = AUTH_PROVIDER_SCHEMA.extend(
|
||||||
|
{vol.Required("users"): [USER_SCHEMA]}, extra=vol.PREVENT_EXTRA
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class InvalidAuthError(HomeAssistantError):
|
||||||
|
"""Raised when submitting invalid authentication."""
|
||||||
|
|
||||||
|
|
||||||
|
@AUTH_PROVIDERS.register("insecure_example")
|
||||||
|
class ExampleAuthProvider(AuthProvider):
|
||||||
|
"""Example auth provider based on hardcoded usernames and passwords."""
|
||||||
|
|
||||||
|
async def async_login_flow(
|
||||||
|
self, context: AuthFlowContext | None
|
||||||
|
) -> ExampleLoginFlow:
|
||||||
|
"""Return a flow to login."""
|
||||||
|
return ExampleLoginFlow(self)
|
||||||
|
|
||||||
|
@callback
|
||||||
|
def async_validate_login(self, username: str, password: str) -> None:
|
||||||
|
"""Validate a username and password."""
|
||||||
|
user = None
|
||||||
|
|
||||||
|
# Compare all users to avoid timing attacks.
|
||||||
|
for usr in self.config["users"]:
|
||||||
|
if hmac.compare_digest(
|
||||||
|
username.encode("utf-8"), usr["username"].encode("utf-8")
|
||||||
|
):
|
||||||
|
user = usr
|
||||||
|
|
||||||
|
if user is None:
|
||||||
|
# Do one more compare to make timing the same as if user was found.
|
||||||
|
hmac.compare_digest(password.encode("utf-8"), password.encode("utf-8"))
|
||||||
|
raise InvalidAuthError
|
||||||
|
|
||||||
|
if not hmac.compare_digest(
|
||||||
|
user["password"].encode("utf-8"), password.encode("utf-8")
|
||||||
|
):
|
||||||
|
raise InvalidAuthError
|
||||||
|
|
||||||
|
async def async_get_or_create_credentials(
|
||||||
|
self, flow_result: Mapping[str, str]
|
||||||
|
) -> Credentials:
|
||||||
|
"""Get credentials based on the flow result."""
|
||||||
|
username = flow_result["username"]
|
||||||
|
|
||||||
|
for credential in await self.async_credentials():
|
||||||
|
if credential.data["username"] == username:
|
||||||
|
return credential
|
||||||
|
|
||||||
|
# Create new credentials.
|
||||||
|
return self.async_create_credentials({"username": username})
|
||||||
|
|
||||||
|
async def async_user_meta_for_credentials(
|
||||||
|
self, credentials: Credentials
|
||||||
|
) -> UserMeta:
|
||||||
|
"""Return extra user metadata for credentials.
|
||||||
|
|
||||||
|
Will be used to populate info when creating a new user.
|
||||||
|
"""
|
||||||
|
username = credentials.data["username"]
|
||||||
|
name = None
|
||||||
|
|
||||||
|
for user in self.config["users"]:
|
||||||
|
if user["username"] == username:
|
||||||
|
name = user.get("name")
|
||||||
|
break
|
||||||
|
|
||||||
|
return UserMeta(name=name, is_active=True)
|
||||||
|
|
||||||
|
|
||||||
|
class ExampleLoginFlow(LoginFlow[ExampleAuthProvider]):
|
||||||
|
"""Handler for the login flow."""
|
||||||
|
|
||||||
|
async def async_step_init(
|
||||||
|
self, user_input: dict[str, str] | None = None
|
||||||
|
) -> AuthFlowResult:
|
||||||
|
"""Handle the step of the form."""
|
||||||
|
errors = None
|
||||||
|
|
||||||
|
if user_input is not None:
|
||||||
|
try:
|
||||||
|
self._auth_provider.async_validate_login(
|
||||||
|
user_input["username"], user_input["password"]
|
||||||
|
)
|
||||||
|
except InvalidAuthError:
|
||||||
|
errors = {"base": "invalid_auth"}
|
||||||
|
|
||||||
|
if not errors:
|
||||||
|
user_input.pop("password")
|
||||||
|
return await self.async_finish(user_input)
|
||||||
|
|
||||||
|
return self.async_show_form(
|
||||||
|
step_id="init",
|
||||||
|
data_schema=vol.Schema(
|
||||||
|
{
|
||||||
|
vol.Required("username"): str,
|
||||||
|
vol.Required("password"): str,
|
||||||
|
}
|
||||||
|
),
|
||||||
|
errors=errors,
|
||||||
|
)
|
||||||
258
home-assistant/homeassistant/auth/providers/trusted_networks.py
Normal file
258
home-assistant/homeassistant/auth/providers/trusted_networks.py
Normal file
@@ -0,0 +1,258 @@
|
|||||||
|
"""Trusted Networks auth provider.
|
||||||
|
|
||||||
|
It shows list of users if access from trusted network.
|
||||||
|
Abort login flow if not access from trusted network.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections.abc import Mapping
|
||||||
|
from ipaddress import (
|
||||||
|
IPv4Address,
|
||||||
|
IPv4Network,
|
||||||
|
IPv6Address,
|
||||||
|
IPv6Network,
|
||||||
|
ip_address,
|
||||||
|
ip_network,
|
||||||
|
)
|
||||||
|
from typing import Any, cast
|
||||||
|
|
||||||
|
import voluptuous as vol
|
||||||
|
|
||||||
|
from homeassistant.core import callback
|
||||||
|
from homeassistant.exceptions import HomeAssistantError
|
||||||
|
import homeassistant.helpers.config_validation as cv
|
||||||
|
from homeassistant.helpers.network import is_cloud_connection
|
||||||
|
|
||||||
|
from .. import InvalidAuthError
|
||||||
|
from ..models import (
|
||||||
|
AuthFlowContext,
|
||||||
|
AuthFlowResult,
|
||||||
|
Credentials,
|
||||||
|
RefreshToken,
|
||||||
|
UserMeta,
|
||||||
|
)
|
||||||
|
from . import AUTH_PROVIDER_SCHEMA, AUTH_PROVIDERS, AuthProvider, LoginFlow
|
||||||
|
|
||||||
|
type IPAddress = IPv4Address | IPv6Address
|
||||||
|
type IPNetwork = IPv4Network | IPv6Network
|
||||||
|
|
||||||
|
CONF_TRUSTED_NETWORKS = "trusted_networks"
|
||||||
|
CONF_TRUSTED_USERS = "trusted_users"
|
||||||
|
CONF_GROUP = "group"
|
||||||
|
CONF_ALLOW_BYPASS_LOGIN = "allow_bypass_login"
|
||||||
|
|
||||||
|
CONFIG_SCHEMA = AUTH_PROVIDER_SCHEMA.extend(
|
||||||
|
{
|
||||||
|
vol.Required(CONF_TRUSTED_NETWORKS): vol.All(cv.ensure_list, [ip_network]),
|
||||||
|
vol.Optional(CONF_TRUSTED_USERS, default={}): vol.Schema(
|
||||||
|
# we only validate the format of user_id or group_id
|
||||||
|
{
|
||||||
|
ip_network: vol.All(
|
||||||
|
cv.ensure_list,
|
||||||
|
[
|
||||||
|
vol.Or(
|
||||||
|
cv.uuid4_hex,
|
||||||
|
vol.Schema({vol.Required(CONF_GROUP): str}),
|
||||||
|
)
|
||||||
|
],
|
||||||
|
)
|
||||||
|
}
|
||||||
|
),
|
||||||
|
vol.Optional(CONF_ALLOW_BYPASS_LOGIN, default=False): cv.boolean,
|
||||||
|
},
|
||||||
|
extra=vol.PREVENT_EXTRA,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class InvalidUserError(HomeAssistantError):
|
||||||
|
"""Raised when try to login as invalid user."""
|
||||||
|
|
||||||
|
|
||||||
|
@AUTH_PROVIDERS.register("trusted_networks")
|
||||||
|
class TrustedNetworksAuthProvider(AuthProvider):
|
||||||
|
"""Trusted Networks auth provider.
|
||||||
|
|
||||||
|
Allow passwordless access from trusted network.
|
||||||
|
"""
|
||||||
|
|
||||||
|
DEFAULT_TITLE = "Trusted Networks"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def trusted_networks(self) -> list[IPNetwork]:
|
||||||
|
"""Return trusted networks."""
|
||||||
|
return cast(list[IPNetwork], self.config[CONF_TRUSTED_NETWORKS])
|
||||||
|
|
||||||
|
@property
|
||||||
|
def trusted_users(self) -> dict[IPNetwork, Any]:
|
||||||
|
"""Return trusted users per network."""
|
||||||
|
return cast(dict[IPNetwork, Any], self.config[CONF_TRUSTED_USERS])
|
||||||
|
|
||||||
|
@property
|
||||||
|
def trusted_proxies(self) -> list[IPNetwork]:
|
||||||
|
"""Return trusted proxies in the system."""
|
||||||
|
if not self.hass.http:
|
||||||
|
return []
|
||||||
|
|
||||||
|
return [
|
||||||
|
ip_network(trusted_proxy)
|
||||||
|
for trusted_proxy in self.hass.http.trusted_proxies
|
||||||
|
]
|
||||||
|
|
||||||
|
@property
|
||||||
|
def support_mfa(self) -> bool:
|
||||||
|
"""Trusted Networks auth provider does not support MFA."""
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def async_login_flow(
|
||||||
|
self, context: AuthFlowContext | None
|
||||||
|
) -> TrustedNetworksLoginFlow:
|
||||||
|
"""Return a flow to login."""
|
||||||
|
assert context is not None
|
||||||
|
ip_addr = cast(IPAddress, context.get("ip_address"))
|
||||||
|
users = await self.store.async_get_users()
|
||||||
|
available_users = [
|
||||||
|
user for user in users if not user.system_generated and user.is_active
|
||||||
|
]
|
||||||
|
for ip_net, user_or_group_list in self.trusted_users.items():
|
||||||
|
if ip_addr not in ip_net:
|
||||||
|
continue
|
||||||
|
|
||||||
|
user_list = [
|
||||||
|
user_id for user_id in user_or_group_list if isinstance(user_id, str)
|
||||||
|
]
|
||||||
|
group_list = [
|
||||||
|
group[CONF_GROUP]
|
||||||
|
for group in user_or_group_list
|
||||||
|
if isinstance(group, dict)
|
||||||
|
]
|
||||||
|
flattened_group_list = [
|
||||||
|
group for sublist in group_list for group in sublist
|
||||||
|
]
|
||||||
|
available_users = [
|
||||||
|
user
|
||||||
|
for user in available_users
|
||||||
|
if (
|
||||||
|
user.id in user_list
|
||||||
|
or any(group.id in flattened_group_list for group in user.groups)
|
||||||
|
)
|
||||||
|
]
|
||||||
|
break
|
||||||
|
|
||||||
|
return TrustedNetworksLoginFlow(
|
||||||
|
self,
|
||||||
|
ip_addr,
|
||||||
|
{user.id: user.name for user in available_users},
|
||||||
|
self.config[CONF_ALLOW_BYPASS_LOGIN],
|
||||||
|
)
|
||||||
|
|
||||||
|
async def async_get_or_create_credentials(
|
||||||
|
self, flow_result: Mapping[str, str]
|
||||||
|
) -> Credentials:
|
||||||
|
"""Get credentials based on the flow result."""
|
||||||
|
user_id = flow_result["user"]
|
||||||
|
|
||||||
|
users = await self.store.async_get_users()
|
||||||
|
for user in users:
|
||||||
|
if user.id != user_id:
|
||||||
|
continue
|
||||||
|
|
||||||
|
if user.system_generated:
|
||||||
|
continue
|
||||||
|
|
||||||
|
if not user.is_active:
|
||||||
|
continue
|
||||||
|
|
||||||
|
for credential in await self.async_credentials():
|
||||||
|
if credential.data["user_id"] == user_id:
|
||||||
|
return credential
|
||||||
|
|
||||||
|
cred = self.async_create_credentials({"user_id": user_id})
|
||||||
|
await self.store.async_link_user(user, cred)
|
||||||
|
return cred
|
||||||
|
|
||||||
|
# We only allow login as exist user
|
||||||
|
raise InvalidUserError
|
||||||
|
|
||||||
|
async def async_user_meta_for_credentials(
|
||||||
|
self, credentials: Credentials
|
||||||
|
) -> UserMeta:
|
||||||
|
"""Return extra user metadata for credentials.
|
||||||
|
|
||||||
|
Trusted network auth provider should never create new user.
|
||||||
|
"""
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
@callback
|
||||||
|
def async_validate_access(self, ip_addr: IPAddress) -> None:
|
||||||
|
"""Make sure the access from trusted networks.
|
||||||
|
|
||||||
|
Raise InvalidAuthError if not.
|
||||||
|
Raise InvalidAuthError if trusted_networks is not configured.
|
||||||
|
"""
|
||||||
|
if not self.trusted_networks:
|
||||||
|
raise InvalidAuthError("trusted_networks is not configured")
|
||||||
|
|
||||||
|
if not any(
|
||||||
|
ip_addr in trusted_network for trusted_network in self.trusted_networks
|
||||||
|
):
|
||||||
|
raise InvalidAuthError("Not in trusted_networks")
|
||||||
|
|
||||||
|
if any(ip_addr in trusted_proxy for trusted_proxy in self.trusted_proxies):
|
||||||
|
raise InvalidAuthError("Can't allow access from a proxy server")
|
||||||
|
|
||||||
|
if is_cloud_connection(self.hass):
|
||||||
|
raise InvalidAuthError("Can't allow access from Home Assistant Cloud")
|
||||||
|
|
||||||
|
@callback
|
||||||
|
def async_validate_refresh_token(
|
||||||
|
self, refresh_token: RefreshToken, remote_ip: str | None = None
|
||||||
|
) -> None:
|
||||||
|
"""Verify a refresh token is still valid."""
|
||||||
|
if remote_ip is None:
|
||||||
|
raise InvalidAuthError(
|
||||||
|
"Unknown remote ip can't be used for trusted network provider."
|
||||||
|
)
|
||||||
|
self.async_validate_access(ip_address(remote_ip))
|
||||||
|
|
||||||
|
|
||||||
|
class TrustedNetworksLoginFlow(LoginFlow[TrustedNetworksAuthProvider]):
|
||||||
|
"""Handler for the login flow."""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
auth_provider: TrustedNetworksAuthProvider,
|
||||||
|
ip_addr: IPAddress,
|
||||||
|
available_users: dict[str, str | None],
|
||||||
|
allow_bypass_login: bool,
|
||||||
|
) -> None:
|
||||||
|
"""Initialize the login flow."""
|
||||||
|
super().__init__(auth_provider)
|
||||||
|
self._available_users = available_users
|
||||||
|
self._ip_address = ip_addr
|
||||||
|
self._allow_bypass_login = allow_bypass_login
|
||||||
|
|
||||||
|
async def async_step_init(
|
||||||
|
self, user_input: dict[str, str] | None = None
|
||||||
|
) -> AuthFlowResult:
|
||||||
|
"""Handle the step of the form."""
|
||||||
|
try:
|
||||||
|
self._auth_provider.async_validate_access(self._ip_address)
|
||||||
|
|
||||||
|
except InvalidAuthError:
|
||||||
|
return self.async_abort(reason="not_allowed")
|
||||||
|
|
||||||
|
if user_input is not None:
|
||||||
|
return await self.async_finish(user_input)
|
||||||
|
|
||||||
|
if self._allow_bypass_login and len(self._available_users) == 1:
|
||||||
|
return await self.async_finish(
|
||||||
|
{"user": next(iter(self._available_users.keys()))}
|
||||||
|
)
|
||||||
|
|
||||||
|
return self.async_show_form(
|
||||||
|
step_id="init",
|
||||||
|
data_schema=vol.Schema(
|
||||||
|
{vol.Required("user"): vol.In(self._available_users)}
|
||||||
|
),
|
||||||
|
)
|
||||||
279
home-assistant/homeassistant/backports/LICENSE.Python
Normal file
279
home-assistant/homeassistant/backports/LICENSE.Python
Normal file
@@ -0,0 +1,279 @@
|
|||||||
|
A. HISTORY OF THE SOFTWARE
|
||||||
|
==========================
|
||||||
|
|
||||||
|
Python was created in the early 1990s by Guido van Rossum at Stichting
|
||||||
|
Mathematisch Centrum (CWI, see https://www.cwi.nl) in the Netherlands
|
||||||
|
as a successor of a language called ABC. Guido remains Python's
|
||||||
|
principal author, although it includes many contributions from others.
|
||||||
|
|
||||||
|
In 1995, Guido continued his work on Python at the Corporation for
|
||||||
|
National Research Initiatives (CNRI, see https://www.cnri.reston.va.us)
|
||||||
|
in Reston, Virginia where he released several versions of the
|
||||||
|
software.
|
||||||
|
|
||||||
|
In May 2000, Guido and the Python core development team moved to
|
||||||
|
BeOpen.com to form the BeOpen PythonLabs team. In October of the same
|
||||||
|
year, the PythonLabs team moved to Digital Creations, which became
|
||||||
|
Zope Corporation. In 2001, the Python Software Foundation (PSF, see
|
||||||
|
https://www.python.org/psf/) was formed, a non-profit organization
|
||||||
|
created specifically to own Python-related Intellectual Property.
|
||||||
|
Zope Corporation was a sponsoring member of the PSF.
|
||||||
|
|
||||||
|
All Python releases are Open Source (see https://opensource.org for
|
||||||
|
the Open Source Definition). Historically, most, but not all, Python
|
||||||
|
releases have also been GPL-compatible; the table below summarizes
|
||||||
|
the various releases.
|
||||||
|
|
||||||
|
Release Derived Year Owner GPL-
|
||||||
|
from compatible? (1)
|
||||||
|
|
||||||
|
0.9.0 thru 1.2 1991-1995 CWI yes
|
||||||
|
1.3 thru 1.5.2 1.2 1995-1999 CNRI yes
|
||||||
|
1.6 1.5.2 2000 CNRI no
|
||||||
|
2.0 1.6 2000 BeOpen.com no
|
||||||
|
1.6.1 1.6 2001 CNRI yes (2)
|
||||||
|
2.1 2.0+1.6.1 2001 PSF no
|
||||||
|
2.0.1 2.0+1.6.1 2001 PSF yes
|
||||||
|
2.1.1 2.1+2.0.1 2001 PSF yes
|
||||||
|
2.1.2 2.1.1 2002 PSF yes
|
||||||
|
2.1.3 2.1.2 2002 PSF yes
|
||||||
|
2.2 and above 2.1.1 2001-now PSF yes
|
||||||
|
|
||||||
|
Footnotes:
|
||||||
|
|
||||||
|
(1) GPL-compatible doesn't mean that we're distributing Python under
|
||||||
|
the GPL. All Python licenses, unlike the GPL, let you distribute
|
||||||
|
a modified version without making your changes open source. The
|
||||||
|
GPL-compatible licenses make it possible to combine Python with
|
||||||
|
other software that is released under the GPL; the others don't.
|
||||||
|
|
||||||
|
(2) According to Richard Stallman, 1.6.1 is not GPL-compatible,
|
||||||
|
because its license has a choice of law clause. According to
|
||||||
|
CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1
|
||||||
|
is "not incompatible" with the GPL.
|
||||||
|
|
||||||
|
Thanks to the many outside volunteers who have worked under Guido's
|
||||||
|
direction to make these releases possible.
|
||||||
|
|
||||||
|
|
||||||
|
B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON
|
||||||
|
===============================================================
|
||||||
|
|
||||||
|
Python software and documentation are licensed under the
|
||||||
|
Python Software Foundation License Version 2.
|
||||||
|
|
||||||
|
Starting with Python 3.8.6, examples, recipes, and other code in
|
||||||
|
the documentation are dual licensed under the PSF License Version 2
|
||||||
|
and the Zero-Clause BSD license.
|
||||||
|
|
||||||
|
Some software incorporated into Python is under different licenses.
|
||||||
|
The licenses are listed with code falling under that license.
|
||||||
|
|
||||||
|
|
||||||
|
PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
|
||||||
|
--------------------------------------------
|
||||||
|
|
||||||
|
1. This LICENSE AGREEMENT is between the Python Software Foundation
|
||||||
|
("PSF"), and the Individual or Organization ("Licensee") accessing and
|
||||||
|
otherwise using this software ("Python") in source or binary form and
|
||||||
|
its associated documentation.
|
||||||
|
|
||||||
|
2. Subject to the terms and conditions of this License Agreement, PSF hereby
|
||||||
|
grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
|
||||||
|
analyze, test, perform and/or display publicly, prepare derivative works,
|
||||||
|
distribute, and otherwise use Python alone or in any derivative version,
|
||||||
|
provided, however, that PSF's License Agreement and PSF's notice of copyright,
|
||||||
|
i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
|
||||||
|
2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023 Python Software Foundation;
|
||||||
|
All Rights Reserved" are retained in Python alone or in any derivative version
|
||||||
|
prepared by Licensee.
|
||||||
|
|
||||||
|
3. In the event Licensee prepares a derivative work that is based on
|
||||||
|
or incorporates Python or any part thereof, and wants to make
|
||||||
|
the derivative work available to others as provided herein, then
|
||||||
|
Licensee hereby agrees to include in any such work a brief summary of
|
||||||
|
the changes made to Python.
|
||||||
|
|
||||||
|
4. PSF is making Python available to Licensee on an "AS IS"
|
||||||
|
basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
|
||||||
|
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
|
||||||
|
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
|
||||||
|
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT
|
||||||
|
INFRINGE ANY THIRD PARTY RIGHTS.
|
||||||
|
|
||||||
|
5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
|
||||||
|
FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
|
||||||
|
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,
|
||||||
|
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
|
||||||
|
|
||||||
|
6. This License Agreement will automatically terminate upon a material
|
||||||
|
breach of its terms and conditions.
|
||||||
|
|
||||||
|
7. Nothing in this License Agreement shall be deemed to create any
|
||||||
|
relationship of agency, partnership, or joint venture between PSF and
|
||||||
|
Licensee. This License Agreement does not grant permission to use PSF
|
||||||
|
trademarks or trade name in a trademark sense to endorse or promote
|
||||||
|
products or services of Licensee, or any third party.
|
||||||
|
|
||||||
|
8. By copying, installing or otherwise using Python, Licensee
|
||||||
|
agrees to be bound by the terms and conditions of this License
|
||||||
|
Agreement.
|
||||||
|
|
||||||
|
|
||||||
|
BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0
|
||||||
|
-------------------------------------------
|
||||||
|
|
||||||
|
BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1
|
||||||
|
|
||||||
|
1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an
|
||||||
|
office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the
|
||||||
|
Individual or Organization ("Licensee") accessing and otherwise using
|
||||||
|
this software in source or binary form and its associated
|
||||||
|
documentation ("the Software").
|
||||||
|
|
||||||
|
2. Subject to the terms and conditions of this BeOpen Python License
|
||||||
|
Agreement, BeOpen hereby grants Licensee a non-exclusive,
|
||||||
|
royalty-free, world-wide license to reproduce, analyze, test, perform
|
||||||
|
and/or display publicly, prepare derivative works, distribute, and
|
||||||
|
otherwise use the Software alone or in any derivative version,
|
||||||
|
provided, however, that the BeOpen Python License is retained in the
|
||||||
|
Software, alone or in any derivative version prepared by Licensee.
|
||||||
|
|
||||||
|
3. BeOpen is making the Software available to Licensee on an "AS IS"
|
||||||
|
basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
|
||||||
|
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND
|
||||||
|
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
|
||||||
|
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT
|
||||||
|
INFRINGE ANY THIRD PARTY RIGHTS.
|
||||||
|
|
||||||
|
4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE
|
||||||
|
SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS
|
||||||
|
AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY
|
||||||
|
DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
|
||||||
|
|
||||||
|
5. This License Agreement will automatically terminate upon a material
|
||||||
|
breach of its terms and conditions.
|
||||||
|
|
||||||
|
6. This License Agreement shall be governed by and interpreted in all
|
||||||
|
respects by the law of the State of California, excluding conflict of
|
||||||
|
law provisions. Nothing in this License Agreement shall be deemed to
|
||||||
|
create any relationship of agency, partnership, or joint venture
|
||||||
|
between BeOpen and Licensee. This License Agreement does not grant
|
||||||
|
permission to use BeOpen trademarks or trade names in a trademark
|
||||||
|
sense to endorse or promote products or services of Licensee, or any
|
||||||
|
third party. As an exception, the "BeOpen Python" logos available at
|
||||||
|
http://www.pythonlabs.com/logos.html may be used according to the
|
||||||
|
permissions granted on that web page.
|
||||||
|
|
||||||
|
7. By copying, installing or otherwise using the software, Licensee
|
||||||
|
agrees to be bound by the terms and conditions of this License
|
||||||
|
Agreement.
|
||||||
|
|
||||||
|
|
||||||
|
CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1
|
||||||
|
---------------------------------------
|
||||||
|
|
||||||
|
1. This LICENSE AGREEMENT is between the Corporation for National
|
||||||
|
Research Initiatives, having an office at 1895 Preston White Drive,
|
||||||
|
Reston, VA 20191 ("CNRI"), and the Individual or Organization
|
||||||
|
("Licensee") accessing and otherwise using Python 1.6.1 software in
|
||||||
|
source or binary form and its associated documentation.
|
||||||
|
|
||||||
|
2. Subject to the terms and conditions of this License Agreement, CNRI
|
||||||
|
hereby grants Licensee a nonexclusive, royalty-free, world-wide
|
||||||
|
license to reproduce, analyze, test, perform and/or display publicly,
|
||||||
|
prepare derivative works, distribute, and otherwise use Python 1.6.1
|
||||||
|
alone or in any derivative version, provided, however, that CNRI's
|
||||||
|
License Agreement and CNRI's notice of copyright, i.e., "Copyright (c)
|
||||||
|
1995-2001 Corporation for National Research Initiatives; All Rights
|
||||||
|
Reserved" are retained in Python 1.6.1 alone or in any derivative
|
||||||
|
version prepared by Licensee. Alternately, in lieu of CNRI's License
|
||||||
|
Agreement, Licensee may substitute the following text (omitting the
|
||||||
|
quotes): "Python 1.6.1 is made available subject to the terms and
|
||||||
|
conditions in CNRI's License Agreement. This Agreement together with
|
||||||
|
Python 1.6.1 may be located on the internet using the following
|
||||||
|
unique, persistent identifier (known as a handle): 1895.22/1013. This
|
||||||
|
Agreement may also be obtained from a proxy server on the internet
|
||||||
|
using the following URL: http://hdl.handle.net/1895.22/1013".
|
||||||
|
|
||||||
|
3. In the event Licensee prepares a derivative work that is based on
|
||||||
|
or incorporates Python 1.6.1 or any part thereof, and wants to make
|
||||||
|
the derivative work available to others as provided herein, then
|
||||||
|
Licensee hereby agrees to include in any such work a brief summary of
|
||||||
|
the changes made to Python 1.6.1.
|
||||||
|
|
||||||
|
4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS"
|
||||||
|
basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
|
||||||
|
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND
|
||||||
|
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
|
||||||
|
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT
|
||||||
|
INFRINGE ANY THIRD PARTY RIGHTS.
|
||||||
|
|
||||||
|
5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
|
||||||
|
1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
|
||||||
|
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1,
|
||||||
|
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
|
||||||
|
|
||||||
|
6. This License Agreement will automatically terminate upon a material
|
||||||
|
breach of its terms and conditions.
|
||||||
|
|
||||||
|
7. This License Agreement shall be governed by the federal
|
||||||
|
intellectual property law of the United States, including without
|
||||||
|
limitation the federal copyright law, and, to the extent such
|
||||||
|
U.S. federal law does not apply, by the law of the Commonwealth of
|
||||||
|
Virginia, excluding Virginia's conflict of law provisions.
|
||||||
|
Notwithstanding the foregoing, with regard to derivative works based
|
||||||
|
on Python 1.6.1 that incorporate non-separable material that was
|
||||||
|
previously distributed under the GNU General Public License (GPL), the
|
||||||
|
law of the Commonwealth of Virginia shall govern this License
|
||||||
|
Agreement only as to issues arising under or with respect to
|
||||||
|
Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this
|
||||||
|
License Agreement shall be deemed to create any relationship of
|
||||||
|
agency, partnership, or joint venture between CNRI and Licensee. This
|
||||||
|
License Agreement does not grant permission to use CNRI trademarks or
|
||||||
|
trade name in a trademark sense to endorse or promote products or
|
||||||
|
services of Licensee, or any third party.
|
||||||
|
|
||||||
|
8. By clicking on the "ACCEPT" button where indicated, or by copying,
|
||||||
|
installing or otherwise using Python 1.6.1, Licensee agrees to be
|
||||||
|
bound by the terms and conditions of this License Agreement.
|
||||||
|
|
||||||
|
ACCEPT
|
||||||
|
|
||||||
|
|
||||||
|
CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2
|
||||||
|
--------------------------------------------------
|
||||||
|
|
||||||
|
Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam,
|
||||||
|
The Netherlands. All rights reserved.
|
||||||
|
|
||||||
|
Permission to use, copy, modify, and distribute this software and its
|
||||||
|
documentation for any purpose and without fee is hereby granted,
|
||||||
|
provided that the above copyright notice appear in all copies and that
|
||||||
|
both that copyright notice and this permission notice appear in
|
||||||
|
supporting documentation, and that the name of Stichting Mathematisch
|
||||||
|
Centrum or CWI not be used in advertising or publicity pertaining to
|
||||||
|
distribution of the software without specific, written prior
|
||||||
|
permission.
|
||||||
|
|
||||||
|
STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
|
||||||
|
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
|
||||||
|
FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
|
||||||
|
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||||
|
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||||
|
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
|
||||||
|
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||||
|
|
||||||
|
ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON DOCUMENTATION
|
||||||
|
----------------------------------------------------------------------
|
||||||
|
|
||||||
|
Permission to use, copy, modify, and/or distribute this software for any
|
||||||
|
purpose with or without fee is hereby granted.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||||
|
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
||||||
|
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||||
|
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
||||||
|
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
||||||
|
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
||||||
|
PERFORMANCE OF THIS SOFTWARE.
|
||||||
5
home-assistant/homeassistant/backports/README
Normal file
5
home-assistant/homeassistant/backports/README
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
This package contains backports of Python functionality from future Python
|
||||||
|
versions.
|
||||||
|
|
||||||
|
Some of the backports have been copied directly from the CPython project,
|
||||||
|
and are subject to license agreement as detailed in LICENSE.Python.
|
||||||
1
home-assistant/homeassistant/backports/__init__.py
Normal file
1
home-assistant/homeassistant/backports/__init__.py
Normal file
@@ -0,0 +1 @@
|
|||||||
|
"""Backports from newer Python versions."""
|
||||||
29
home-assistant/homeassistant/backports/enum.py
Normal file
29
home-assistant/homeassistant/backports/enum.py
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
"""Enum backports from standard lib.
|
||||||
|
|
||||||
|
This file contained the backport of the StrEnum of Python 3.11.
|
||||||
|
|
||||||
|
Since we have dropped support for Python 3.10, we can remove this backport.
|
||||||
|
This file is kept for now to avoid breaking custom components that might
|
||||||
|
import it.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from enum import StrEnum as _StrEnum
|
||||||
|
from functools import partial
|
||||||
|
|
||||||
|
from homeassistant.helpers.deprecation import (
|
||||||
|
DeprecatedAlias,
|
||||||
|
all_with_deprecated_constants,
|
||||||
|
check_if_deprecated_constant,
|
||||||
|
dir_with_deprecated_constants,
|
||||||
|
)
|
||||||
|
|
||||||
|
# StrEnum deprecated as of 2024.5 use enum.StrEnum instead.
|
||||||
|
_DEPRECATED_StrEnum = DeprecatedAlias(_StrEnum, "enum.StrEnum", "2025.5")
|
||||||
|
|
||||||
|
__getattr__ = partial(check_if_deprecated_constant, module_globals=globals())
|
||||||
|
__dir__ = partial(
|
||||||
|
dir_with_deprecated_constants, module_globals_keys=[*globals().keys()]
|
||||||
|
)
|
||||||
|
__all__ = all_with_deprecated_constants(globals())
|
||||||
31
home-assistant/homeassistant/backports/functools.py
Normal file
31
home-assistant/homeassistant/backports/functools.py
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
"""Functools backports from standard lib.
|
||||||
|
|
||||||
|
This file contained the backport of the cached_property implementation of Python 3.12.
|
||||||
|
|
||||||
|
Since we have dropped support for Python 3.11, we can remove this backport.
|
||||||
|
This file is kept for now to avoid breaking custom components that might
|
||||||
|
import it.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
# pylint: disable-next=hass-deprecated-import
|
||||||
|
from functools import cached_property as _cached_property, partial
|
||||||
|
|
||||||
|
from homeassistant.helpers.deprecation import (
|
||||||
|
DeprecatedAlias,
|
||||||
|
all_with_deprecated_constants,
|
||||||
|
check_if_deprecated_constant,
|
||||||
|
dir_with_deprecated_constants,
|
||||||
|
)
|
||||||
|
|
||||||
|
# cached_property deprecated as of 2024.5 use functools.cached_property instead.
|
||||||
|
_DEPRECATED_cached_property = DeprecatedAlias(
|
||||||
|
_cached_property, "functools.cached_property", "2025.5"
|
||||||
|
)
|
||||||
|
|
||||||
|
__getattr__ = partial(check_if_deprecated_constant, module_globals=globals())
|
||||||
|
__dir__ = partial(
|
||||||
|
dir_with_deprecated_constants, module_globals_keys=[*globals().keys()]
|
||||||
|
)
|
||||||
|
__all__ = all_with_deprecated_constants(globals())
|
||||||
184
home-assistant/homeassistant/backup_restore.py
Normal file
184
home-assistant/homeassistant/backup_restore.py
Normal file
@@ -0,0 +1,184 @@
|
|||||||
|
"""Home Assistant module to handle restoring backups."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections.abc import Iterable
|
||||||
|
from dataclasses import dataclass
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
from pathlib import Path
|
||||||
|
import shutil
|
||||||
|
import sys
|
||||||
|
from tempfile import TemporaryDirectory
|
||||||
|
|
||||||
|
from awesomeversion import AwesomeVersion
|
||||||
|
import securetar
|
||||||
|
|
||||||
|
from .const import __version__ as HA_VERSION
|
||||||
|
|
||||||
|
RESTORE_BACKUP_FILE = ".HA_RESTORE"
|
||||||
|
KEEP_BACKUPS = ("backups",)
|
||||||
|
KEEP_DATABASE = (
|
||||||
|
"home-assistant_v2.db",
|
||||||
|
"home-assistant_v2.db-wal",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class RestoreBackupFileContent:
|
||||||
|
"""Definition for restore backup file content."""
|
||||||
|
|
||||||
|
backup_file_path: Path
|
||||||
|
password: str | None
|
||||||
|
remove_after_restore: bool
|
||||||
|
restore_database: bool
|
||||||
|
restore_homeassistant: bool
|
||||||
|
|
||||||
|
|
||||||
|
def password_to_key(password: str) -> bytes:
|
||||||
|
"""Generate a AES Key from password.
|
||||||
|
|
||||||
|
Matches the implementation in supervisor.backups.utils.password_to_key.
|
||||||
|
"""
|
||||||
|
key: bytes = password.encode()
|
||||||
|
for _ in range(100):
|
||||||
|
key = hashlib.sha256(key).digest()
|
||||||
|
return key[:16]
|
||||||
|
|
||||||
|
|
||||||
|
def restore_backup_file_content(config_dir: Path) -> RestoreBackupFileContent | None:
|
||||||
|
"""Return the contents of the restore backup file."""
|
||||||
|
instruction_path = config_dir.joinpath(RESTORE_BACKUP_FILE)
|
||||||
|
try:
|
||||||
|
instruction_content = json.loads(instruction_path.read_text(encoding="utf-8"))
|
||||||
|
return RestoreBackupFileContent(
|
||||||
|
backup_file_path=Path(instruction_content["path"]),
|
||||||
|
password=instruction_content["password"],
|
||||||
|
remove_after_restore=instruction_content["remove_after_restore"],
|
||||||
|
restore_database=instruction_content["restore_database"],
|
||||||
|
restore_homeassistant=instruction_content["restore_homeassistant"],
|
||||||
|
)
|
||||||
|
except (FileNotFoundError, KeyError, json.JSONDecodeError):
|
||||||
|
return None
|
||||||
|
finally:
|
||||||
|
# Always remove the backup instruction file to prevent a boot loop
|
||||||
|
instruction_path.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
def _clear_configuration_directory(config_dir: Path, keep: Iterable[str]) -> None:
|
||||||
|
"""Delete all files and directories in the config directory except entries in the keep list."""
|
||||||
|
keep_paths = [config_dir.joinpath(path) for path in keep]
|
||||||
|
entries_to_remove = sorted(
|
||||||
|
entry for entry in config_dir.iterdir() if entry not in keep_paths
|
||||||
|
)
|
||||||
|
|
||||||
|
for entry in entries_to_remove:
|
||||||
|
entrypath = config_dir.joinpath(entry)
|
||||||
|
|
||||||
|
if entrypath.is_file():
|
||||||
|
entrypath.unlink()
|
||||||
|
elif entrypath.is_dir():
|
||||||
|
shutil.rmtree(entrypath)
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_backup(
|
||||||
|
config_dir: Path,
|
||||||
|
restore_content: RestoreBackupFileContent,
|
||||||
|
) -> None:
|
||||||
|
"""Extract the backup file to the config directory."""
|
||||||
|
with (
|
||||||
|
TemporaryDirectory() as tempdir,
|
||||||
|
securetar.SecureTarFile(
|
||||||
|
restore_content.backup_file_path,
|
||||||
|
gzip=False,
|
||||||
|
mode="r",
|
||||||
|
) as ostf,
|
||||||
|
):
|
||||||
|
ostf.extractall(
|
||||||
|
path=Path(tempdir, "extracted"),
|
||||||
|
members=securetar.secure_path(ostf),
|
||||||
|
filter="fully_trusted",
|
||||||
|
)
|
||||||
|
backup_meta_file = Path(tempdir, "extracted", "backup.json")
|
||||||
|
backup_meta = json.loads(backup_meta_file.read_text(encoding="utf8"))
|
||||||
|
|
||||||
|
if (
|
||||||
|
backup_meta_version := AwesomeVersion(
|
||||||
|
backup_meta["homeassistant"]["version"]
|
||||||
|
)
|
||||||
|
) > HA_VERSION:
|
||||||
|
raise ValueError(
|
||||||
|
f"You need at least Home Assistant version {backup_meta_version} to restore this backup"
|
||||||
|
)
|
||||||
|
|
||||||
|
with securetar.SecureTarFile(
|
||||||
|
Path(
|
||||||
|
tempdir,
|
||||||
|
"extracted",
|
||||||
|
f"homeassistant.tar{'.gz' if backup_meta["compressed"] else ''}",
|
||||||
|
),
|
||||||
|
gzip=backup_meta["compressed"],
|
||||||
|
key=password_to_key(restore_content.password)
|
||||||
|
if restore_content.password is not None
|
||||||
|
else None,
|
||||||
|
mode="r",
|
||||||
|
) as istf:
|
||||||
|
istf.extractall(
|
||||||
|
path=Path(tempdir, "homeassistant"),
|
||||||
|
members=securetar.secure_path(istf),
|
||||||
|
filter="fully_trusted",
|
||||||
|
)
|
||||||
|
if restore_content.restore_homeassistant:
|
||||||
|
keep = list(KEEP_BACKUPS)
|
||||||
|
if not restore_content.restore_database:
|
||||||
|
keep.extend(KEEP_DATABASE)
|
||||||
|
_clear_configuration_directory(config_dir, keep)
|
||||||
|
shutil.copytree(
|
||||||
|
Path(tempdir, "homeassistant", "data"),
|
||||||
|
config_dir,
|
||||||
|
dirs_exist_ok=True,
|
||||||
|
ignore=shutil.ignore_patterns(*(keep)),
|
||||||
|
)
|
||||||
|
elif restore_content.restore_database:
|
||||||
|
for entry in KEEP_DATABASE:
|
||||||
|
entrypath = config_dir / entry
|
||||||
|
|
||||||
|
if entrypath.is_file():
|
||||||
|
entrypath.unlink()
|
||||||
|
elif entrypath.is_dir():
|
||||||
|
shutil.rmtree(entrypath)
|
||||||
|
|
||||||
|
for entry in KEEP_DATABASE:
|
||||||
|
shutil.copy(
|
||||||
|
Path(tempdir, "homeassistant", "data", entry),
|
||||||
|
config_dir,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def restore_backup(config_dir_path: str) -> bool:
|
||||||
|
"""Restore the backup file if any.
|
||||||
|
|
||||||
|
Returns True if a restore backup file was found and restored, False otherwise.
|
||||||
|
"""
|
||||||
|
config_dir = Path(config_dir_path)
|
||||||
|
if not (restore_content := restore_backup_file_content(config_dir)):
|
||||||
|
return False
|
||||||
|
|
||||||
|
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
|
||||||
|
backup_file_path = restore_content.backup_file_path
|
||||||
|
_LOGGER.info("Restoring %s", backup_file_path)
|
||||||
|
try:
|
||||||
|
_extract_backup(
|
||||||
|
config_dir=config_dir,
|
||||||
|
restore_content=restore_content,
|
||||||
|
)
|
||||||
|
except FileNotFoundError as err:
|
||||||
|
raise ValueError(f"Backup file {backup_file_path} does not exist") from err
|
||||||
|
if restore_content.remove_after_restore:
|
||||||
|
backup_file_path.unlink(missing_ok=True)
|
||||||
|
_LOGGER.info("Restore complete, restarting")
|
||||||
|
return True
|
||||||
258
home-assistant/homeassistant/block_async_io.py
Normal file
258
home-assistant/homeassistant/block_async_io.py
Normal file
@@ -0,0 +1,258 @@
|
|||||||
|
"""Block blocking calls being done in asyncio."""
|
||||||
|
|
||||||
|
import builtins
|
||||||
|
from collections.abc import Callable
|
||||||
|
from contextlib import suppress
|
||||||
|
from dataclasses import dataclass
|
||||||
|
import glob
|
||||||
|
from http.client import HTTPConnection
|
||||||
|
import importlib
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
from ssl import SSLContext
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from .helpers.frame import get_current_frame
|
||||||
|
from .util.loop import protect_loop
|
||||||
|
|
||||||
|
_IN_TESTS = "unittest" in sys.modules
|
||||||
|
|
||||||
|
ALLOWED_FILE_PREFIXES = ("/proc",)
|
||||||
|
|
||||||
|
|
||||||
|
def _check_import_call_allowed(mapped_args: dict[str, Any]) -> bool:
|
||||||
|
# If the module is already imported, we can ignore it.
|
||||||
|
return bool((args := mapped_args.get("args")) and args[0] in sys.modules)
|
||||||
|
|
||||||
|
|
||||||
|
def _check_file_allowed(mapped_args: dict[str, Any]) -> bool:
|
||||||
|
# If the file is in /proc we can ignore it.
|
||||||
|
args = mapped_args["args"]
|
||||||
|
path = args[0] if type(args[0]) is str else str(args[0]) # noqa: E721
|
||||||
|
return path.startswith(ALLOWED_FILE_PREFIXES)
|
||||||
|
|
||||||
|
|
||||||
|
def _check_sleep_call_allowed(mapped_args: dict[str, Any]) -> bool:
|
||||||
|
#
|
||||||
|
# Avoid extracting the stack unless we need to since it
|
||||||
|
# will have to access the linecache which can do blocking
|
||||||
|
# I/O and we are trying to avoid blocking calls.
|
||||||
|
#
|
||||||
|
# frame[0] is us
|
||||||
|
# frame[1] is raise_for_blocking_call
|
||||||
|
# frame[2] is protected_loop_func
|
||||||
|
# frame[3] is the offender
|
||||||
|
with suppress(ValueError):
|
||||||
|
return get_current_frame(4).f_code.co_filename.endswith("pydevd.py")
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _check_load_verify_locations_call_allowed(mapped_args: dict[str, Any]) -> bool:
|
||||||
|
# If only cadata is passed, we can ignore it
|
||||||
|
kwargs = mapped_args.get("kwargs")
|
||||||
|
return bool(kwargs and len(kwargs) == 1 and "cadata" in kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(slots=True, frozen=True)
|
||||||
|
class BlockingCall:
|
||||||
|
"""Class to hold information about a blocking call."""
|
||||||
|
|
||||||
|
original_func: Callable
|
||||||
|
object: object
|
||||||
|
function: str
|
||||||
|
check_allowed: Callable[[dict[str, Any]], bool] | None
|
||||||
|
strict: bool
|
||||||
|
strict_core: bool
|
||||||
|
skip_for_tests: bool
|
||||||
|
|
||||||
|
|
||||||
|
_BLOCKING_CALLS: tuple[BlockingCall, ...] = (
|
||||||
|
BlockingCall(
|
||||||
|
original_func=HTTPConnection.putrequest,
|
||||||
|
object=HTTPConnection,
|
||||||
|
function="putrequest",
|
||||||
|
check_allowed=None,
|
||||||
|
strict=True,
|
||||||
|
strict_core=True,
|
||||||
|
skip_for_tests=False,
|
||||||
|
),
|
||||||
|
BlockingCall(
|
||||||
|
original_func=time.sleep,
|
||||||
|
object=time,
|
||||||
|
function="sleep",
|
||||||
|
check_allowed=_check_sleep_call_allowed,
|
||||||
|
strict=True,
|
||||||
|
strict_core=True,
|
||||||
|
skip_for_tests=False,
|
||||||
|
),
|
||||||
|
BlockingCall(
|
||||||
|
original_func=glob.glob,
|
||||||
|
object=glob,
|
||||||
|
function="glob",
|
||||||
|
check_allowed=None,
|
||||||
|
strict=False,
|
||||||
|
strict_core=False,
|
||||||
|
skip_for_tests=False,
|
||||||
|
),
|
||||||
|
BlockingCall(
|
||||||
|
original_func=glob.iglob,
|
||||||
|
object=glob,
|
||||||
|
function="iglob",
|
||||||
|
check_allowed=None,
|
||||||
|
strict=False,
|
||||||
|
strict_core=False,
|
||||||
|
skip_for_tests=False,
|
||||||
|
),
|
||||||
|
BlockingCall(
|
||||||
|
original_func=os.walk,
|
||||||
|
object=os,
|
||||||
|
function="walk",
|
||||||
|
check_allowed=None,
|
||||||
|
strict=False,
|
||||||
|
strict_core=False,
|
||||||
|
skip_for_tests=False,
|
||||||
|
),
|
||||||
|
BlockingCall(
|
||||||
|
original_func=os.listdir,
|
||||||
|
object=os,
|
||||||
|
function="listdir",
|
||||||
|
check_allowed=None,
|
||||||
|
strict=False,
|
||||||
|
strict_core=False,
|
||||||
|
skip_for_tests=True,
|
||||||
|
),
|
||||||
|
BlockingCall(
|
||||||
|
original_func=os.scandir,
|
||||||
|
object=os,
|
||||||
|
function="scandir",
|
||||||
|
check_allowed=None,
|
||||||
|
strict=False,
|
||||||
|
strict_core=False,
|
||||||
|
skip_for_tests=True,
|
||||||
|
),
|
||||||
|
BlockingCall(
|
||||||
|
original_func=builtins.open,
|
||||||
|
object=builtins,
|
||||||
|
function="open",
|
||||||
|
check_allowed=_check_file_allowed,
|
||||||
|
strict=False,
|
||||||
|
strict_core=False,
|
||||||
|
skip_for_tests=True,
|
||||||
|
),
|
||||||
|
BlockingCall(
|
||||||
|
original_func=importlib.import_module,
|
||||||
|
object=importlib,
|
||||||
|
function="import_module",
|
||||||
|
check_allowed=_check_import_call_allowed,
|
||||||
|
strict=False,
|
||||||
|
strict_core=False,
|
||||||
|
skip_for_tests=True,
|
||||||
|
),
|
||||||
|
BlockingCall(
|
||||||
|
original_func=SSLContext.load_default_certs,
|
||||||
|
object=SSLContext,
|
||||||
|
function="load_default_certs",
|
||||||
|
check_allowed=None,
|
||||||
|
strict=False,
|
||||||
|
strict_core=False,
|
||||||
|
skip_for_tests=True,
|
||||||
|
),
|
||||||
|
BlockingCall(
|
||||||
|
original_func=SSLContext.load_verify_locations,
|
||||||
|
object=SSLContext,
|
||||||
|
function="load_verify_locations",
|
||||||
|
check_allowed=_check_load_verify_locations_call_allowed,
|
||||||
|
strict=False,
|
||||||
|
strict_core=False,
|
||||||
|
skip_for_tests=True,
|
||||||
|
),
|
||||||
|
BlockingCall(
|
||||||
|
original_func=SSLContext.load_cert_chain,
|
||||||
|
object=SSLContext,
|
||||||
|
function="load_cert_chain",
|
||||||
|
check_allowed=None,
|
||||||
|
strict=False,
|
||||||
|
strict_core=False,
|
||||||
|
skip_for_tests=True,
|
||||||
|
),
|
||||||
|
BlockingCall(
|
||||||
|
original_func=Path.open,
|
||||||
|
object=Path,
|
||||||
|
function="open",
|
||||||
|
check_allowed=_check_file_allowed,
|
||||||
|
strict=False,
|
||||||
|
strict_core=False,
|
||||||
|
skip_for_tests=True,
|
||||||
|
),
|
||||||
|
BlockingCall(
|
||||||
|
original_func=Path.read_text,
|
||||||
|
object=Path,
|
||||||
|
function="read_text",
|
||||||
|
check_allowed=_check_file_allowed,
|
||||||
|
strict=False,
|
||||||
|
strict_core=False,
|
||||||
|
skip_for_tests=True,
|
||||||
|
),
|
||||||
|
BlockingCall(
|
||||||
|
original_func=Path.read_bytes,
|
||||||
|
object=Path,
|
||||||
|
function="read_bytes",
|
||||||
|
check_allowed=_check_file_allowed,
|
||||||
|
strict=False,
|
||||||
|
strict_core=False,
|
||||||
|
skip_for_tests=True,
|
||||||
|
),
|
||||||
|
BlockingCall(
|
||||||
|
original_func=Path.write_text,
|
||||||
|
object=Path,
|
||||||
|
function="write_text",
|
||||||
|
check_allowed=_check_file_allowed,
|
||||||
|
strict=False,
|
||||||
|
strict_core=False,
|
||||||
|
skip_for_tests=True,
|
||||||
|
),
|
||||||
|
BlockingCall(
|
||||||
|
original_func=Path.write_bytes,
|
||||||
|
object=Path,
|
||||||
|
function="write_bytes",
|
||||||
|
check_allowed=_check_file_allowed,
|
||||||
|
strict=False,
|
||||||
|
strict_core=False,
|
||||||
|
skip_for_tests=True,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(slots=True)
|
||||||
|
class BlockedCalls:
|
||||||
|
"""Class to track which calls are blocked."""
|
||||||
|
|
||||||
|
calls: set[BlockingCall]
|
||||||
|
|
||||||
|
|
||||||
|
_BLOCKED_CALLS = BlockedCalls(set())
|
||||||
|
|
||||||
|
|
||||||
|
def enable() -> None:
|
||||||
|
"""Enable the detection of blocking calls in the event loop."""
|
||||||
|
calls = _BLOCKED_CALLS.calls
|
||||||
|
if calls:
|
||||||
|
raise RuntimeError("Blocking call detection is already enabled")
|
||||||
|
|
||||||
|
loop_thread_id = threading.get_ident()
|
||||||
|
for blocking_call in _BLOCKING_CALLS:
|
||||||
|
if _IN_TESTS and blocking_call.skip_for_tests:
|
||||||
|
continue
|
||||||
|
|
||||||
|
protected_function = protect_loop(
|
||||||
|
blocking_call.original_func,
|
||||||
|
strict=blocking_call.strict,
|
||||||
|
strict_core=blocking_call.strict_core,
|
||||||
|
check_allowed=blocking_call.check_allowed,
|
||||||
|
loop_thread_id=loop_thread_id,
|
||||||
|
)
|
||||||
|
setattr(blocking_call.object, blocking_call.function, protected_function)
|
||||||
|
calls.add(blocking_call)
|
||||||
1079
home-assistant/homeassistant/bootstrap.py
Normal file
1079
home-assistant/homeassistant/bootstrap.py
Normal file
File diff suppressed because it is too large
Load Diff
5
home-assistant/homeassistant/brands/airthings.json
Normal file
5
home-assistant/homeassistant/brands/airthings.json
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"domain": "airthings",
|
||||||
|
"name": "Airthings",
|
||||||
|
"integrations": ["airthings", "airthings_ble"]
|
||||||
|
}
|
||||||
5
home-assistant/homeassistant/brands/airvisual.json
Normal file
5
home-assistant/homeassistant/brands/airvisual.json
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"domain": "airvisual",
|
||||||
|
"name": "AirVisual",
|
||||||
|
"integrations": ["airvisual", "airvisual_pro"]
|
||||||
|
}
|
||||||
5
home-assistant/homeassistant/brands/airzone.json
Normal file
5
home-assistant/homeassistant/brands/airzone.json
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"domain": "airzone",
|
||||||
|
"name": "Airzone",
|
||||||
|
"integrations": ["airzone", "airzone_cloud"]
|
||||||
|
}
|
||||||
5
home-assistant/homeassistant/brands/amazon.json
Normal file
5
home-assistant/homeassistant/brands/amazon.json
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"domain": "amazon",
|
||||||
|
"name": "Amazon",
|
||||||
|
"integrations": ["alexa", "amazon_polly", "aws", "fire_tv", "route53"]
|
||||||
|
}
|
||||||
5
home-assistant/homeassistant/brands/ambient_weather.json
Normal file
5
home-assistant/homeassistant/brands/ambient_weather.json
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"domain": "ambient_weather",
|
||||||
|
"name": "Ambient Weather",
|
||||||
|
"integrations": ["ambient_network", "ambient_station"]
|
||||||
|
}
|
||||||
13
home-assistant/homeassistant/brands/apple.json
Normal file
13
home-assistant/homeassistant/brands/apple.json
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
{
|
||||||
|
"domain": "apple",
|
||||||
|
"name": "Apple",
|
||||||
|
"integrations": [
|
||||||
|
"apple_tv",
|
||||||
|
"homekit_controller",
|
||||||
|
"homekit",
|
||||||
|
"ibeacon",
|
||||||
|
"icloud",
|
||||||
|
"itunes",
|
||||||
|
"weatherkit"
|
||||||
|
]
|
||||||
|
}
|
||||||
5
home-assistant/homeassistant/brands/aqara.json
Normal file
5
home-assistant/homeassistant/brands/aqara.json
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"domain": "aqara",
|
||||||
|
"name": "Aqara",
|
||||||
|
"iot_standards": ["matter", "zigbee"]
|
||||||
|
}
|
||||||
5
home-assistant/homeassistant/brands/aruba.json
Normal file
5
home-assistant/homeassistant/brands/aruba.json
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"domain": "aruba",
|
||||||
|
"name": "Aruba",
|
||||||
|
"integrations": ["aruba", "cppm_tracker"]
|
||||||
|
}
|
||||||
5
home-assistant/homeassistant/brands/august.json
Normal file
5
home-assistant/homeassistant/brands/august.json
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"domain": "august",
|
||||||
|
"name": "August Home",
|
||||||
|
"integrations": ["august", "yalexs_ble"]
|
||||||
|
}
|
||||||
5
home-assistant/homeassistant/brands/cisco.json
Normal file
5
home-assistant/homeassistant/brands/cisco.json
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"domain": "cisco",
|
||||||
|
"name": "Cisco",
|
||||||
|
"integrations": ["cisco_ios", "cisco_mobility_express", "cisco_webex_teams"]
|
||||||
|
}
|
||||||
5
home-assistant/homeassistant/brands/clicksend.json
Normal file
5
home-assistant/homeassistant/brands/clicksend.json
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"domain": "clicksend",
|
||||||
|
"name": "ClickSend",
|
||||||
|
"integrations": ["clicksend", "clicksend_tts"]
|
||||||
|
}
|
||||||
5
home-assistant/homeassistant/brands/denon.json
Normal file
5
home-assistant/homeassistant/brands/denon.json
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"domain": "denon",
|
||||||
|
"name": "Denon",
|
||||||
|
"integrations": ["denon", "denonavr", "heos"]
|
||||||
|
}
|
||||||
6
home-assistant/homeassistant/brands/devolo.json
Normal file
6
home-assistant/homeassistant/brands/devolo.json
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"domain": "devolo",
|
||||||
|
"name": "devolo",
|
||||||
|
"integrations": ["devolo_home_control", "devolo_home_network"],
|
||||||
|
"iot_standards": ["zwave"]
|
||||||
|
}
|
||||||
5
home-assistant/homeassistant/brands/dlna.json
Normal file
5
home-assistant/homeassistant/brands/dlna.json
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"domain": "dlna",
|
||||||
|
"name": "DLNA",
|
||||||
|
"integrations": ["dlna_dmr", "dlna_dms"]
|
||||||
|
}
|
||||||
5
home-assistant/homeassistant/brands/elgato.json
Normal file
5
home-assistant/homeassistant/brands/elgato.json
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"domain": "elgato",
|
||||||
|
"name": "Elgato",
|
||||||
|
"integrations": ["avea", "elgato"]
|
||||||
|
}
|
||||||
5
home-assistant/homeassistant/brands/emoncms.json
Normal file
5
home-assistant/homeassistant/brands/emoncms.json
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"domain": "emoncms",
|
||||||
|
"name": "emoncms",
|
||||||
|
"integrations": ["emoncms", "emoncms_history"]
|
||||||
|
}
|
||||||
5
home-assistant/homeassistant/brands/eq3.json
Normal file
5
home-assistant/homeassistant/brands/eq3.json
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"domain": "eq3",
|
||||||
|
"name": "eQ-3",
|
||||||
|
"integrations": ["maxcube", "eq3btsmart"]
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user