// 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 === "admin") { const switched = new Client(); assert.equal((await switched.login("reader", "reader-new-test-password")).status, 303); await context.setCookie({ name: "NFSC_Session_12345", value: switched.cookies.get("NFSC_Session_12345"), url: base + hook + "/", path: hook + "/", httpOnly: true, sameSite: "Strict" }); await page.waitForFunction(() => document.querySelector("nextfloor-panel")?.hass?.user?.name === "reader"); assert.equal(await page.evaluate(() => document.querySelector("nextfloor-panel").hass.user.is_admin), false, "a shared-cookie account switch removes stale admin data in other tabs"); } 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); }