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

+2 -1
View File
@@ -116,7 +116,8 @@ function copySymconAssets() {
// Metered-device detail discovery adds about 2 KB; keep a small, explicit margin.
// Charging telemetry, native time/duration formatting and labels add another 5 KB.
// Zoom detail levels and bounded device-card layouts add about 1.5 KB.
const BUDGET = { "nextfloor.js": 682 * 1024, "nextfloor-3d.js": 1000 * 1024, "nextfloor-editor.js": 720 * 1024, "nextfloor-card-editor.js": 240 * 1024, "nextfloor-trend.js": 100 * 1024, "nextfloor-hydronics.js": 100 * 1024 };
// Native per-device read-only presentation and account guards add about 2 KB.
const BUDGET = { "nextfloor.js": 686 * 1024, "nextfloor-3d.js": 1000 * 1024, "nextfloor-editor.js": 720 * 1024, "nextfloor-card-editor.js": 240 * 1024, "nextfloor-trend.js": 100 * 1024, "nextfloor-hydronics.js": 100 * 1024 };
copyAssets();
copySymconAssets();
+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);
+177
View File
@@ -0,0 +1,177 @@
// Real PHP WebHook, cookies and hostile API requests; then actual password login and viewer/editor UIs.
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { createServer } from "node:net";
import { mkdtempSync, mkdirSync, existsSync, readFileSync, rmSync, rmdirSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { createHash } from "node:crypto";
import puppeteer from "puppeteer-core";
const root = resolve(import.meta.dirname, ".."), out = join(root, "preview/screenshots"); mkdirSync(out, { recursive: true });
const dir = mkdtempSync(join(tmpdir(), "nextfloor-auth-")), stateFile = join(dir, "state.json");
const portProbe = createServer(); await new Promise((done) => portProbe.listen(0, "127.0.0.1", done));
const port = portProbe.address().port; await new Promise((done) => portProbe.close(done));
const base = `http://127.0.0.1:${port}`, hook = "/hook/nextfloor/12345";
const php = spawn(process.env.PHP_PATH || "C:/xampp/php/php.exe", ["-S", `127.0.0.1:${port}`, join(root, "symcon/tests/auth-router.php")], {
cwd: root, windowsHide: true, env: { ...process.env, NEXTFLOOR_TEST_STATE: stateFile }, stdio: ["ignore", "pipe", "pipe"],
});
let logs = "", browser; php.stdout.on("data", (data) => logs += data); php.stderr.on("data", (data) => logs += data);
const delay = (ms) => new Promise((done) => setTimeout(done, ms));
class Client {
cookies = new Map(); csrf = ""; setCookies = [];
async request(path, init = {}) {
const response = await fetch(base + path, { ...init, redirect: "manual", headers: { ...init.headers, Cookie: [...this.cookies].map(([k, v]) => `${k}=${v}`).join("; ") } });
this.setCookies = response.headers.getSetCookie();
for (const cookie of this.setCookies) { const [pair] = cookie.split(";"), at = pair.indexOf("="); this.cookies.set(pair.slice(0, at), pair.slice(at + 1)); }
return response;
}
async login(name, password = `${name}-test-password`, remember = false) {
const page = await this.request(hook + "/login"), text = await page.text();
const nonce = /name="csrf" value="([a-f0-9]+)"/.exec(text)?.[1]; assert.ok(nonce, text.slice(0, 250));
const result = await this.request(hook + "/login", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", Origin: base }, body: new URLSearchParams({ username: name, password, csrf: nonce, ...(remember ? { remember: "1" } : {}) }) });
if (result.status === 303) {
assert.ok(this.setCookies.some((c) => /^NFSC_Session_/.test(c) && /HttpOnly/i.test(c) && /SameSite=Strict/i.test(c)), "session cookie protection");
const html = await (await this.request(hook + "/designer")).text();
const config = JSON.parse(/window\.__NEXTFLOOR_SYMCON__=(.*?);<\/script>/s.exec(html)?.[1] ?? "null");
assert.ok(config?.csrf); assert.equal(config.token, undefined); this.csrf = config.csrf;
}
return result;
}
api(action, payload = {}, extraHeaders = {}) {
return this.request(hook + "/api", { method: "POST", headers: { "Content-Type": "application/json", "X-NextFloor-CSRF": this.csrf, Origin: base, ...extraHeaders }, body: JSON.stringify({ ...payload, action, transport: "nextfloor-chunks-v1" }) });
}
async json(action, payload = {}) {
const response = await this.api(action, payload), text = await response.text();
assert.equal(response.status, 200, text); return JSON.parse(text);
}
}
try {
let ready = false;
for (let i = 0; i < 100; i++) { try { ready = (await fetch(base + "/__test/state")).ok; } catch {} if (ready) break; await delay(100); }
assert.ok(ready, logs.slice(-2000));
const anonymous = new Client();
assert.equal((await anonymous.request(hook + "/")).status, 303);
assert.equal((await anonymous.api("bootstrap")).status, 401);
assert.equal((await anonymous.request(hook + "/assets/nextfloor-designer.js")).status, 401);
assert.equal((await anonymous.request(hook + "/api?token=old-reusable-token", { method: "POST", body: '{"action":"bootstrap"}' })).status, 401);
const reader = new Client(); assert.equal((await reader.login("reader", undefined, true)).status, 303);
let response = await reader.api("bootstrap"); const boot = await response.json();
assert.equal(boot.access.is_admin, false); assert.equal(boot.access.name, "reader");
assert.equal(boot.variables.length, 9); assert.ok(boot.variables.every((v) => v.attributes.symcon_can_control === false));
assert.ok(!boot.variables.some((v) => v.attributes.symcon_id === 888), "all-view permission excludes unrelated Symcon secrets");
const attributes = JSON.parse(readFileSync(stateFile, "utf8")).attributes;
const rawCookie = reader.cookies.get("NFSC_Session_12345");
assert.ok(JSON.parse(attributes.Sessions)[createHash("sha256").update(rawCookie).digest("hex")]);
assert.ok(!JSON.stringify(attributes).includes(rawCookie)); assert.ok(!JSON.stringify(attributes).includes("reader-test-password"));
assert.ok(Object.values(JSON.parse(attributes.Sessions)).some((s) => s.expires > Date.now() / 1000 + 25 * 86400), "remembered sessions survive browser restarts");
for (const action of ["building/save", "history/get", "backup/export", "packs/import", "image/set"]) assert.equal((await reader.api(action, { building: {} })).status, 403, action);
assert.equal((await reader.api("variables/action", { domain: "light", service: "toggle", data: { entity_id: "light.101" } })).status, 403);
assert.equal((await reader.api("bootstrap", {}, { "X-NextFloor-CSRF": "wrong" })).status, 403);
assert.equal((await reader.api("bootstrap", {}, { Origin: "http://attacker.invalid" })).status, 403);
assert.equal((await reader.request(hook + "/assets/nextfloor-editor.js")).status, 403);
const csrfOnly = new Client(); csrfOnly.csrf = reader.csrf; assert.equal((await csrfOnly.api("bootstrap")).status, 401);
const office = new Client(); assert.equal((await office.login("office")).status, 303);
const restricted = await office.json("bootstrap");
assert.deepEqual(restricted.variables.map((v) => v.attributes.symcon_id).sort((a, b) => a - b), [101, 102, 103, 104, 105]);
const plan = (await office.json("building/get")).building;
assert.equal(plan.floors[0].rooms.length, 2); assert.equal(plan.floors[0].rooms[1].climate.temperature, "none");
assert.equal(plan.floors[0].placements[1].entity_id, "none");
const now = Math.floor(Date.now() / 1000);
assert.equal((await office.api("archive/trend", { entity_id: "sensor.204", start: now - 3600, end: now })).status, 403);
assert.equal((await office.api("archive/trend", { entity_id: "sensor.104", start: now - 3600, end: now })).status, 200);
const before = (await (await fetch(base + "/__test/state")).json()).writes.length;
assert.equal((await office.api("variables/action", { domain: "light", service: "turn_off", data: { entity_id: ["light.101", "light.201"] } })).status, 403);
assert.equal((await (await fetch(base + "/__test/state")).json()).writes.length, before, "no partial writes from mixed bulk targets");
assert.equal((await office.api("variables/action", { domain: "cover", service: "close_cover", data: { entity_id: "cover.201" } })).status, 403);
assert.equal((await office.api("variables/action", { domain: "light", service: "turn_off", data: { entity_id: "light.101" } })).status, 200);
assert.equal((await office.api("variables/action", { domain: "schedule", service: "set_active", data: { entity_id: "schedule.105", active: false } })).status, 200);
const device = new Client(); assert.equal((await device.login("device")).status, 303);
assert.deepEqual((await device.json("bootstrap")).variables.map((v) => v.attributes.symcon_id).sort(), [102, 103]);
assert.equal((await device.api("variables/action", { domain: "light", service: "turn_on", data: { entity_id: "light.101" } })).status, 403);
assert.equal((await device.api("image/get", { image_id: "unreferenced-secret" })).status, 403);
// Native console recovery does not depend on knowing any NextFloor password.
const consoleClient = new Client(), consoleURL = (await (await fetch(base + "/__test/console")).json()).url;
assert.equal((await consoleClient.request(consoleURL)).status, 303);
assert.equal((await new Client().request(consoleURL)).status, 401, "ticket replay");
const html = await (await consoleClient.request(hook + "/designer")).text();
consoleClient.csrf = JSON.parse(/window\.__NEXTFLOOR_SYMCON__=(.*?);<\/script>/s.exec(html)[1]).csrf;
assert.equal((await consoleClient.json("bootstrap")).access.is_admin, true);
// A console password reset revokes remembered sessions immediately, including copied cookies.
await fetch(base + "/__test/reset", { method: "POST", body: JSON.stringify({ name: "reader", password: "reader-new-test-password" }) });
assert.equal((await reader.api("bootstrap")).status, 401);
const oldPassword = new Client(); assert.equal((await oldPassword.login("reader")).status, 401);
const resetReader = new Client(); assert.equal((await resetReader.login("reader", "reader-new-test-password")).status, 303);
const copiedCookie = new Client(); copiedCookie.cookies = new Map(resetReader.cookies); copiedCookie.csrf = resetReader.csrf;
assert.equal((await resetReader.request(hook + "/logout", { method: "POST", headers: { Origin: base, "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ csrf: resetReader.csrf }) })).status, 303);
assert.equal((await copiedCookie.api("bootstrap")).status, 401);
const brute = new Client();
for (let i = 0; i < 8; i++) assert.equal((await brute.login("unknown", "invalid-test-password")).status, 401);
assert.equal((await brute.login("unknown", "invalid-test-password")).status, 429);
const executablePath = [process.env.CHROME_PATH, "C:/Program Files/Google/Chrome/Application/chrome.exe", "C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"].find((p) => p && existsSync(p));
browser = await puppeteer.launch({ executablePath, headless: true, args: ["--use-angle=swiftshader", "--enable-unsafe-swiftshader"] });
const errors = [];
for (const [name, password] of [["reader", "reader-new-test-password"], ["office", "office-test-password"], ["device", "device-test-password"], ["admin", "admin-test-password"]]) {
const context = await browser.createBrowserContext(), page = await context.newPage(); await page.setViewport({ width: 1440, height: 1000 });
page.on("pageerror", (e) => errors.push(String(e)));
await page.goto(base + hook + "/", { waitUntil: "networkidle0" });
if (name === "reader") {
await page.screenshot({ path: join(out, "symcon-login.png") });
await page.setViewport({ width: 390, height: 844 }); await page.screenshot({ path: join(out, "symcon-login-mobile.png") });
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true);
await page.setViewport({ width: 1440, height: 1000 });
}
await page.type("#username", name); await page.type("#password", password);
const [navigation] = await Promise.all([page.waitForNavigation({ waitUntil: "networkidle0" }), page.click('button[type="submit"]')]);
assert.ok(navigation.status() < 400, `Browser login failed: ${navigation.status()} ${await page.evaluate(() => document.body.innerText)}`);
await page.waitForFunction(() => document.querySelector("nextfloor-panel")?.shadowRoot?.querySelector("nf-view3d")?.viewer).catch(async (e) => {
await page.screenshot({ path: join(out, `symcon-access-${name}-failure.png`) });
console.log("Mount failure", name, errors, await page.evaluate(() => ({ body: document.body.innerText.slice(0, 1500), panel: document.querySelector("nextfloor-panel")?.shadowRoot?.textContent.slice(-1800) })));
throw e;
});
const info = await page.evaluate(() => {
window.authPanel = document.querySelector("nextfloor-panel");
return { admin: window.authPanel.hass.user.is_admin, editor: [...window.authPanel.shadowRoot.querySelectorAll("[role=tab]")].some((b) => b.textContent.includes("Editor")), ids: Object.keys(window.authPanel.hass.states) };
});
assert.equal(info.admin, name === "admin"); assert.equal(info.editor, name === "admin");
if (name !== "admin") {
await page.evaluate(() => window.authPanel.shadowRoot.querySelector("nf-view3d").dispatchEvent(new CustomEvent("room-tap", { detail: { floorId: "eg", roomId: "office2" }, bubbles: true, composed: true })));
await page.waitForFunction(() => document.querySelector("nextfloor-panel").shadowRoot.querySelector("nf-room-panel")?.shadowRoot?.querySelector(".nf-rp"));
const buttons = await page.evaluate(() => [...window.authPanel.shadowRoot.querySelector("nf-room-panel").shadowRoot.querySelectorAll(".nf-switch")].map((b) => ({ disabled: b.disabled, name: b.getAttribute("aria-label") })));
if (name === "reader") assert.deepEqual(buttons, [], "readers get readouts, not switches");
else {
assert.ok(buttons.some((b) => !b.disabled)); assert.ok(!info.ids.includes("light.201"));
await page.evaluate(() => window.authPanel.shadowRoot.querySelector("nf-room-panel").shadowRoot.querySelector(".nf-switch:not(:disabled)").click());
await page.evaluate(() => window.authPanel.shadowRoot.querySelector("nf-view3d").dispatchEvent(new CustomEvent("room-tap", { detail: { floorId: "eg", roomId: "office3" }, bubbles: true, composed: true })));
await page.waitForFunction(() => window.authPanel.shadowRoot.querySelector("nf-room-panel")?.room?.id === "office3");
const forbiddenRoom = await page.evaluate(() => { const r = window.authPanel.shadowRoot.querySelector("nf-room-panel").shadowRoot; return { text: r.textContent, switches: r.querySelectorAll(".nf-switch").length }; });
assert.match(forbiddenRoom.text, /keine Zustände freigegeben/); assert.equal(forbiddenRoom.switches, 0); assert.doesNotMatch(forbiddenRoom.text, /26[,.]7/);
await page.screenshot({ path: join(out, `symcon-access-${name}-blocked-room.png`) });
await page.evaluate(() => window.authPanel.shadowRoot.querySelector("nf-view3d").dispatchEvent(new CustomEvent("room-tap", { detail: { floorId: "eg", roomId: "office2" }, bubbles: true, composed: true })));
}
} else {
await page.evaluate(() => [...window.authPanel.shadowRoot.querySelectorAll("[role=tab]")].find((b) => b.textContent.includes("Editor")).click());
await page.waitForFunction(() => window.authPanel.shadowRoot.querySelector("nf-editor")?.shadowRoot);
}
await page.screenshot({ path: join(out, `symcon-access-${name}.png`) });
if (name === "reader") {
await Promise.all([page.waitForNavigation({ waitUntil: "networkidle0" }), page.click('.nf-session-bar button')]);
await page.waitForSelector("#username"); await page.goBack({ waitUntil: "networkidle0" });
await page.waitForSelector("#username"); assert.equal(await page.$("nextfloor-panel"), null, "back navigation cannot restore the old account's view");
}
await context.close();
}
assert.deepEqual(errors, []);
console.log("OK: real PHP login/cookies/CSRF, remembered session reset/logout/replay/throttling, room/device/native scopes, alias and archive/bulk/admin guards, console recovery, plus real reader/operator/admin browser UIs");
} catch (e) {
console.error(logs.split("\n").filter((line) => /error|warning|fatal/i.test(line)).slice(-12).join("\n")); throw e;
} finally {
await browser?.close(); php.kill(); await new Promise((done) => { if (php.exitCode !== null) done(); else php.once("exit", done); });
if (existsSync(stateFile)) rmSync(stateFile); rmdirSync(dir);
}
+4 -4
View File
@@ -66,7 +66,7 @@ try {
await drag([7.12, 0.14], [9.1, 2.2]);
const drawn = await page.evaluate(() => window.outdoorEditor._doc.floors[0].outdoor.at(-1));
assert.ok(drawn.points.some(([x, z]) => x === 7.03 && z === 0.07), "new rectangle starts at the adjacent exact corner");
for (const [type, label] of [["street", "Straße"], ["sidewalk", "Gehweg"], ["gravel", "Schotterfläche"], ["river", "Fluss"], ["stream", "Bach"]]) {
for (const [type, label] of [["street", "Straße"], ["sidewalk", "Gehweg"], ["gravel", "Schotterfläche"], ["river", "Fluss"], ["stream", "Bach"], ["pavers", "Pflastersteine"], ["stepping_stones", "Trittplatten"], ["natural_stone", "Natursteinweg"]]) {
const stored = await page.evaluate(async ({ type, label, id }) => {
const e = window.outdoorEditor; e._tool = "select"; e.selectItem("outdoor", id); await e.updateComplete;
const input = [...e.shadowRoot.querySelectorAll("select")].find((s) => [...s.options].some((o) => o.value === type && o.textContent === label));
@@ -99,7 +99,7 @@ try {
await page.screenshot({ path: join(out, "symcon-outdoor-editor.png") });
await page.evaluate(async () => {
const p = window.nfPanel, b = structuredClone(window.outdoorEditor._doc), f = b.floors[0];
const types = ["lawn", "terrace", "path", "driveway", "street", "sidewalk", "gravel", "river", "stream", "pool", "bed", "wild", "hedge", "fence", "pergola"];
const types = ["lawn", "terrace", "path", "driveway", "street", "sidewalk", "gravel", "river", "stream", "pool", "bed", "wild", "hedge", "fence", "pergola", "pavers", "stepping_stones", "natural_stone"];
f.outdoor = types.map((type, i) => {
const x = (i % 5) * 5, z = Math.floor(i / 5) * 4;
return { id: type, type, points: [[x, z], [x + 4, z], [x + 4, z + 3], [x, z + 3]], ...(type === "terrace" ? { texture_scale: 2.5, texture_rotation: 45 } : {}), ...(type === "sidewalk" ? { slope: 0.25, texture_scale: 0.5, texture_rotation: 90 } : {}), ...(type === "stream" ? { opacity: 0.6, texture_scale: 1.5, texture_rotation: 330 } : {}) };
@@ -114,14 +114,14 @@ try {
await page.evaluate(() => {
window.outdoorView = window.nfPanel.shadowRoot.querySelector("nf-view3d");
window.nfPanel.openFloor(window.outdoorFloor);
window.outdoorView.viewer.showView({ target: { x: 12, y: 0, z: 5.5 }, radius: 25, phi: 0.65, theta: 0.1 }, 0);
window.outdoorView.viewer.showView({ target: { x: 12, y: 0, z: 7.5 }, radius: 29, phi: 0.65, theta: 0.1 }, 0);
});
for (const theme of ["neon", "day", "blueprint"]) {
await page.evaluate((theme) => { const v = window.outdoorView.viewer; v.setTheme(theme); v.invalidate(); }, theme);
await page.evaluate(() => new Promise((done) => requestAnimationFrame(() => requestAnimationFrame(done))));
await page.screenshot({ path: join(out, `symcon-outdoor-${theme}.png`) });
}
for (const [name, x, z] of [["street", 22, 1.5], ["gravel", 7, 5.5], ["lawn", 2, 1.5], ["terrace", 7, 1.5]]) {
for (const [name, x, z] of [["street", 22, 1.5], ["gravel", 7, 5.5], ["lawn", 2, 1.5], ["terrace", 7, 1.5], ["pavers", 2, 13.5], ["stepping-stones", 7, 13.5], ["natural-stone", 12, 13.5]]) {
await page.evaluate(({ x, z }) => {
const v = window.outdoorView.viewer; v.setTheme("day"); v.showView({ target: { x, y: 0, z }, radius: 5, phi: 0.65, theta: 0.1 }, 0);
}, { x, z });