feat: add scoped user accounts, password login and garden paving materials

This commit is contained in:
jhartworks committed 2026-11-16 16:30:47 +01:00
1 parent c56f1a5ba9
commit 1d67e8ceba
43 files changed
+2024 -625

No files matched your search

+16
View File
@@ -0,0 +1,16 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { canControl } from "./access.ts";
import { entity, hassOf } from "./entities/fixtures.ts";
import { symconControl } from "./symcon-controls.ts";
test("native read-only flags survive role aliases; missing or forbidden targets have no controls", () => {
const st = entity("sensor.10", "30", { symcon_id: 10, symcon_variable_type: 2, symcon_numeric_value: 30, symcon_can_control: false });
const alias = symconControl(st, "light")!;
const h = hassOf([st, alias, entity("switch.20", "on", { symcon_can_control: true })], {}, { symconObjects: [] });
assert.equal(canControl(h, "sensor.10"), false);
assert.equal(canControl(h, "light.10"), false);
assert.equal(canControl(h, "switch.20"), true);
assert.equal(canControl(h, "switch.999"), false);
assert.equal(canControl(hassOf([st]), "sensor.10"), true, "HA behavior stays independent of Symcon roles");
});
+7
View File
@@ -0,0 +1,7 @@
import type { HomeAssistant } from "./types.ts";
/** Presentation guard only. The Symcon API independently checks every requested native target. */
export function canControl(hass: HomeAssistant | undefined, id: string): boolean {
if (!hass || hass.symconObjects === undefined) return true;
return !!hass.states[id] && hass.states[id].attributes.symcon_can_control !== false && hass.states[id].attributes.symcon_has_action !== false;
}
+4 -2
View File
@@ -8,6 +8,7 @@ import { onPluginsChanged } from "./plugins/registry.ts";
import { normalizeBuilding, type Building } from "./model.ts";
import { setPacks, type FurniturePack } from "./packs.ts";
import type { HomeAssistant } from "./types.ts";
import { isSymcon } from "./entities/symcon-values.ts";
export type SaveState = "idle" | "saving" | "saved" | "error";
@@ -111,6 +112,7 @@ export class BuildingController implements ReactiveController {
/** A local edit: visible at once, sent after a short pause. */
edit(building: Building): void {
if (this.hass && isSymcon(this.hass) && !this.hass.user?.is_admin) return;
this.building = building;
void loadPlugins(building.settings.plugins);
this.waiting = building;
@@ -179,7 +181,7 @@ export class BuildingController implements ReactiveController {
} catch (error) {
this.saveState = "error";
this.saveError = messageOf(error);
storeDraft({ building, savedAt: Date.now() }); // after a restart it can be restored and saved
if (!isSymcon(hass)) storeDraft({ building, savedAt: Date.now() }); // Symcon sessions do not leave private plans in shared browser storage.
}
this.host.requestUpdate();
}
@@ -221,7 +223,7 @@ export class BuildingController implements ReactiveController {
this.backendVersion = fetched.version ?? null;
this.revision = fetched.revision;
this.error = null;
if (this.draft === null && !this.waiting) this.draft = loadDraft();
if (!isSymcon(this.hass) && this.draft === null && !this.waiting) this.draft = loadDraft();
} catch (error) {
this.error = messageOf(error);
}
+9
View File
@@ -981,6 +981,15 @@ export const editorStyles = css`
fill: rgba(184, 163, 130, 0.24);
stroke: rgba(184, 163, 130, 0.65);
}
.nf-out-pavers polygon,
.nf-out-natural_stone polygon {
fill: rgba(170, 160, 135, 0.22);
stroke: rgba(170, 160, 135, 0.6);
}
.nf-out-stepping_stones polygon {
fill: rgba(130, 170, 110, 0.18);
stroke: rgba(160, 190, 140, 0.55);
}
.nf-free-wall {
cursor: grab;
}
+3 -1
View File
@@ -2,6 +2,7 @@
// up/stop/down for blinds, on/off for switches, with a slider and a way to the full details.
import { css, html, LitElement, nothing } from "lit";
import { canControl } from "../access.ts";
import { assumedCover, type CarState, entityName, isUnavailable, kindOf } from "../devices.ts";
import { translate, type I18nKey } from "../i18n.ts";
import { openMoreInfo, stateText } from "../markers.ts";
@@ -73,6 +74,7 @@ export class NfQuickMenu extends LitElement {
}
private call(domain: string, service: string, data: Record<string, unknown> = {}): void {
if (!canControl(this.hass, this.entity)) return;
void this.hass.callService(domain, service, { entity_id: this.entity, ...data });
}
@@ -262,7 +264,7 @@ export class NfQuickMenu extends LitElement {
if (!st) return nothing;
const kind = kindOf(this.entity);
// a cover without feedback (a garage remote) stays unknown, but its buttons still work
const body = isUnavailable(st) && !assumedCover(st)
const body = !canControl(this.hass, this.entity) || (isUnavailable(st) && !assumedCover(st))
? html`<p class="qm-note">${stateText(this.hass, st)}</p>`
: kind === "light"
? this.renderLight(st)
+3 -1
View File
@@ -5,6 +5,7 @@ import { ROOM_HVAC_FIELDS } from "../entities/room-hvac.ts";
import { nativeBool, nativeNumber, nativeText, nativeValue } from "../entities/symcon-values.ts";
import { controls, tokens } from "../styles.ts";
import { trendButton } from "./trend-button.ts";
import { canControl } from "../access.ts";
interface SchedulePoint { hour: number; minute: number; second: number; action: number }
interface ScheduleGroup { id: number; days: number; points: SchedulePoint[] }
@@ -20,6 +21,7 @@ export class NfRoomHvac extends LitElement {
constructor() { super(); this._pending = new Set(); this._error = ""; }
private async send(id: string, domain: string, service: string, data: Record<string, unknown>) {
if (!canControl(this.hass, id)) return;
this._pending = new Set([...this._pending, id]);
this._error = "";
try { await this.hass.callService(domain, service, { entity_id: id, ...data }); }
@@ -47,7 +49,7 @@ export class NfRoomHvac extends LitElement {
const days = ["Mo", "Di", "Mi", "Do", "Fr", "Sa", "So"];
const time = (p: SchedulePoint) => `${String(p.hour).padStart(2, "0")}:${String(p.minute).padStart(2, "0")}${p.second ? `:${String(p.second).padStart(2, "0")}` : ""}`;
return html`<details class="schedule"><summary>${String(st.attributes.friendly_name ?? "Schaltuhr")}</summary>
<label class="nf-check"><input type="checkbox" .checked=${st.state === "on"} ?disabled=${this._pending.has(id)} @change=${(e: Event) => void this.send(id, "schedule", "set_active", { active: (e.target as HTMLInputElement).checked })} /> Aktiv</label>
<label class="nf-check"><input type="checkbox" .checked=${st.state === "on"} ?disabled=${this._pending.has(id) || !canControl(this.hass, id)} @change=${(e: Event) => void this.send(id, "schedule", "set_active", { active: (e.target as HTMLInputElement).checked })} /> Aktiv</label>
${next > 0 ? html`<p class="next">Nächster Schaltpunkt: ${new Date(next * 1000).toLocaleString(this.hass.language)}${nextAction ? ` · ${nextAction.name}` : ""}</p>` : nothing}
${groups.length ? groups.map((group) => html`<div class="schedule-group"><b>${days.filter((_, i) => group.days & (1 << i)).join(" · ")}</b><div class="points">
${[...group.points].sort((a, b) => a.hour * 3600 + a.minute * 60 + a.second - (b.hour * 3600 + b.minute * 60 + b.second)).map((point) => {
+27 -21
View File
@@ -2,6 +2,7 @@
// scenes and scripts). Shown next to the 3D view when a room is selected.
import { css, html, LitElement, nothing, svg, type TemplateResult } from "lit";
import { canControl } from "../access.ts";
import { assumedCover, entityName, groupByDevice, groupCovers, isActive, isUnavailable, kindOf, roomClimateSensors, roomClimateValue, roomPanelEntities, fromCelsius, tempUnit, type DeviceKind, roomEntities } from "../devices.ts";
import { formatNumber, translate, type I18nKey } from "../i18n.ts";
import { iconPath } from "../icons.ts";
@@ -239,7 +240,7 @@ export class NfRoomPanel extends LitElement {
if (!quietSince || minutes < EMPTY_MINUTES) return nothing;
return html`<div class="nf-rp-shade">
<span>💡 ${this.t("empty_lights_hint", { n: lightsOn.length, min: minutes })}</span>
<button class="nf-btn nf-rp-small" @click=${() => this.call("light", "turn_off", { entity_id: lightsOn.map((l) => l.entity_id) })}>${this.t("empty_lights_off")}</button>
<button class="nf-btn nf-rp-small" ?disabled=${!lightsOn.some((l) => canControl(this.hass, l.entity_id))} @click=${() => this.call("light", "turn_off", { entity_id: lightsOn.filter((l) => canControl(this.hass, l.entity_id)).map((l) => l.entity_id) })}>${this.t("empty_lights_off")}</button>
</div>`;
}
@@ -254,6 +255,7 @@ export class NfRoomPanel extends LitElement {
if (!open.length) return nothing;
const down = () => {
for (const c of heating) {
if (!canControl(this.hass, c.entity_id)) continue;
const modes = (c.attributes.hvac_modes as string[] | undefined) ?? [];
if (modes.includes("off")) this.call("climate", "set_hvac_mode", { entity_id: c.entity_id, hvac_mode: "off" });
else if (typeof c.attributes.min_temp === "number") this.call("climate", "set_temperature", { entity_id: c.entity_id, temperature: c.attributes.min_temp });
@@ -261,7 +263,7 @@ export class NfRoomPanel extends LitElement {
};
return html`<div class="nf-rp-shade nf-rp-open-heat">
<span>🪟 ${this.t("open_heating_hint", { n: open.length })}</span>
<button class="nf-btn nf-rp-small" @click=${down}>${this.t("open_heating_off")}</button>
<button class="nf-btn nf-rp-small" ?disabled=${!heating.some((c) => canControl(this.hass, c.entity_id))} @click=${down}>${this.t("open_heating_off")}</button>
</div>`;
}
@@ -281,7 +283,7 @@ export class NfRoomPanel extends LitElement {
const pos = st.attributes.current_position;
return typeof pos === "number" ? pos > 30 : st.state === "open";
};
const covers = [...new Set(sunnyWindowsNow(this.building, this.floor, room, { latitude, longitude }).flatMap((o) => [o.cover, o.cover2].filter(open)))];
const covers = [...new Set(sunnyWindowsNow(this.building, this.floor, room, { latitude, longitude }).flatMap((o) => [o.cover, o.cover2].filter(open)))].filter((id) => canControl(this.hass, id));
if (!covers.length) return nothing;
return html`<div class="nf-rp-shade">
<span>☀ ${this.t("shade_hint", { n: covers.length, temp: `${formatNumber(this.hass, fromCelsius(this.hass, temp), 1)} ${tempUnit(this.hass)}` })}</span>
@@ -366,6 +368,8 @@ export class NfRoomPanel extends LitElement {
}
private call(domain: string, service: string, data: Record<string, unknown>): void {
const ids = Array.isArray(data.entity_id) ? data.entity_id : [data.entity_id];
if (ids.some((id) => typeof id !== "string" || !canControl(this.hass, id))) return;
void this.hass.callService(domain, service, data);
}
@@ -373,7 +377,7 @@ export class NfRoomPanel extends LitElement {
private renderClean(room: Room) {
const id = room.clean_entity;
const st = id ? this.hass.states[id] : undefined;
if (!id || !st) return nothing;
if (!id || !st || !canControl(this.hass, id)) return nothing;
const domain = id.slice(0, id.indexOf("."));
const run = () => (domain === "script" ? this.call("script", "turn_on", { entity_id: id }) : this.call(domain, "press", { entity_id: id }));
return html`<div class="nf-rp-alloff"><button class="nf-btn nf-rp-small" ?disabled=${isUnavailable(st)} title=${this.t("room_clean_run_hint")} @click=${run}>🧹 ${this.t("room_clean_run")}</button></div>`;
@@ -381,7 +385,7 @@ export class NfRoomPanel extends LitElement {
/** Switches off what is on in the room and offers to undo it for ten seconds. */
private allOff(states: HassEntity[]): void {
const plan = allOffPlan(states);
const plan = allOffPlan(states.filter((st) => canControl(this.hass, st.entity_id)));
for (const c of plan.off) this.call(c.domain, c.service, c.data);
this._undo = plan.undo;
clearTimeout(this.undoTimer);
@@ -397,7 +401,7 @@ export class NfRoomPanel extends LitElement {
/** "Everything off" while something is on, and its undo right after. */
private renderAllOff(states: HassEntity[]): TemplateResult | typeof nothing {
if (this._undo) return html`<div class="nf-rp-alloff"><span>${this.t("all_off_done")}</span><button class="nf-btn nf-rp-small" @click=${() => this.undoAllOff()}>↶ ${this.t("all_off_undo")}</button></div>`;
const { count } = allOffPlan(states);
const { count } = allOffPlan(states.filter((st) => canControl(this.hass, st.entity_id)));
if (count < 2) return nothing;
return html`<div class="nf-rp-alloff"><button class="nf-btn nf-rp-small" title=${this.t("all_off_hint")} @click=${() => this.allOff(states)}>⏻ ${this.t("all_off_n", { n: count })}</button></div>`;
}
@@ -435,7 +439,7 @@ export class NfRoomPanel extends LitElement {
role="switch"
aria-checked=${on ? "true" : "false"}
aria-label=${this.name(st.entity_id)}
?disabled=${isUnavailable(st)}
?disabled=${isUnavailable(st) || !canControl(this.hass, st.entity_id)}
@click=${guarded}
></button>`;
}
@@ -470,7 +474,7 @@ export class NfRoomPanel extends LitElement {
const switches = by(["switch", "fan", "lock"]);
const sensors = by(["sensor", "binary"]);
const scenes = by(["scene", "script"]);
const facts = this.facts(climates);
const facts = room.symcon_read_room === false ? [] : this.facts(climates);
const lightsOn = lights.filter((l) => l.state === "on");
return html`<section class="nf-rp" aria-label=${room.name}>
<header class="nf-rp-head">
@@ -491,7 +495,9 @@ export class NfRoomPanel extends LitElement {
<nf-utility-report .hass=${this.hass} .readings=${roomUtilityReadings(this.hass, room, this.building?.floors.flatMap((f) => f.rooms))}></nf-utility-report>
${this.renderAllOff([...lights, ...media, ...switches])}
${this.renderClean(room)}
${!room.area_id && !outside && !(isSymcon(this.hass) && hvacRefs.length)
${room.symcon_read_room === false
? html`<p class="nf-rp-note">${this.t(ids.length ? "access_room_devices" : "access_room_geometry")}</p>`
: !room.area_id && !outside && !(isSymcon(this.hass) && hvacRefs.length)
? html`<p class="nf-rp-note">${this.t("panel_no_area")}</p>`
: !ids.length && !(isSymcon(this.hass) && hvacRefs.length)
? html`<p class="nf-rp-note">${this.t("panel_empty")}</p>`
@@ -517,13 +523,13 @@ export class NfRoomPanel extends LitElement {
${lights.length
? this.section(
"panel_lights",
[...lights.map((st) => this.lightRow(st)), ...(room ? [this.renderMoods(room, lights)] : [])],
html`${lightsOn.length < lights.length
? html`<button class="nf-btn nf-rp-small" @click=${() => this.call("light", "turn_on", { entity_id: lights.filter((l) => !isUnavailable(l)).map((l) => l.entity_id) })}>
[...lights.map((st) => canControl(this.hass, st.entity_id) ? this.lightRow(st) : this.sensorRow(st)), ...(room && lights.some((st) => canControl(this.hass, st.entity_id)) ? [this.renderMoods(room, lights)] : [])],
html`${lights.some((l) => l.state !== "on" && canControl(this.hass, l.entity_id))
? html`<button class="nf-btn nf-rp-small" ?disabled=${!lights.some((l) => canControl(this.hass, l.entity_id))} @click=${() => this.call("light", "turn_on", { entity_id: lights.filter((l) => !isUnavailable(l) && canControl(this.hass, l.entity_id)).map((l) => l.entity_id) })}>
${this.t("panel_all_on")}
</button>`
: nothing}${lightsOn.length
? html`<button class="nf-btn nf-rp-small" @click=${() => this.call("light", "turn_off", { entity_id: lightsOn.map((l) => l.entity_id) })}>
: nothing}${lightsOn.some((l) => canControl(this.hass, l.entity_id))
? html`<button class="nf-btn nf-rp-small" ?disabled=${!lightsOn.some((l) => canControl(this.hass, l.entity_id))} @click=${() => this.call("light", "turn_off", { entity_id: lightsOn.filter((l) => canControl(this.hass, l.entity_id)).map((l) => l.entity_id) })}>
${this.t("panel_all_off")}
</button>`
: nothing}`,
@@ -532,20 +538,20 @@ export class NfRoomPanel extends LitElement {
${covers.length
? this.section(
"panel_covers",
covers.map((st) => this.coverRow(st)),
covers.length > 1 && groupCovers(covers, this.confirmEntities).length
? html`<button class="nf-btn nf-rp-small" @click=${() => this.call("cover", "open_cover", { entity_id: groupCovers(covers, this.confirmEntities) })}>
covers.map((st) => canControl(this.hass, st.entity_id) ? this.coverRow(st) : this.sensorRow(st)),
covers.length > 1 && groupCovers(covers.filter((c) => canControl(this.hass, c.entity_id)), this.confirmEntities).length
? html`<button class="nf-btn nf-rp-small" @click=${() => this.call("cover", "open_cover", { entity_id: groupCovers(covers.filter((c) => canControl(this.hass, c.entity_id)), this.confirmEntities) })}>
${this.t("panel_all_open")}</button
><button class="nf-btn nf-rp-small" @click=${() => this.call("cover", "close_cover", { entity_id: groupCovers(covers, this.confirmEntities) })}>
><button class="nf-btn nf-rp-small" @click=${() => this.call("cover", "close_cover", { entity_id: groupCovers(covers.filter((c) => canControl(this.hass, c.entity_id)), this.confirmEntities) })}>
${this.t("panel_all_close")}
</button>`
: nothing,
)
: nothing}
${isSymcon(this.hass) ? html`<nf-room-hvac .hass=${this.hass} .room=${room}></nf-room-hvac>` : nothing}
${climates.length ? this.section("panel_climate", climates.map((st) => this.climateRow(st))) : nothing}
${media.length ? this.section("panel_media", media.map((st) => this.mediaRow(st))) : nothing}
${switches.length ? this.section("panel_switches", switches.map((st) => this.switchRow(st))) : nothing}
${climates.length ? this.section("panel_climate", climates.map((st) => canControl(this.hass, st.entity_id) ? this.climateRow(st) : this.sensorRow(st))) : nothing}
${media.length ? this.section("panel_media", media.map((st) => canControl(this.hass, st.entity_id) ? this.mediaRow(st) : this.sensorRow(st))) : nothing}
${switches.length ? this.section("panel_switches", switches.map((st) => canControl(this.hass, st.entity_id) ? this.switchRow(st) : this.sensorRow(st))) : nothing}
${sensors.length ? this.section("panel_sensors", sensors.map((st) => this.sensorRow(st))) : nothing}
${this.extraValues(room)}
${!isSymcon(this.hass) && canAnnounce(this.hass) && roomHasSpeaker(this.hass, this.floor, room) ? this.announceSection(room) : nothing}
+13 -6
View File
@@ -1,6 +1,7 @@
// Lit wrapper around the lazily loaded 3D viewer.
import { changeMoments, hassAt, loadHistory, replayable, type History } from "../live/time-travel.ts";
import { canControl } from "../access.ts";
import { sunPosition, todayAt } from "../sun-position.ts";
import { dayCurves, statesRead, type DayCurves } from "../live/day-curves.ts";
import { backdropStyle } from "../backdrop.ts";
@@ -1070,7 +1071,7 @@ export class NfView3d extends LitElement {
private jumpTo(a: Alert): void {
// an own warning: its details, or what was chosen for it (switch the entity, go to its room)
if (a.kind === "own" && a.tap !== "room") {
if (a.tap === "toggle") void this.hass.callService("homeassistant", "toggle", { entity_id: a.entity });
if (a.tap === "toggle" && canControl(this.hass, a.entity)) void this.hass.callService("homeassistant", "toggle", { entity_id: a.entity });
else openMoreInfo(this, a.entity);
return;
}
@@ -1091,7 +1092,7 @@ export class NfView3d extends LitElement {
const room = floor?.rooms.find((r) => r.id === roomId);
if (!b || !hass || !floor || !room) return;
const mode = roomToggleMode(b.settings.room_double_tap, this.roomDoubleTap);
const lights = roomToggleLights(hass, floor, room, this.furnitureLinks, this.confirmSet, mode);
const lights = roomToggleLights(hass, floor, room, this.furnitureLinks, this.confirmSet, mode).filter((id) => canControl(hass, id));
if (!lights.length) return;
const anyOn = lights.some((id) => hass.states[id]?.state === "on");
void hass.callService("homeassistant", anyOn ? "turn_off" : "turn_on", { entity_id: lights });
@@ -1104,6 +1105,7 @@ export class NfView3d extends LitElement {
}
private runScene(id: string): void {
if (!canControl(this.hass, id)) return;
void this.hass.callService(id.split(".")[0], "turn_on", { entity_id: id });
this._sceneFired = id;
setTimeout(() => (this._sceneFired = null), 600);
@@ -1802,7 +1804,7 @@ export class NfView3d extends LitElement {
const st = this.hass?.states[entityId];
if (phase === "start") {
// devices that ask before switching are not moved by a swipe (it turns the view instead)
if (!st || isUnavailable(st) || this.confirmSet.has(entityId)) return false;
if (!st || isUnavailable(st) || !canControl(this.hass, entityId) || this.confirmSet.has(entityId)) return false;
const kind = kindOf(entityId);
if (kind === "light" && lightAbilities(st).dim) {
const pct = st.state === "on" ? (typeof st.attributes.brightness === "number" ? Math.round((st.attributes.brightness as number) / 2.55) : 100) : 0;
@@ -1843,6 +1845,7 @@ export class NfView3d extends LitElement {
}
private applySwipe(): void {
if (this._swipe && !canControl(this.hass, this._swipe.entity)) return;
const s = this._swipe;
if (!s || !this.hass) return;
if (s.kind === "light") {
@@ -2002,8 +2005,8 @@ export class NfView3d extends LitElement {
if (!this._central) return star;
const floor = this.floorId ? b.floors.find((f) => f.id === this.floorId) : undefined;
const floors = floor ? [floor] : b.floors;
const lights = floors.flatMap((f) => floorControls(hass, f).lights);
const covers = floors.flatMap((f) => floorControls(hass, f).covers);
const lights = floors.flatMap((f) => floorControls(hass, f).lights).filter((id) => canControl(hass, id));
const covers = floors.flatMap((f) => floorControls(hass, f).covers).filter((id) => canControl(hass, id));
const lightsOn = lights.filter((id) => hass.states[id]?.state === "on").length;
const house = !floor;
// house-wide: the first tap arms the button ("sure?"), the second runs it
@@ -2050,7 +2053,7 @@ export class NfView3d extends LitElement {
return html`<button
class="nf-chip"
aria-pressed=${on || this._sceneFired === id}
?disabled=${isUnavailable(st)}
?disabled=${isUnavailable(st) || !canControl(hass, id)}
@click=${() => {
void hass.callService(domain, service, { entity_id: id });
this._sceneFired = id;
@@ -2357,6 +2360,10 @@ export class NfView3d extends LitElement {
return;
}
const kind = kindOf(entityId);
if (this.hass.symconObjects !== undefined && !canControl(this.hass, entityId)) {
if (this.hass.states[entityId]) this._menu = { entity: entityId, x, y };
return;
}
// blinds have no single on/off: a tap opens their quick menu (up, positions, stop, down); speakers and TVs open theirs
// (play, skip, volume, sources and the stations set for them)
if (kind === "cover" || kind === "media") {
+10
View File
@@ -1134,6 +1134,11 @@ const DE = {
out_path: "Weg",
out_driveway: "Einfahrt",
out_street: "Straße",
out_pavers: "Pflastersteine",
access_room_devices: "Hier sind nur die einzeln freigegebenen Geräte sichtbar.",
access_room_geometry: "Für diesen Raum sind keine Zustände freigegeben.",
out_stepping_stones: "Trittplatten",
out_natural_stone: "Natursteinweg",
outdoor_texture_scale: "Texturmaßstab (%)",
outdoor_texture_rotation: "Texturdrehung (°)",
outdoor_texture_hint: "100 % ist die Originalgröße. 200 % macht das Muster doppelt so groß, 50 % halb so groß (5–2000 %). Die Drehung verändert nur die Textur dieser Fläche. Standard: 100 % und 0°.",
@@ -3207,6 +3212,11 @@ const EN: Record<Key, string> = {
out_path: "Path",
out_driveway: "Driveway",
out_street: "Street",
out_pavers: "Paving stones",
access_room_devices: "Only individually authorized devices are visible here.",
access_room_geometry: "No live data is shared for this room.",
out_stepping_stones: "Stepping stones",
out_natural_stone: "Natural stone path",
outdoor_texture_scale: "Texture scale (%)",
outdoor_texture_rotation: "Texture rotation (°)",
outdoor_texture_hint: "100% is the original size. 200% doubles the pattern size, 50% halves it (5–2000%). Rotation changes only this area's texture. Defaults: 100% and 0°.",
+6 -1
View File
@@ -49,6 +49,8 @@ export type WeatherVariableKey = typeof WEATHER_VARIABLE_KEYS[number];
export type WallHeight = number | null | (number | null)[];
export interface Room {
/** Viewer-only Symcon access metadata; absent in the admin's stored project. */
symcon_read_room?: boolean;
/** Room temperature, humidity and CO2: chosen sensors instead of the automatic pick. */
climate?: RoomClimate | null;
/** Show temperature, humidity and CO2 in a floating glass card over this room. */
@@ -909,7 +911,7 @@ export type WeatherEffect = (typeof WEATHER_EFFECTS)[number];
/** The effects shown when the plan does not say: everything but fog (fog greys the whole scene). */
export const DEFAULT_WEATHER_EFFECTS: WeatherEffect[] = ["rain", "snow", "clouds", "lightning", "sky"];
export const OUTDOOR_TYPES = ["lawn", "terrace", "path", "driveway", "street", "sidewalk", "gravel", "river", "stream", "pool", "bed", "wild", "hedge", "fence", "pergola"] as const;
export const OUTDOOR_TYPES = ["lawn", "terrace", "path", "driveway", "pavers", "stepping_stones", "natural_stone", "street", "sidewalk", "gravel", "river", "stream", "pool", "bed", "wild", "hedge", "fence", "pergola"] as const;
export type OutdoorType = (typeof OUTDOOR_TYPES)[number];
/** Top of each kind of outdoor area above ground level (pool: its water, below). */
@@ -918,6 +920,9 @@ export const OUTDOOR_TOP: Record<OutdoorType, number> = {
terrace: 0.12,
path: 0.02,
driveway: 0.02,
pavers: 0.025,
stepping_stones: 0.025,
natural_stone: 0.03,
street: 0.02,
sidewalk: 0.12,
gravel: 0.018,
+1
View File
@@ -174,6 +174,7 @@ export class NextFloorPanel extends LitElement {
}
private setMode(mode: Mode): void {
if (mode !== "view" && !this.isAdmin) return;
if (mode === this._mode) return;
if (mode === "view") void this.data.flush();
this._mode = mode;
+15 -1
View File
@@ -1,12 +1,26 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { callSymcon } from "./symcon-api.ts";
import { callSymcon, SymconAuthError } from "./symcon-api.ts";
import { SymconBridge } from "./symcon-bridge.ts";
const settings = { endpoint: "/hook/fixture", token: "test-only" };
const CHUNK_BYTES = 128 * 1024;
const id = "0123456789abcdef0123456789abcdef";
test("authenticated calls use cookie credentials and a CSRF header, with no credential in the URL", async (context) => {
context.mock.method(globalThis, "fetch", async (url: string, init: RequestInit) => {
assert.equal(url, "/hook/fixture/api"); assert.equal(init.credentials, "same-origin");
assert.equal((init.headers as Record<string, string>)["X-NextFloor-CSRF"], "csrf-fixture");
return new Response("{\"revision\":1}");
});
assert.deepEqual(await callSymcon({ endpoint: "/hook/fixture", csrf: "csrf-fixture" }, "building/get"), { revision: 1 });
});
test("an expired session is distinguished from a forbidden operation", async (context) => {
context.mock.method(globalThis, "fetch", async () => new Response('{"error":"authentication_required"}', { status: 401 }));
await assert.rejects(callSymcon({ endpoint: "/hook/fixture", csrf: "csrf-fixture" }, "bootstrap"), SymconAuthError);
});
test("small replies remain compatible and transport negotiation is explicit", async (context) => {
context.mock.method(globalThis, "fetch", async (_url: string, init: RequestInit) => {
const request = JSON.parse(String(init.body));
+8 -3
View File
@@ -1,9 +1,13 @@
// Bounded WebHook responses: Symcon's default PHP output limit is 1 MiB per request.
export interface SymconEndpoint {
endpoint: string;
token: string;
/** Legacy fixture/old-client support; current hosts authenticate with an HttpOnly cookie. */
token?: string;
csrf?: string;
}
export class SymconAuthError extends Error {}
interface Transfer {
id: string;
bytes: number;
@@ -15,13 +19,14 @@ const TRANSPORT = "nextfloor-chunks-v1";
const MAX_TRANSFER_BYTES = 64 * 1024 * 1024;
async function request(settings: SymconEndpoint, action: string, payload: Record<string, unknown>): Promise<Record<string, unknown>> {
const response = await fetch(`${settings.endpoint}/api?token=${encodeURIComponent(settings.token)}`, {
const response = await fetch(`${settings.endpoint}/api${settings.csrf ? "" : settings.token ? `?token=${encodeURIComponent(settings.token)}` : ""}`, {
method: "POST",
headers: { "Content-Type": "application/json", Accept: "application/json" },
headers: { "Content-Type": "application/json", Accept: "application/json", ...(settings.csrf ? { "X-NextFloor-CSRF": settings.csrf } : {}) },
credentials: "same-origin",
body: JSON.stringify({ ...payload, action, transport: TRANSPORT }),
});
const raw = await response.text();
if (response.status === 401) throw new SymconAuthError("Die Anmeldung ist abgelaufen. Bitte erneut anmelden.");
let body: unknown;
try {
body = JSON.parse(raw);
+18
View File
@@ -20,6 +20,24 @@ test("configured view names are exposed to the header with a safe empty-name fal
assert.equal(new SymconBridge().snapshot().symconTitle, "NextFloor");
});
test("server roles control editor access and read-only role aliases cannot send commands", async (context) => {
mockWindow(context);
let commands = 0;
context.mock.method(globalThis, "fetch", async (_url: string, init: RequestInit) => {
const request = JSON.parse(String(init.body));
if (request.action === "variables/action") { commands++; return new Response("{}"); }
return new Response(JSON.stringify({ access: { id: "reader", name: "Leser", is_admin: false }, state_revision: 1, building_revision: 1, areas: [], objects: [],
variables: [{ entity_id: "sensor.10", name: "Wert", state: "30", path: "Büro / Wert", attributes: { symcon_id: 10, symcon_variable_type: 2, symcon_numeric_value: 30, symcon_can_control: false } }] }));
});
const bridge = new SymconBridge();
try {
const h = await bridge.start();
assert.equal(h.user?.is_admin, false); assert.equal(h.user?.name, "Leser");
await assert.rejects(h.callService("light", "turn_on", { entity_id: "light.10" }), /nur die Anzeige/);
assert.equal(commands, 0);
} finally { bridge.stop(); }
});
test("numeric control roles stay selectable in the real tree without duplicating automatic device lists", async (context) => {
mockWindow(context);
context.mock.method(globalThis, "fetch", async () => new Response(JSON.stringify({ state_revision: 1, building_revision: 1, areas: [{ area_id: "room", name: "Raum" }],
+15 -6
View File
@@ -5,12 +5,14 @@
// only ever shows and selects their object-tree path. The numeric object id stays an implementation detail.
import type { HassArea, HassEntity, HassEntityEntry, HomeAssistant, SymconObject } from "./types.ts";
import { callSymcon as call } from "./symcon-api.ts";
import { callSymcon as call, SymconAuthError } from "./symcon-api.ts";
import { symconControl } from "./symcon-controls.ts";
interface SymconConfig {
endpoint: string;
token: string;
token?: string;
csrf?: string;
user?: { id: string; name: string; is_admin: boolean; view_all?: boolean; control_all?: boolean; can_control?: boolean };
language?: string;
title?: string;
}
@@ -26,6 +28,7 @@ interface SymconVariable {
}
interface Bootstrap {
access?: { id: string; name: string; is_admin: boolean };
state_revision: number;
building_revision: number;
variables: SymconVariable[];
@@ -52,7 +55,7 @@ declare global {
function config(): SymconConfig {
const settings = window.__NEXTFLOOR_SYMCON__;
if (!settings?.endpoint || !settings.token) throw new Error("NextFloor Symcon host configuration is missing");
if (!settings?.endpoint || (!settings.csrf && !settings.token)) throw new Error("NextFloor Symcon host configuration is missing");
return settings;
}
@@ -62,6 +65,7 @@ function config(): SymconConfig {
* unauthenticated JSON-RPC port to the browser. The module returns only variables from the object tree.
*/
export class SymconBridge {
onExpired?: () => void;
private readonly settings = config();
private readonly changeListeners = new Set<Listener>();
private readonly buildingListeners = new Set<BuildingListener>();
@@ -76,7 +80,7 @@ export class SymconBridge {
private readonly facade: HomeAssistant = {
language: this.settings.language || navigator.language || "de",
user: { is_admin: true, name: this.settings.title || "IP-Symcon" },
user: this.settings.user ?? { is_admin: false, name: "IP-Symcon" },
states: this.states,
entities: this.entities,
areas: this.areas,
@@ -106,10 +110,13 @@ export class SymconBridge {
/** Read the initial object tree and begin refreshing changed values. */
async start(): Promise<HomeAssistant> {
const initial = await call<Bootstrap>(this.settings, "bootstrap");
if (initial.access) this.facade.user = initial.access;
this.apply(initial);
this.stateRevision = initial.state_revision;
this.buildingRevision = initial.building_revision;
this.timer = setInterval(() => void this.refresh().catch(() => undefined), 800);
this.timer = setInterval(() => void this.refresh().catch((error) => {
if (error instanceof SymconAuthError) { this.stop(); this.states = {}; this.entities = {}; this.onExpired?.(); }
}), 800);
return this.snapshot();
}
@@ -204,13 +211,15 @@ export class SymconBridge {
}
private async callService(domain: string, service: string, data: Record<string, unknown> = {}): Promise<unknown> {
const ids = Array.isArray(data.entity_id) ? data.entity_id : [data.entity_id];
if (ids.some((id) => typeof id !== "string" || this.states[id]?.attributes.symcon_can_control === false)) throw new Error("Für dieses Gerät ist nur die Anzeige freigegeben.");
return call(this.settings, "variables/action", { domain, service, data });
}
/** Mesh uploads are intentionally not exposed until the Symcon asset store exists. Other paths stay same-origin. */
private fetchWithToken(path: string, init: Record<string, unknown> = {}): Promise<Response> {
const url = new URL(path, window.location.origin);
url.searchParams.set("token", this.settings.token);
if (!this.settings.csrf && this.settings.token) url.searchParams.set("token", this.settings.token);
return fetch(url, { ...init, credentials: "same-origin" });
}
}
+18 -3
View File
@@ -4,6 +4,7 @@
import "./main.ts";
import { SymconBridge } from "./symcon-bridge.ts";
import type { HomeAssistant } from "./types.ts";
import { SymconAuthError } from "./symcon-api.ts";
type SymconPanel = HTMLElement & { hass: HomeAssistant; narrow: boolean };
type SymconCard = HTMLElement & { hass: HomeAssistant; setConfig(config: Record<string, unknown>): void };
@@ -13,7 +14,11 @@ function pageMode(): "designer" | "tile" {
}
async function mount(): Promise<void> {
// Old admin drafts must not survive a switch to a more restricted account in the same browser.
try { localStorage.removeItem("nextfloor.unsaved"); } catch { /* storage may be disabled */ }
const bridge = new SymconBridge();
const settings = window.__NEXTFLOOR_SYMCON__!;
bridge.onExpired = () => { document.body.replaceChildren(); window.location.replace(`${settings.endpoint}/login?mode=${pageMode()}`); };
const hass = await bridge.start();
const tile = pageMode() === "tile";
const app = (tile ? document.createElement("nextfloor-card") : document.createElement("nextfloor-panel")) as SymconCard & SymconPanel;
@@ -22,15 +27,25 @@ async function mount(): Promise<void> {
if (tile) {
(app as SymconCard).setConfig({ type: "custom:nextfloor-card", fill: true, room_buttons: true, controls: true, weather: false, announcements: false });
} else {
(app as SymconPanel).narrow = false;
(app as SymconPanel).narrow = window.innerWidth < 870;
}
document.body.replaceChildren(app);
const resize = () => { if (!tile) (app as SymconPanel).narrow = window.innerWidth < 870; };
window.addEventListener("resize", resize);
const bar = document.createElement("nav"); bar.className = "nf-session-bar"; bar.setAttribute("aria-label", "Benutzerkonto");
const identity = document.createElement("span"); identity.textContent = `${hass.user?.name ?? ""} · ${hass.user?.is_admin ? "Administrator" : settings.user?.can_control === false ? "Nur ansehen" : settings.user?.control_all ? "Bedienung" : settings.user?.view_all ? "Ansicht und freigegebene Bedienung" : "Freigegebene Räume / Geräte"}`;
const form = document.createElement("form"); form.method = "post"; form.action = `${settings.endpoint}/logout?mode=${pageMode()}`;
const csrf = document.createElement("input"); csrf.type = "hidden"; csrf.name = "csrf"; csrf.value = settings.csrf || "";
const logout = document.createElement("button"); logout.type = "submit"; logout.textContent = "Abmelden";
form.append(csrf, logout); bar.append(identity, form);
document.body.replaceChildren(bar, app);
bridge.onChange(() => {
app.hass = bridge.snapshot();
});
window.addEventListener("pagehide", () => bridge.stop(), { once: true });
window.addEventListener("pagehide", () => { bridge.stop(); window.removeEventListener("resize", resize); document.body.replaceChildren(); }, { once: true });
window.addEventListener("pageshow", (event) => { if (event.persisted) location.reload(); });
}
void mount().catch((error: unknown) => {
if (error instanceof SymconAuthError) { window.location.replace(`${window.__NEXTFLOOR_SYMCON__!.endpoint}/login?mode=${pageMode()}`); return; }
document.body.textContent = `NextFloor konnte nicht geladen werden: ${error instanceof Error ? error.message : String(error)}`;
});
+3
View File
@@ -15,6 +15,9 @@ export const LOOKS: Record<OutdoorType, Look> = {
terrace: { color: 0x1c1b30, side: 0x161628, edge: 0x5b7cff, edgeAlpha: 0.32 },
path: { color: 0x1b2234, side: 0x151b29, edge: 0x5b7cff, edgeAlpha: 0.22 },
driveway: { color: 0x171d2c, side: 0x121725, edge: 0x5b7cff, edgeAlpha: 0.18 },
pavers: { color: 0x48453f, side: 0x292720, edge: 0xa59d88, edgeAlpha: 0.25 },
stepping_stones: { color: 0x55574b, side: 0x292f22, edge: 0x9eaf83, edgeAlpha: 0.22 },
natural_stone: { color: 0x514a3d, side: 0x29261f, edge: 0xb1a38a, edgeAlpha: 0.25 },
street: { color: 0x24272d, side: 0x15181e, edge: 0x9aa4b2, edgeAlpha: 0.25 },
sidewalk: { color: 0x48505b, side: 0x29313b, edge: 0xaebbc9, edgeAlpha: 0.28 },
gravel: { color: 0x514b3e, side: 0x2a2822, edge: 0xb8a882, edgeAlpha: 0.26 },
+26 -2
View File
@@ -5,6 +5,7 @@ import type { OutdoorType } from "../../model.ts";
export const OUTDOOR_MATERIAL: Record<OutdoorType, number> = {
lawn: 1, terrace: 2, path: 3, driveway: 4, pool: 5, bed: 6, wild: 7,
hedge: 8, fence: 9, pergola: 9, street: 10, sidewalk: 11, gravel: 12, river: 13, stream: 14,
pavers: 15, stepping_stones: 16, natural_stone: 17,
};
const TEXTURE = /* glsl */ `
@@ -29,10 +30,11 @@ float nfJoint(float v, float width) {
}
// Keep the material recognizable in the day look: its general theme otherwise maps dark asphalt to near-white.
vec3 nfOutdoorDay(float kind) {
if (kind > 14.5) return kind < 15.5 ? vec3(0.30, 0.28, 0.25) : kind < 16.5 ? vec3(0.38, 0.38, 0.32) : vec3(0.34, 0.30, 0.24);
if (kind < 1.5 || (kind > 6.5 && kind < 8.5)) return kind > 7.5 ? vec3(0.055, 0.17, 0.07) : vec3(0.12, 0.28, 0.08);
if (kind < 2.5) return vec3(0.38, 0.32, 0.25);
if (kind < 4.5) return kind < 3.5 ? vec3(0.36, 0.34, 0.30) : vec3(0.23, 0.25, 0.27);
if ((kind > 4.5 && kind < 5.5) || kind > 12.5) return vec3(0.035, 0.22, 0.28);
if ((kind > 4.5 && kind < 5.5) || (kind > 12.5 && kind < 14.5)) return vec3(0.035, 0.22, 0.28);
if (kind < 6.5) return vec3(0.15, 0.09, 0.045);
if (kind < 9.5) return vec3(0.27, 0.15, 0.065);
if (kind < 10.5) return vec3(0.07, 0.075, 0.085);
@@ -65,6 +67,28 @@ vec3 nfOutdoorTexture(vec3 position, float kind) {
float c = cos(angle), s = sin(angle);
p = vec2(c * p.x + s * p.y, -s * p.x + c * p.y) / max(vNfSurfaceTransform.x, 0.05);
float broad = nfNoise(p * 1.7);
if (kind > 16.5) return nfPebbles(p * 2.3, false);
if (kind > 15.5) {
// Separate garden slabs with generous green gaps; texture scale changes slab size and spacing together.
vec2 cell = p / 0.85;
cell.x += mod(floor(cell.y), 2.0) * 0.12;
vec2 f = fract(cell), aa = max(fwidth(cell), vec2(0.001));
vec2 lo = smoothstep(vec2(0.12), vec2(0.12) + aa, f);
vec2 hi = 1.0 - smoothstep(vec2(0.88) - aa, vec2(0.88), f);
float slab = lo.x * lo.y * hi.x * hi.y;
vec3 stone = vec3(0.85 + nfGrain(floor(cell)) * 0.24) * (0.9 + nfNoise(p * 32.0) * 0.18);
vec3 grass = vec3(0.23, 0.62, 0.18) * (0.8 + broad * 0.4);
return mix(grass, stone, slab);
}
if (kind > 14.5) {
vec2 cell = p / vec2(0.2, 0.16);
cell.x += mod(floor(cell.y), 2.0) * 0.5;
float wobble = (nfNoise(p * 14.0) - 0.5) * 0.08;
float seam = max(nfJoint(cell.x + wobble, 0.03), nfJoint(cell.y + wobble, 0.03));
float bevel = max(nfJoint(cell.x + wobble, 0.1), nfJoint(cell.y + wobble, 0.1));
float variation = 0.7 + nfGrain(floor(cell)) * 0.55;
return vec3(mix(variation * (1.0 - bevel * 0.18), 0.28, seam * nfDetail(cell)));
}
if (kind < 1.5 || (kind > 6.5 && kind < 8.5)) {
if (kind > 7.5) return nfPebbles(p * 14.0, true);
float blades = nfNoise(p * vec2(65, 24));
@@ -81,7 +105,7 @@ vec3 nfOutdoorTexture(vec3 position, float kind) {
float grain = mix(1.0, 0.88 + nfNoise(p * 80.0) * 0.24, nfDetail(p * 80.0));
return vec3(mix(variation, 0.35, joint * nfDetail(tile)) * grain);
}
if ((kind > 4.5 && kind < 5.5) || kind > 12.5) {
if ((kind > 4.5 && kind < 5.5) || (kind > 12.5 && kind < 14.5)) {
// Water: broad ripples and smaller crossing highlights, with a tighter scale in streams.
vec2 water = p * (kind > 13.5 ? 1.8 : 1.0);
float wave = sin(water.x * 8.0 + sin(water.y * 3.0) + broad * 3.0);