diff --git a/changelog/highlights/320.json b/changelog/highlights/320.json new file mode 100644 index 000000000..b5aa416f8 --- /dev/null +++ b/changelog/highlights/320.json @@ -0,0 +1,8 @@ +{ + "de": { + "*": "Home Assistant Ports werden auf dem Node installiert und betrieben" + }, + "en": { + "*": "Install and run Home Assistant ports on the node" + } +} diff --git a/dashboard/CHANGELOG.md b/dashboard/CHANGELOG.md index 43505c7e1..93a4887b8 100644 --- a/dashboard/CHANGELOG.md +++ b/dashboard/CHANGELOG.md @@ -1,11 +1,15 @@ # Changelog -## v0.12.1-pre.2 (2026-12-04) +## v0.12.1-pre.3 (2026-12-06) ### Features - **dashboard:** A compact header whose status chip names the cause of a problem (#316) (6f5aa61) - **overview:** add a device map card to the overview (#318) (1557b48) +- **dashboard:** allow Home Assistant port sections in the config schema (02c1387) +- **dashboard:** list Home Assistant port units in diagnostics and service logs (4ab3000) +- **dashboard:** let the system action helper read and stop Home Assistant port units (9e8f14c) +- **ha:** install and run Home Assistant ports on the node (#320) - **overview:** add the device_map card type to the layout settings (a226f60) - **overview:** add viewport gestures and fit spring for map cards (62c9456) - **overview:** add the device map card component (a99435a) @@ -22,6 +26,7 @@ ### Fixes +- **dashboard:** show port sections in the system settings form (1856b7d) - **energy:** show role edges with the data layer on the live core (124761f) - **overview:** make viewport attach idempotent (7d40301) - **overview:** clear the refresh timer when a live map is destroyed (d6ab607) diff --git a/dashboard/VERSION b/dashboard/VERSION index 7e5116881..b686b7123 100644 --- a/dashboard/VERSION +++ b/dashboard/VERSION @@ -1 +1 @@ -v0.12.1-pre.2 +v0.12.1-pre.3 diff --git a/dashboard/cmd/schemagen/core.schema.json b/dashboard/cmd/schemagen/core.schema.json index 12e9c7e4e..6f630b69f 100644 --- a/dashboard/cmd/schemagen/core.schema.json +++ b/dashboard/cmd/schemagen/core.schema.json @@ -42,7 +42,18 @@ "title": "Services", "additionalProperties": false, "required": [], - "properties": {} + "properties": {}, + "patternProperties": { + "^ha_[a-z0-9_]+$": { + "title": "Home Assistant port", + "type": "object", + "additionalProperties": false, + "required": ["service_id"], + "properties": { + "service_id": {"type": "string", "pattern": "^ha_[a-z0-9_]+$", "title": "Service ID", "description": "Identifies the port in its MQTT topics."} + } + } + } }, "installed_services": { "type": "object", diff --git a/dashboard/energy-node-dashboard-system-action b/dashboard/energy-node-dashboard-system-action index 8266fe2f9..00a5fb5c7 100644 --- a/dashboard/energy-node-dashboard-system-action +++ b/dashboard/energy-node-dashboard-system-action @@ -23,6 +23,11 @@ APP_CONFIG_OWNER="energynode" # replaces this line with a stub, so keep the assignment on one line. JOURNALCTL="/usr/bin/journalctl" +# Manifest directory of the Home Assistant ports. The test +# scripts/tests/test_bootstrap_dashboard_read_journal.sh replaces this line +# with a temp dir, so keep the assignment on one line. +HA_MANIFEST_DIR="/etc/energy-node/manifests" + # systemctl binary for stop-services and start-services. The test # scripts/tests/test_system_action_services.sh replaces this line with a # stub, so keep the assignment on one line. @@ -178,12 +183,25 @@ apply_app_config() { exit 0 } +# ha_domain_ok succeeds only for a Home Assistant port domain: 1 to 40 +# characters of a-z, 0-9 and underscore. The pattern is a case glob with a +# negated class, so a newline, a slash, a dot, a semicolon or an uppercase +# letter always fails. +ha_domain_ok() { + case "$1" in + ''|*[!a-z0-9_]*) return 1 ;; + esac + [ "${#1}" -le 40 ] +} + # read_journal prints journal entries of one allowlisted unit as JSON lines. -# Arguments: key (dashboard|tailscale), since in minutes (15|60|360|1440|10080), -# lines (100|200|500|1000) and an optional cursor. The key is one of the -# eleven allowlisted service keys in the case below. The cursor must start with -# "s=", be at most 256 characters, and contain only [A-Za-z0-9=;], so it can -# never be read as a journalctl option. Exit codes of journalctl pass through. +# Arguments: key (dashboard|tailscale|ha-), since in minutes +# (15|60|360|1440|10080), lines (100|200|500|1000) and an optional cursor. The +# key is one of the eleven allowlisted service keys in the case below, or +# ha- for a Home Assistant port whose manifest exists. The cursor must +# start with "s=", be at most 256 characters, and contain only [A-Za-z0-9=;], so +# it can never be read as a journalctl option. Exit codes of journalctl pass +# through. read_journal() { key="$1" since="$2" @@ -202,6 +220,12 @@ read_journal() { mosquitto) unit="mosquitto.service" ;; caddy) unit="caddy.service" ;; tailscale) unit="tailscaled.service" ;; + ha-*) + domain="${key#ha-}" + ha_domain_ok "$domain" || exit 65 + [ -f "$HA_MANIFEST_DIR/ha_${domain}.json" ] || exit 65 + unit="energy-node-ha@${domain}.service" + ;; *) exit 65 ;; esac case "$since" in @@ -274,11 +298,31 @@ storage_helper() { esac } -# service_units prints the units that stop-services and start-services act on. -# Keep the names in step with the units of the read_journal case statement. +# service_units prints the units that stop-services and start-services act on: +# the fixed list, then every enabled Home Assistant port unit. Keep the fixed +# names in step with the units of the read_journal case statement. service_units() { printf '%s\n' automation.service battery-soc.service shelly-rpc.service \ trucki-http.service tuya.service apsystems-ez1.service + ha_port_units +} + +# ha_port_units prints every enabled energy-node-ha@.service whose +# domain passes ha_domain_ok. Any other name, including the template unit +# itself, is dropped. +ha_port_units() { + "$SYSTEMCTL" list-unit-files 'energy-node-ha@*.service' --state=enabled --no-legend 2>/dev/null \ + | while read -r unit _; do + case "$unit" in + energy-node-ha@*.service) : ;; + *) continue ;; + esac + domain="${unit#energy-node-ha@}" + domain="${domain%.service}" + if ha_domain_ok "$domain"; then + printf '%s\n' "energy-node-ha@${domain}.service" + fi + done } # service_loop VERB runs "systemctl VERB UNIT" for every enabled unit of diff --git a/dashboard/internal/appconfig/appconfig_test.go b/dashboard/internal/appconfig/appconfig_test.go index 53b8271bb..9b228452f 100644 --- a/dashboard/internal/appconfig/appconfig_test.go +++ b/dashboard/internal/appconfig/appconfig_test.go @@ -380,3 +380,30 @@ func TestSchemaAcceptsConfigWithoutRuntimeDir(t *testing.T) { t.Fatalf("Load ohne runtime_dir: %v", err) } } + +func TestSchemaAcceptsHAPortSection(t *testing.T) { + document := validDocument() + document["services"].(map[string]any)["ha_nordpool"] = map[string]any{"service_id": "ha_nordpool"} + if _, err := appconfig.Load(writeConfig(t, document)); err != nil { + t.Fatalf("Load mit HA-Port-Abschnitt: %v", err) + } +} + +func TestSchemaRejectsUnknownService(t *testing.T) { + document := validDocument() + document["services"].(map[string]any)["foo"] = map[string]any{"service_id": "foo"} + if _, err := appconfig.Load(writeConfig(t, document)); err == nil { + t.Fatal("erwartete einen Schema-Fehler fuer den unbekannten Dienst foo") + } +} + +func TestSchemaRejectsHAPortExtraField(t *testing.T) { + document := validDocument() + document["services"].(map[string]any)["ha_nordpool"] = map[string]any{ + "service_id": "ha_nordpool", + "poll_interval_s": 60, + } + if _, err := appconfig.Load(writeConfig(t, document)); err == nil { + t.Fatal("erwartete einen Schema-Fehler fuer ein Zusatzfeld in einem HA-Port-Abschnitt") + } +} diff --git a/dashboard/internal/appconfig/config.schema.json b/dashboard/internal/appconfig/config.schema.json index 2669155ae..0aaf62a3c 100644 --- a/dashboard/internal/appconfig/config.schema.json +++ b/dashboard/internal/appconfig/config.schema.json @@ -270,6 +270,24 @@ }, "services": { "additionalProperties": false, + "patternProperties": { + "^ha_[a-z0-9_]+$": { + "additionalProperties": false, + "properties": { + "service_id": { + "description": "Identifies the port in its MQTT topics.", + "pattern": "^ha_[a-z0-9_]+$", + "title": "Service ID", + "type": "string" + } + }, + "required": [ + "service_id" + ], + "title": "Home Assistant port", + "type": "object" + } + }, "properties": { "apsystems": { "additionalProperties": false, diff --git a/dashboard/internal/config/config.go b/dashboard/internal/config/config.go index b697840d8..5a9baaa36 100644 --- a/dashboard/internal/config/config.go +++ b/dashboard/internal/config/config.go @@ -62,6 +62,12 @@ func displayName(name string) (key, label string) { if info, ok := displayNames[name]; ok { return info.key, info.label } + // Home Assistant port devices: ha__devices. + if rest, ok := strings.CutPrefix(name, "ha_"); ok { + if domain, ok := strings.CutSuffix(rest, "_devices"); ok && domain != "" { + return "", "HA: " + domain + } + } return "", name } @@ -534,6 +540,13 @@ func checkSchemaKeywords(raw any, path string) error { } } } + if patterns, ok := schema["patternProperties"].(map[string]any); ok { + for key, child := range patterns { + if err := checkSchemaKeywords(child, path+".patternProperties."+key); err != nil { + return err + } + } + } for _, keyword := range []string{"items", "if", "then", "else"} { if child, ok := schema[keyword]; ok { if err := checkSchemaKeywords(child, path+"."+keyword); err != nil { @@ -666,9 +679,17 @@ func applySchema(value, rawSchema any, path string) (map[string]bool, error) { return nil, fmt.Errorf("%s.%s is required", path, required) } } + patterns, _ := schema["patternProperties"].(map[string]any) if additional, ok := schema["additionalProperties"].(bool); ok && !additional { for _, key := range sortedKeys(object) { - if _, exists := properties[key]; !exists { + if _, exists := properties[key]; exists { + continue + } + matched, err := matchingPatternSchemas(patterns, key) + if err != nil { + return nil, err + } + if len(matched) == 0 { return nil, fmt.Errorf("%s.%s is not allowed", path, key) } } @@ -680,6 +701,16 @@ func applySchema(value, rawSchema any, path string) (map[string]bool, error) { return nil, err } } + matched, err := matchingPatternSchemas(patterns, key) + if err != nil { + return nil, err + } + for _, sub := range matched { + evaluated[key] = true + if err := validateValue(object[key], sub, path+"."+key); err != nil { + return nil, err + } + } } } if all, ok := schema["allOf"].([]any); ok { @@ -739,6 +770,23 @@ func applySchema(value, rawSchema any, path string) (map[string]bool, error) { return evaluated, nil } +// matchingPatternSchemas returns the patternProperties subschemas whose +// regular expression matches key, in pattern order. An invalid pattern is an +// error, so a broken schema cannot silently accept keys. +func matchingPatternSchemas(patterns map[string]any, key string) ([]any, error) { + var matched []any + for _, pattern := range sortedKeys(patterns) { + expr, err := compiledPattern(pattern) + if err != nil { + return nil, fmt.Errorf("invalid patternProperties pattern %q", pattern) + } + if expr.MatchString(key) { + matched = append(matched, patterns[pattern]) + } + } + return matched, nil +} + // branchDeclarations collects the properties of every then/else branch, // active or not, the first declaration winning (as allProperties in // schema-form.js). Deviating from JSON Schema on purpose: a field of an diff --git a/dashboard/internal/config/config_test.go b/dashboard/internal/config/config_test.go index aa17211db..629293d63 100644 --- a/dashboard/internal/config/config_test.go +++ b/dashboard/internal/config/config_test.go @@ -496,3 +496,33 @@ func TestAutomationRulesSchemaPatternAcceptsCustomCategories(t *testing.T) { t.Fatal("custom:Sauna accepted") } } + +const patternPropertiesSchema = `{"type":"object","additionalProperties":false,"properties":{"services":{"type":"object","additionalProperties":false,"properties":{},"patternProperties":{"^ha_[a-z0-9_]+$":{"type":"object","additionalProperties":false,"required":["service_id"],"properties":{"service_id":{"type":"string","pattern":"^ha_[a-z0-9_]+$"}}}}}}}` + +func TestPatternPropertiesAcceptsMatchingKey(t *testing.T) { + data := []byte(`{"services":{"ha_nordpool":{"service_id":"ha_nordpool"}}}`) + if err := ValidateDocument(data, []byte(patternPropertiesSchema)); err != nil { + t.Fatalf("matching key rejected: %v", err) + } +} + +func TestPatternPropertiesRejectsExtraFieldOnMatchingKey(t *testing.T) { + data := []byte(`{"services":{"ha_nordpool":{"service_id":"ha_nordpool","poll_interval_s":60}}}`) + if err := ValidateDocument(data, []byte(patternPropertiesSchema)); err == nil { + t.Fatal("extra field on a matching key was accepted") + } +} + +func TestPatternPropertiesRejectsNonMatchingKey(t *testing.T) { + data := []byte(`{"services":{"foo":{"service_id":"foo"}}}`) + if err := ValidateDocument(data, []byte(patternPropertiesSchema)); err == nil { + t.Fatal("non-matching key was accepted under additionalProperties false") + } +} + +func TestDisplayNameHAPort(t *testing.T) { + key, label := displayName("ha_nordpool_devices") + if key != "" || label != "HA: nordpool" { + t.Fatalf("displayName(ha_nordpool_devices) = (%q, %q), want (\"\", \"HA: nordpool\")", key, label) + } +} diff --git a/dashboard/internal/httpapi/servicelogs.go b/dashboard/internal/httpapi/servicelogs.go index 51064a489..649c561d2 100644 --- a/dashboard/internal/httpapi/servicelogs.go +++ b/dashboard/internal/httpapi/servicelogs.go @@ -4,12 +4,23 @@ import ( "context" "errors" "net/http" + "slices" "strconv" "github.com/Developer-Simon/energy-node-dashboard/internal/auth" "github.com/Developer-Simon/energy-node-dashboard/internal/servicelogs" ) +// portManifestDir is where the installed Home Assistant port manifests live. +// A variable so tests can point it at a temporary directory. +var portManifestDir = servicelogs.DefaultPortManifestDir + +// portLogUnits returns the Home Assistant port units the log screen may show. +// It is kept apart from the fixed units, so this part can be switched off alone. +func portLogUnits() []string { + return servicelogs.PortUnits(portManifestDir) +} + // ServiceLogReader reads the journal entries of one allowlisted service. // *servicelogs.Reader implements it. type ServiceLogReader interface { @@ -60,7 +71,7 @@ func handleServiceLogs(manager *auth.Manager, reader ServiceLogReader) http.Hand } query.Lines = n } - if err := query.Validate(); err != nil { + if err := query.ValidateWith(portLogUnits()); err != nil { writeError(w, http.StatusBadRequest, "log_query_invalid", "Die Log-Abfrage ist ungültig.") return } @@ -102,7 +113,7 @@ func handleServiceLogUnits(manager *auth.Manager) http.HandlerFunc { return } writeJSON(w, map[string]any{ - "units": servicelogs.Units, + "units": slices.Concat(servicelogs.Units, portLogUnits()), "since_minutes": servicelogs.SinceMinutes, "lines": servicelogs.LineLimits, "default_unit": servicelogs.DefaultUnit, diff --git a/dashboard/internal/httpapi/servicelogs_test.go b/dashboard/internal/httpapi/servicelogs_test.go index c1f1757c3..cb312d273 100644 --- a/dashboard/internal/httpapi/servicelogs_test.go +++ b/dashboard/internal/httpapi/servicelogs_test.go @@ -6,6 +6,7 @@ import ( "fmt" "net/http" "net/http/httptest" + "os" "path/filepath" "slices" "strings" @@ -229,3 +230,50 @@ func TestServiceLogsHiddenWithoutReader(t *testing.T) { } } } + +func TestServiceLogUnitsListsPortUnits(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "ha_nordpool.json"), []byte(`{"service_id":"ha_nordpool","unit":"energy-node-ha@nordpool.service","ha_port":{}}`), 0o644); err != nil { + t.Fatal(err) + } + previous := portManifestDir + portManifestDir = dir + t.Cleanup(func() { portManifestDir = previous }) + + router := newServiceLogsTestRouter(t, &fakeServiceLogReader{}) + admin, _ := loginAsAdmin(t, router) + recorder := serviceLogsGet(t, router, "/api/v1/system/logs/units", admin) + if recorder.Code != http.StatusOK { + t.Fatalf("status %d: %s", recorder.Code, recorder.Body.String()) + } + var body struct { + Units []string `json:"units"` + } + if err := json.Unmarshal(recorder.Body.Bytes(), &body); err != nil { + t.Fatal(err) + } + want := append(slices.Clone(servicelogs.Units), "ha-nordpool") + if !slices.Equal(body.Units, want) { + t.Fatalf("units = %q, want %q", body.Units, want) + } +} + +func TestServiceLogsAcceptsPortUnitQuery(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "ha_nordpool.json"), []byte(`{"service_id":"ha_nordpool","ha_port":{}}`), 0o644); err != nil { + t.Fatal(err) + } + previous := portManifestDir + portManifestDir = dir + t.Cleanup(func() { portManifestDir = previous }) + + reader := &fakeServiceLogReader{} + router := newServiceLogsTestRouter(t, reader) + admin, _ := loginAsAdmin(t, router) + if recorder := serviceLogsGet(t, router, "/api/v1/system/logs?unit=ha-nordpool", admin); recorder.Code != http.StatusOK { + t.Fatalf("port unit status %d: %s", recorder.Code, recorder.Body.String()) + } + if recorder := serviceLogsGet(t, router, "/api/v1/system/logs?unit=ha-unbekannt", admin); recorder.Code != http.StatusBadRequest { + t.Fatalf("unknown port unit status %d, want 400", recorder.Code) + } +} diff --git a/dashboard/internal/servicelogs/servicelogs.go b/dashboard/internal/servicelogs/servicelogs.go index f1f2aa578..6230bd879 100644 --- a/dashboard/internal/servicelogs/servicelogs.go +++ b/dashboard/internal/servicelogs/servicelogs.go @@ -6,9 +6,13 @@ import ( "bufio" "bytes" "context" + "encoding/json" "errors" "fmt" + "os" "os/exec" + "path/filepath" + "regexp" "slices" "strconv" "strings" @@ -18,6 +22,14 @@ import ( var Units = []string{"dashboard", "updater", "automation", "battery-soc", "shelly", "trucki", "tuya", "apsystems", "mosquitto", "caddy", "tailscale"} + +// DefaultPortManifestDir holds the manifests of the installed Home Assistant +// ports. Their ha- units are allowed next to the fixed Units. +const DefaultPortManifestDir = "/etc/energy-node/manifests" + +// portKeyPattern is the shape of a Home Assistant port unit key. +var portKeyPattern = regexp.MustCompile(`^ha-[a-z0-9_]{1,40}$`) + var SinceMinutes = []int{15, 60, 360, 1440, 10080} var LineLimits = []int{100, 200, 500, 1000} @@ -69,11 +81,44 @@ type Runner interface { Run(ctx context.Context, name string, args ...string) (stdout, stderr []byte, err error) } +// PortUnits returns ha- for every ha_.json manifest in +// manifestDir that has an ha_port entry. A missing directory gives no units. +func PortUnits(manifestDir string) []string { + units := []string{} + paths, _ := filepath.Glob(filepath.Join(manifestDir, "ha_*.json")) + for _, path := range paths { + raw, err := os.ReadFile(path) + if err != nil { + continue + } + var manifest map[string]json.RawMessage + if json.Unmarshal(raw, &manifest) != nil { + continue + } + if _, ok := manifest["ha_port"]; !ok { + continue + } + domain := strings.TrimSuffix(strings.TrimPrefix(filepath.Base(path), "ha_"), ".json") + if unit := "ha-" + domain; portKeyPattern.MatchString(unit) { + units = append(units, unit) + } + } + return units +} + // Validate checks every field against the allowlists. The cursor must match // what the helper accepts (prefix "s=", at most 256 characters, only // [A-Za-z0-9=;]), so an invalid cursor is rejected before any sudo call. func (q Query) Validate() error { - if !slices.Contains(Units, q.Unit) { + return q.ValidateWith(nil) +} + +// ValidateWith is Validate with extra allowed unit keys, such as the port +// units from PortUnits. An extra key must also match portKeyPattern. +func (q Query) ValidateWith(extra []string) error { + allowed := slices.Contains(Units, q.Unit) || + (slices.Contains(extra, q.Unit) && portKeyPattern.MatchString(q.Unit)) + if !allowed { return fmt.Errorf("%w: unit %q", ErrInvalidQuery, q.Unit) } if !slices.Contains(SinceMinutes, q.SinceMinutes) { @@ -103,10 +148,11 @@ const maxScanLine = 1 << 20 // Reader runs the system action helper's read-journal action for one query at // a time per slot, and never more than MaxConcurrent at once. type Reader struct { - runner Runner - helper string - timeout time.Duration - sem chan struct{} + runner Runner + helper string + timeout time.Duration + sem chan struct{} + portManifestDir string } // NewReader returns a Reader that calls helper through sudo. A nil runner @@ -116,17 +162,18 @@ func NewReader(runner Runner, helper string) *Reader { runner = execRunner{} } return &Reader{ - runner: runner, - helper: helper, - timeout: QueryTimeout, - sem: make(chan struct{}, MaxConcurrent), + runner: runner, + helper: helper, + timeout: QueryTimeout, + sem: make(chan struct{}, MaxConcurrent), + portManifestDir: DefaultPortManifestDir, } } // Read validates the query, runs the helper and returns the matching entries. // The filter is applied here, the cursor advances past every fetched line. func (r *Reader) Read(ctx context.Context, q Query) (Result, error) { - if err := q.Validate(); err != nil { + if err := q.ValidateWith(PortUnits(r.portManifestDir)); err != nil { return Result{}, err } diff --git a/dashboard/internal/servicelogs/servicelogs_test.go b/dashboard/internal/servicelogs/servicelogs_test.go index 2a679770d..6f0bcc66a 100644 --- a/dashboard/internal/servicelogs/servicelogs_test.go +++ b/dashboard/internal/servicelogs/servicelogs_test.go @@ -4,6 +4,8 @@ import ( "context" "encoding/json" "errors" + "os" + "path/filepath" "slices" "strings" "sync" @@ -286,3 +288,62 @@ func TestReadRejectsInvalidQueryWithoutRunning(t *testing.T) { t.Errorf("runner called %d times, want 0", n) } } + +func writeManifest(t *testing.T, dir, name, body string) { + t.Helper() + if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0o644); err != nil { + t.Fatal(err) + } +} + +func TestPortUnitsFromManifests(t *testing.T) { + dir := t.TempDir() + writeManifest(t, dir, "ha_nordpool.json", `{"service_id":"ha_nordpool","unit":"energy-node-ha@nordpool.service","ha_port":{}}`) + writeManifest(t, dir, "ha_plain.json", `{"service_id":"ha_plain","unit":"x.service"}`) + writeManifest(t, dir, "shelly.json", `{"service_id":"shelly","ha_port":{}}`) + got := PortUnits(dir) + if !slices.Equal(got, []string{"ha-nordpool"}) { + t.Fatalf("PortUnits() = %q, want [ha-nordpool]", got) + } + if got := PortUnits(filepath.Join(dir, "fehlt")); len(got) != 0 { + t.Fatalf("PortUnits(missing dir) = %q, want empty", got) + } +} + +func TestValidateWithAcceptsPortKey(t *testing.T) { + q := Query{Unit: "ha-nordpool", SinceMinutes: 60, Lines: 200} + if err := q.ValidateWith([]string{"ha-nordpool"}); err != nil { + t.Fatalf("ValidateWith() = %v, want nil", err) + } +} + +func TestValidateRejectsPortKeyWithoutExtra(t *testing.T) { + q := Query{Unit: "ha-nordpool", SinceMinutes: 60, Lines: 200} + if err := q.Validate(); !errors.Is(err, ErrInvalidQuery) { + t.Fatalf("Validate() = %v, want ErrInvalidQuery", err) + } + if err := q.ValidateWith(nil); !errors.Is(err, ErrInvalidQuery) { + t.Fatalf("ValidateWith(nil) = %v, want ErrInvalidQuery", err) + } +} + +func TestValidateWithRejectsBadKey(t *testing.T) { + q := Query{Unit: "ha-../x", SinceMinutes: 60, Lines: 200} + if err := q.ValidateWith([]string{"ha-../x"}); !errors.Is(err, ErrInvalidQuery) { + t.Fatalf("ValidateWith() = %v, want ErrInvalidQuery", err) + } +} + +func TestReadAcceptsPortUnitFromManifestDir(t *testing.T) { + dir := t.TempDir() + writeManifest(t, dir, "ha_nordpool.json", `{"service_id":"ha_nordpool","ha_port":{}}`) + fake := &fakeRunner{stdout: joinLines(fakeJournalLine(t, "s=1", "ok"))} + r := NewReader(fake, testHelper) + r.portManifestDir = dir + if _, err := r.Read(context.Background(), Query{Unit: "ha-nordpool", SinceMinutes: 60, Lines: 200}); err != nil { + t.Fatalf("Read() of port unit = %v, want nil", err) + } + if _, err := r.Read(context.Background(), Query{Unit: "ha-unbekannt", SinceMinutes: 60, Lines: 200}); !errors.Is(err, ErrInvalidQuery) { + t.Fatalf("Read() of unknown port unit = %v, want ErrInvalidQuery", err) + } +} diff --git a/dashboard/internal/webui/cache-bust-history.csv b/dashboard/internal/webui/cache-bust-history.csv index af7310617..01e082f91 100644 --- a/dashboard/internal/webui/cache-bust-history.csv +++ b/dashboard/internal/webui/cache-bust-history.csv @@ -1,4 +1,5 @@ version,date,asset,v,note +v0.12.1-pre.3,2026-12-06,js/schema-form.js,3, v0.12.1-pre.2,2026-12-03,css/base.css,57, v0.12.1-pre.2,2026-12-03,css/manager.css,55, v0.12.1-pre.2,2026-12-03,js/dashboard.js,58, diff --git a/dashboard/internal/webui/static/js/schema-form.js b/dashboard/internal/webui/static/js/schema-form.js index 4adf1dc5a..66909696d 100644 --- a/dashboard/internal/webui/static/js/schema-form.js +++ b/dashboard/internal/webui/static/js/schema-form.js @@ -223,6 +223,14 @@ return merged; } + // The patternProperties schema for a key, or null. The pattern has to match + // the whole key, so a key like "xha_x" does not count for "^ha_". + function patternSchemaFor(schema, key) { + const patterns = schema.patternProperties || {}; + const match = Object.keys(patterns).find(pattern => new RegExp(`^(?:${pattern})$`).test(key)); + return match === undefined ? null : patterns[match]; + } + // Decides a condition like the server validator for the subset the // schemas use: required, const and enum. An absent value passes a // property rule, as JSON Schema's properties keyword does. @@ -364,6 +372,16 @@ rendered.set(propertyKey, child); if (requiredFields.has(propertyKey)) node.append(child); else optionalFields.append(child); }); + // Keys that only a patternProperties entry declares (e.g. ha_ + // ports) render as plain children, so readNode writes them back. + if (value && typeof value === 'object' && !Array.isArray(value)) { + const declared = allProperties(schema); + Object.keys(value).forEach(childKey => { + if (Object.hasOwn(declared, childKey)) return; + const patternSchema = patternSchemaFor(schema, childKey); + if (patternSchema) node.append(renderNode(ctx, patternSchema, value[childKey], childKey, false, childKey)); + }); + } const branches = conditionalBranches(schema); const conditional = new Map(); const lastBehind = new Map(); @@ -493,17 +511,23 @@ if (!schema || value === null || typeof value !== 'object') return []; const found = []; if (schema.type === 'object' && !Array.isArray(value)) { - const known = new Set(Object.keys(allProperties(schema))); - if (schema.additionalProperties === false || schema.unevaluatedProperties === false) { - Object.keys(value).forEach(childKey => { - if (!known.has(childKey)) found.push(path ? `${path}.${childKey}` : childKey); - }); - } - Object.entries(allProperties(schema)).forEach(([childKey, childSchema]) => { + const declared = allProperties(schema); + const closed = schema.additionalProperties === false || schema.unevaluatedProperties === false; + Object.keys(value).forEach(childKey => { + if (Object.hasOwn(declared, childKey) || patternSchemaFor(schema, childKey)) return; + if (closed) found.push(path ? `${path}.${childKey}` : childKey); + }); + Object.entries(declared).forEach(([childKey, childSchema]) => { if (value[childKey] !== undefined) { found.push(...findUnknownKeys(childSchema, value[childKey], path ? `${path}.${childKey}` : childKey)); } }); + Object.keys(value).forEach(childKey => { + const patternSchema = Object.hasOwn(declared, childKey) ? null : patternSchemaFor(schema, childKey); + if (patternSchema) { + found.push(...findUnknownKeys(patternSchema, value[childKey], path ? `${path}.${childKey}` : childKey)); + } + }); } else if (schema.type === 'array' && Array.isArray(value)) { value.forEach((entry, index) => { found.push(...findUnknownKeys(schema.items || {}, entry, `${path}[${index}]`)); diff --git a/dashboard/internal/webui/templates/base.html b/dashboard/internal/webui/templates/base.html index 73165beb5..a8aba10df 100644 --- a/dashboard/internal/webui/templates/base.html +++ b/dashboard/internal/webui/templates/base.html @@ -241,10 +241,10 @@

{{t "no_access.title"}}

{{if index .Can "view_monitoring"}}

{{t "panel.monitoring_loading"}}

{{end}} {{if .Manager}} {{if index .Can "view_diagnostics"}}

{{t "panel.diagnostics_loading"}}

{{end}} -{{if index .Can "view_config"}}

{{t "panel.config_loading"}}

{{end}} +{{if index .Can "view_config"}}

{{t "panel.config_loading"}}

{{end}} {{if index .Can "view_energy"}}

{{t "panel.energy_loading"}}

{{end}} {{if index .Can "view_device_map"}}

{{t "panel.devicemap_loading"}}

{{end}} -

{{t "panel.settings_loading"}}

+

{{t "panel.settings_loading"}}

{{if index .Can "view_automations"}} {{if index .InstalledServices "automation"}}

{{t "panel.automations_loading"}}

{{end}}{{end}} {{else}} {{if index .Can "view_diagnostics"}}

{{t "panel.diagnostics_loading"}}

{{end}} diff --git a/dashboard/internal/webui/templates/settings.html b/dashboard/internal/webui/templates/settings.html index d4953f0d1..d5dbdfa55 100644 --- a/dashboard/internal/webui/templates/settings.html +++ b/dashboard/internal/webui/templates/settings.html @@ -706,7 +706,7 @@

{{t "settings.history.energy_stats.title"}}

+ data-subpage-script="{{.BasePath}}/static/js/schema-form.js?v=3,{{.BasePath}}/static/js/systemconfig.page.js?v=5" data-subpage-css="">