fix: bound Symcon API responses below the kernel output limit

This commit is contained in:
jhartworks committed 2026-11-09 14:37:21 +01:00
1 parent eff9eb83d7
commit 804f2d0494
9 files changed
+470 -110

No files matched your search

+95
View File
@@ -0,0 +1,95 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { callSymcon } 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("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));
assert.equal(request.action, "building/get");
assert.equal(request.transport, "nextfloor-chunks-v1");
return new Response(JSON.stringify({ revision: 1 }));
});
assert.deepEqual(await callSymcon(settings, "building/get"), { revision: 1 });
});
test("the real bridge loads 10000 variables and objects through bounded, immutable response chunks", async (context) => {
const variables = Array.from({ length: 10000 }, (_, index) => ({
entity_id: `sensor.${index + 1}`, name: `Zähler Küche ÄÖÜ 🌞 ${index}`, state: "21.5",
path: `Haus / Erdgeschoss / Küche / ${"Unterkategorie / ".repeat(8)}Zähler ${index}`,
attributes: { unit_of_measurement: "°C" },
}));
const objects = variables.map((variable, index) => ({ object_id: index + 1, parent_id: 0, name: variable.name, path: variable.path, object_type: 2, position: index, hidden: false, icon: "", entity_id: variable.entity_id }));
const expected = { state_revision: 1, building_revision: 2, variables, objects, areas: [] };
const encoded = new TextEncoder().encode(JSON.stringify(expected));
assert.ok(encoded.length > 1024 * 1024, "fixture must reproduce the actual output-limit failure");
const actions: string[] = [];
let largestResponse = 0;
context.mock.method(globalThis, "fetch", async (_url: string, init: RequestInit) => {
const request = JSON.parse(String(init.body));
actions.push(request.action);
let reply: unknown;
if (request.action === "bootstrap") reply = { _nextfloor_transfer: { id, bytes: encoded.length, chunk_bytes: CHUNK_BYTES, chunks: Math.ceil(encoded.length / CHUNK_BYTES) } };
else if (request.action === "transport/read") {
assert.equal(request.transfer_id, id);
reply = { index: request.index, data: Buffer.from(encoded.subarray(request.index * CHUNK_BYTES, (request.index + 1) * CHUNK_BYTES)).toString("base64") };
} else {
assert.equal(request.action, "transport/release");
reply = [];
}
const json = JSON.stringify(reply);
largestResponse = Math.max(largestResponse, Buffer.byteLength(json));
return new Response(json);
});
const previousWindow = Object.getOwnPropertyDescriptor(globalThis, "window");
Object.defineProperty(globalThis, "window", { configurable: true, value: { __NEXTFLOOR_SYMCON__: settings, matchMedia: () => ({ matches: true }) } });
let bridge: SymconBridge | undefined;
try {
bridge = new SymconBridge();
const hass = await bridge.start();
bridge.stop();
assert.equal(Object.keys(hass.states).length, variables.length);
assert.equal(hass.symconObjects?.length, objects.length);
assert.equal(hass.states["sensor.10000"].attributes.friendly_name, variables.at(-1)!.name);
assert.equal(actions.filter((action) => action === "bootstrap").length, 1, "chunks must not rerun the original action");
assert.equal(actions.filter((action) => action === "transport/release").length, 1);
assert.ok(largestResponse < 256 * 1024);
} finally {
bridge?.stop();
if (previousWindow) Object.defineProperty(globalThis, "window", previousWindow);
else Reflect.deleteProperty(globalThis, "window");
}
});
test("UTF-8 characters split across byte boundaries are reassembled without loss", async (context) => {
const expected = { text: "ä🌞".repeat(200000) };
const encoded = Buffer.from(JSON.stringify(expected));
context.mock.method(globalThis, "fetch", async (_url: string, init: RequestInit) => {
const request = JSON.parse(String(init.body));
const reply = request.action === "image/get" ? { _nextfloor_transfer: { id, bytes: encoded.length, chunk_bytes: CHUNK_BYTES, chunks: Math.ceil(encoded.length / CHUNK_BYTES) } }
: request.action === "transport/read" ? { index: request.index, data: encoded.subarray(request.index * CHUNK_BYTES, (request.index + 1) * CHUNK_BYTES).toString("base64") } : [];
return new Response(JSON.stringify(reply));
});
assert.deepEqual(await callSymcon(settings, "image/get"), expected);
});
test("incomplete chunks abort and release the snapshot instead of showing partial object data", async (context) => {
const actions: string[] = [];
context.mock.method(globalThis, "fetch", async (_url: string, init: RequestInit) => {
const request = JSON.parse(String(init.body));
actions.push(request.action);
return new Response(JSON.stringify(request.action === "bootstrap" ? { _nextfloor_transfer: { id, bytes: CHUNK_BYTES + 2, chunk_bytes: CHUNK_BYTES, chunks: 2 } }
: request.action === "transport/read" ? { index: request.index, data: "eA==" } : []));
});
await assert.rejects(callSymcon(settings, "bootstrap"), /unvollständig/);
assert.deepEqual(actions, ["bootstrap", "transport/read", "transport/release"]);
});
test("Symcon's HTTP-200 output-buffer failure has an accurate error message", async (context) => {
context.mock.method(globalThis, "fetch", async () => new Response("Output-Buffer exceeds Limit (1048576 bytes). Operation halted.", { status: 200 }));
await assert.rejects(callSymcon(settings, "bootstrap"), /Ausgabebegrenzung/);
});
+69
View File
@@ -0,0 +1,69 @@
// Bounded WebHook responses: Symcon's default PHP output limit is 1 MiB per request.
export interface SymconEndpoint {
endpoint: string;
token: string;
}
interface Transfer {
id: string;
bytes: number;
chunk_bytes: number;
chunks: number;
}
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)}`, {
method: "POST",
headers: { "Content-Type": "application/json", Accept: "application/json" },
credentials: "same-origin",
body: JSON.stringify({ ...payload, action, transport: TRANSPORT }),
});
const raw = await response.text();
let body: unknown;
try {
body = JSON.parse(raw);
} catch {
if (/Output-Buffer exceeds Limit/i.test(raw)) {
throw new Error("Symcon hat die Antwort wegen seiner Ausgabebegrenzung abgebrochen. Bitte das NextFloor-Modul aktualisieren und den Designer neu laden.");
}
throw new Error(`Symcon liefert ${raw.trim() ? "kein gültiges JSON" : "eine leere Antwort"} für „${action}“ (HTTP ${response.status}).`);
}
if (!response.ok || !body || typeof body !== "object" || "error" in body) {
const error = body && typeof body === "object" && "error" in body ? (body as { error?: unknown }).error : `HTTP ${response.status}`;
throw new Error(String(error));
}
return body as Record<string, unknown>;
}
/** Complete an immutable response snapshot without rerunning the original action for each chunk. */
export async function callSymcon<T>(settings: SymconEndpoint, action: string, payload: Record<string, unknown> = {}): Promise<T> {
const body = await request(settings, action, payload);
if (!("_nextfloor_transfer" in body)) return body as T;
const transfer = body._nextfloor_transfer as Transfer | null;
if (!transfer || !/^[a-f0-9]{32}$/.test(transfer.id) || !Number.isSafeInteger(transfer.bytes) || transfer.bytes <= 0
|| transfer.bytes > MAX_TRANSFER_BYTES || !Number.isSafeInteger(transfer.chunk_bytes) || transfer.chunk_bytes <= 0
|| transfer.chunk_bytes > 128 * 1024 || transfer.chunks !== Math.ceil(transfer.bytes / transfer.chunk_bytes) || transfer.chunks > 512) {
throw new Error("Symcon hat eine ungültige Datenübertragung angekündigt.");
}
try {
const decoder = new TextDecoder("utf-8", { fatal: true });
const parts: string[] = [];
for (let index = 0; index < transfer.chunks; index++) {
const chunk = await request(settings, "transport/read", { transfer_id: transfer.id, index });
if (chunk.index !== index || typeof chunk.data !== "string") throw new Error("Ein Symcon-Datenpaket fehlt oder ist ungültig.");
const bytes = Uint8Array.from(atob(chunk.data), (character) => character.charCodeAt(0));
if (bytes.length !== Math.min(transfer.chunk_bytes, transfer.bytes - index * transfer.chunk_bytes)) {
throw new Error("Ein Symcon-Datenpaket wurde unvollständig übertragen.");
}
parts.push(decoder.decode(bytes, { stream: true }));
}
parts.push(decoder.decode());
return JSON.parse(parts.join("")) as T;
} finally {
// Failed transfers are released too; the server expires abandoned browser sessions separately.
await request(settings, "transport/release", { transfer_id: transfer.id }).catch(() => undefined);
}
}
+6 -16
View File
@@ -5,6 +5,7 @@
// 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";
interface SymconConfig {
endpoint: string;
@@ -54,22 +55,6 @@ function config(): SymconConfig {
return settings;
}
/** Same-origin JSON call to the instance's protected WebHook. */
async function call<T>(settings: SymconConfig, action: string, payload: Record<string, unknown> = {}): Promise<T> {
const response = await fetch(`${settings.endpoint}/api?token=${encodeURIComponent(settings.token)}`, {
method: "POST",
headers: { "Content-Type": "application/json", Accept: "application/json" },
credentials: "same-origin",
body: JSON.stringify({ action, ...payload }),
});
const body: unknown = await response.json().catch(() => ({ error: `HTTP ${response.status}` }));
if (!response.ok || !body || typeof body !== "object" || "error" in body) {
const error = body && typeof body === "object" && "error" in body ? (body as { error?: unknown }).error : `HTTP ${response.status}`;
throw new Error(String(error));
}
return body as T;
}
/**
* Turns the instance WebHook into the interface used by the NextFloor UI. Polling is deliberate here: it
* works in the designer tab, an iframe in the Tile visualization and a remote WebFront without exposing an
@@ -83,6 +68,7 @@ export class SymconBridge {
private stateRevision = -1;
private buildingRevision = -1;
private objectsSignature = "";
private refreshing = false;
private states: Record<string, HassEntity> = {};
private entities: Record<string, HassEntityEntry> = {};
private areas: Record<string, HassArea> = {};
@@ -140,6 +126,8 @@ export class SymconBridge {
}
private async refresh(): Promise<void> {
if (this.refreshing) return;
this.refreshing = true;
try {
const next = await call<VariableSnapshot>(this.settings, "variables/snapshot", { revision: this.stateRevision });
if (next.state_revision !== this.stateRevision && next.variables) {
@@ -153,6 +141,8 @@ export class SymconBridge {
}
} catch {
// A temporary unavailable WebHook must not blank a running visualization. The next poll retries.
} finally {
this.refreshing = false;
}
}