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 f6bc7b27bc
commit a3c211d8df
16 files changed
+1339 -313

No files matched your search

+111
View File
@@ -0,0 +1,111 @@
<?php
declare(strict_types=1);
require __DIR__ . '/support/access-runtime.php';
$module = new AccessFixtureModule(); initializeAccessFixture($module);
$method = static fn(string $name, mixed ...$args): mixed => (new ReflectionMethod($module, $name))->invoke($module, ...$args);
$accounts = $method('accounts');
$as = static function (string $name) use ($module, $accounts): void {
foreach ($accounts as $id => $a) if ($a['name'] === $name) {
(new ReflectionProperty(NextFloor::class, 'requestUser'))->setValue($module, [...$a, 'id' => $id, 'session_id' => 'fixture-' . $name, 'csrf' => 'fixture']);
(new ReflectionProperty(NextFloor::class, 'requestScope'))->setValue($module, null); return;
}
throw new RuntimeException('Unknown fixture account');
};
$denied = static function (callable $call, string $reason): void {
try { $call(); throw new LogicException('Unexpected permission grant: ' . $reason); }
catch (NextFloorDenied $e) { check($e->getMessage() === $reason, 'Expected ' . $reason . ', got ' . $e->getMessage()); }
};
foreach ($accounts as $a) check($a['password'] !== $a['name'] . '-test-password' && password_verify($a['name'] . '-test-password', $a['password']), 'Passwords are hashed');
$form = $module->GetConfigurationForm();
check(!str_contains($form, 'password_hash') && !str_contains($form, '$2y$') && !str_contains($form, '$argon2'), 'Configuration never exposes password hashes');
check(str_contains($form, 'SelectObject') && str_contains($form, 'Büro 2'), 'Rights use actual plan and native object choices');
$as('empty');
check($method('visibleTree', $method('objectTree'))['variables'] === [], 'An empty user sees no values');
$building = $method('visibleBuilding');
check(count($building['floors'][0]['rooms']) === 2 && count($building['floors'][0]['furniture']) === 1, 'All building geometry remains');
check($building['floors'][0]['rooms'][0]['climate_card'] === false && $building['floors'][0]['rooms'][1]['area_id'] === null, 'No live room binding leaks');
$denied(fn() => $method('authorizeApi', 'building/save', ['building' => fixtureBuilding()]), 'admin_required');
$denied(fn() => $method('authorizeApi', 'archive/trend', ['entity_id' => 'sensor.204']), 'read_forbidden');
$as('reader');
$tree = $method('visibleTree', $method('objectTree'));
check(count($tree['variables']) === 9, 'Global readers see every variable and the schedule');
check(!in_array(888, array_column(array_column($tree['variables'], 'attributes'), 'symcon_id'), true), 'All means the visualization, never unrelated Symcon variables');
check($tree['objects'] === [], 'Users never receive the full native picker');
foreach ($tree['variables'] as $v) check($v['attributes']['symcon_can_control'] === false, 'Every reader value is marked readonly');
$denied(fn() => $method('authorizeApi', 'variables/action', ['data' => ['entity_id' => 'light.101']]), 'control_forbidden');
$as('office');
$tree = $method('visibleTree', $method('objectTree'));
$ids = array_column(array_column($tree['variables'], 'attributes'), 'symcon_id'); sort($ids);
check($ids === [101, 102, 103, 104, 105], 'Room control exposes its own native category and schedule only; links do not pull in private targets');
$method('authorizeApi', 'variables/action', ['data' => ['entity_id' => 'cover.101']]); // alias uses the same native capability
$denied(fn() => $method('authorizeApi', 'variables/action', ['data' => ['entity_id' => ['light.101', 'light.201']]]), 'control_forbidden');
$denied(fn() => $method('authorizeApi', 'variables/action', ['data' => ['entity_id' => 'sensor.103']]), 'variable_readonly');
$method('authorizeApi', 'archive/trend', ['entity_id' => 'sensor.104']);
$denied(fn() => $method('authorizeApi', 'archive/trend', ['entity_id' => 'sensor.204']), 'read_forbidden');
$building = $method('visibleBuilding');
check($building['floors'][0]['rooms'][1]['climate']['temperature'] === 'none', 'Foreign room climate is removed');
check($building['floors'][0]['placements'][1]['entity_id'] === 'none', 'Foreign placement link is removed even while its geometry stays');
$as('device');
$tree = $method('visibleTree', $method('objectTree'));
$ids = array_column(array_column($tree['variables'], 'attributes'), 'symcon_id'); sort($ids);
check($ids === [102, 103], 'Single-device grant does not grant its whole room or native area');
$building = $method('visibleBuilding');
check($building['floors'][0]['rooms'][0]['climate_card'] === false, 'Device grant does not reveal room climate');
check(in_array('switch.102', $building['floors'][0]['rooms'][0]['panel'], true), 'Approved device is still reachable in its room under its actual native entity');
$denied(fn() => $method('authorizeApi', 'variables/action', ['data' => ['entity_id' => 'light.101']]), 'control_forbidden');
// Shared variables and legacy bindings on a different item must not reappear outside the granted room.
$extended = fixtureBuilding();
$extended['floors'][0]['furniture'][] = ['id' => 'private', 'type' => 'wallbox', 'x' => 7, 'z' => 2, 'temp_entity2' => 'sensor.104', 'legacy_binding' => 'sensor.104', 'picture' => 'https://camera.invalid/live'];
$fixture['attributes']['Building'] = json_encode($extended);
$as('office'); $projected = $method('visibleBuilding')['floors'][0]['furniture'][1];
check($projected['temp_entity2'] === 'none' && $projected['legacy_binding'] === 'none' && !isset($projected['picture']), 'Unauthorized items never reuse otherwise approved values or live pictures');
$extended['floors'][0]['furniture'][0]['temp_entity2'] = 'sensor.104';
$fixture['attributes']['Building'] = json_encode($extended);
$as('device');
check($method('allowedEntity', 'sensor.104', false), 'Additional temperature bindings belong to an explicitly granted device');
$fixture['attributes']['Building'] = json_encode(fixtureBuilding());
$as('operator');
$method('authorizeApi', 'variables/action', ['data' => ['entity_id' => 'light.201']]);
$denied(fn() => $method('authorizeApi', 'archive/trend', ['entity_id' => 'sensor.888']), 'read_forbidden');
$denied(fn() => $method('authorizeApi', 'variables/action', ['data' => ['entity_id' => 'sensor.888']]), 'control_forbidden');
$as('native');
$tree = $method('visibleTree', $method('objectTree'));
$ids = array_column(array_column($tree['variables'], 'attributes'), 'symcon_id'); sort($ids);
check($ids === [201, 203], 'An explicit native instance grant follows its descendants, not its whole area');
$as('admin');
$method('authorizeApi', 'building/save', ['building' => fixtureBuilding()]);
check(count($method('visibleTree', $method('objectTree'))['objects']) > 0, 'Admin retains the native editor tree');
check($method('visibleBuilding') === fixtureBuilding(), 'Admin project is unmodified');
ob_start(); $method('sendApiResult', ['payload' => str_repeat('x', 300000)], true); $manifest = json_decode((string) ob_get_clean(), true)['_nextfloor_transfer'];
$as('reader');
try { $method('readTransfer', $manifest['id'], 0); throw new LogicException('Cross-session transport read was accepted'); }
catch (RuntimeException $e) { check($e->getMessage() === 'transfer_not_found', 'Transfer ownership is enforced'); }
$method('releaseTransfer', $manifest['id']);
$as('admin');
check(strlen($method('readTransfer', $manifest['id'], 0)['data']) > 0, 'Another session cannot remove this snapshot');
$method('releaseTransfer', $manifest['id']);
$url = $module->OpenDesigner(); parse_str((string) parse_url(substr($url, 5), PHP_URL_QUERY), $query);
check(isset($query['ticket']) && !isset($query['token']), 'Console links use tickets, never a reusable admin token');
check($method('exchangeConsoleTicket', $query['ticket']), 'Console recovers admin access without an account');
check(!$method('exchangeConsoleTicket', $query['ticket']), 'Console tickets cannot be replayed');
check(!str_contains($module->GetVisualizationTile(), 'ticket=') && !str_contains($module->GetVisualizationTile(), 'token='), 'Tiles never embed admin capabilities');
// A saved rights/enable change and a native delete revoke a previously valid cookie.
$accountID = array_key_first(array_filter($accounts, static fn(array $a): bool => $a['name'] === 'officeview'));
$browserToken = str_repeat('b', 64);
$fixture['attributes']['Sessions'] = json_encode([hash('sha256', $browserToken) => ['account' => $accountID, 'epoch' => $accounts[$accountID]['epoch'], 'csrf' => 'test', 'seen' => time(), 'expires' => time() + 3600]]);
$_COOKIE['NFSC_Session_12345'] = $browserToken;
check($method('resolveSession') !== null, 'Cookie starts valid');
$module->SaveAccessUser($accountID, 'officeview', 'user', false, false, false, '[]', '[]', '[]', '');
check($method('resolveSession') === null, 'Disabling or editing rights revokes the old cookie');
$module->DeleteAccessUser($accountID);
check(!isset($method('accounts')[$accountID]) && $method('resolveSession') === null, 'Deletion removes the account and its access');
echo "OK: hashed accounts, console recovery, one-use tickets, admin/reader/room/device scopes, alias-resistant access, private state and geometry separation, bulk preauthorization, archive guards and native readonly variables\n";
+18
View File
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
if (!getenv('NEXTFLOOR_TEST_STATE')) { echo "Local authentication browser-test fixture; NEXTFLOOR_TEST_STATE required.\n"; exit; }
require __DIR__ . '/support/access-runtime.php';
$module = new AccessFixtureModule(); initializeAccessFixture($module);
$path = parse_url((string) $_SERVER['REQUEST_URI'], PHP_URL_PATH);
if ($path === '/__test/console') { header('Content-Type: application/json'); echo json_encode(['url' => substr($module->OpenDesigner(), 5)]); return; }
if ($path === '/__test/state') {
header('Content-Type: application/json');
echo json_encode(['writes' => $fixture['writes'], 'accounts' => array_map(static fn(array $a): array => ['name' => $a['name'], 'enabled' => $a['enabled']], json_decode($fixture['attributes']['Accounts'], true))]); return;
}
if ($path === '/__test/reset' && $_SERVER['REQUEST_METHOD'] === 'POST') {
$data = json_decode((string) file_get_contents('php://input'), true);
$accounts = json_decode($fixture['attributes']['Accounts'], true);
foreach ($accounts as $id => $a) if ($a['name'] === ($data['name'] ?? '')) { echo $module->ResetUserPassword($id, (string) ($data['password'] ?? '')); return; }
}
$module->hook();
+105
View File
@@ -0,0 +1,105 @@
<?php
declare(strict_types=1);
// Deliberately small local Symcon fixture. No connection to a user's actual kernel or variables.
const KR_READY = 10103;
const IPS_KERNELSTARTED = 10001;
const KL_ERROR = 10205;
$fixtureFile = getenv('NEXTFLOOR_TEST_STATE') ?: '';
$fixture = $fixtureFile !== '' && is_file($fixtureFile) ? json_decode((string) file_get_contents($fixtureFile), true) : [];
$fixture += ['attributes' => [], 'properties' => [], 'writes' => [], 'initialized' => false];
function persistFixture(): void { global $fixture, $fixtureFile; if ($fixtureFile !== '') file_put_contents($fixtureFile, json_encode($fixture, JSON_THROW_ON_ERROR), LOCK_EX); }
function check(bool $condition, string $message): void { if (!$condition) throw new RuntimeException($message); }
class IPSModuleStrict
{
protected int $InstanceID;
public array $fields = [];
public function __construct(int $id = 12345) { $this->InstanceID = $id; }
public function Create(): void {}
public function ApplyChanges(): void {}
public function MessageSink(int $t, int $s, int $m, array $d): void {}
protected function RegisterPropertyString(string $name, string $value): void { global $fixture; $fixture['properties'][$name] ??= $value; persistFixture(); }
protected function RegisterAttributeString(string $name, string $value): void { global $fixture; $fixture['attributes'][$name] ??= $value; persistFixture(); }
protected function RegisterAttributeInteger(string $name, int $value): void { global $fixture; $fixture['attributes'][$name] ??= $value; persistFixture(); }
protected function ReadAttributeString(string $name): string { global $fixture; return (string) ($fixture['attributes'][$name] ?? ''); }
protected function ReadAttributeInteger(string $name): int { global $fixture; return (int) ($fixture['attributes'][$name] ?? 0); }
protected function WriteAttributeString(string $name, string $value): void { global $fixture; $fixture['attributes'][$name] = $value; persistFixture(); }
protected function WriteAttributeInteger(string $name, int $value): void { global $fixture; $fixture['attributes'][$name] = $value; persistFixture(); }
protected function ReadPropertyString(string $name): string { global $fixture; return (string) ($fixture['properties'][$name] ?? ''); }
protected function RegisterMessage(int $sender, int $message): void {}
protected function RegisterTimer(string $name, int $interval, string $script): void {}
protected function SetTimerInterval(string $name, int $interval): void {}
protected function SetVisualizationType(int $type): void {}
protected function SetStatus(int $status): void {}
protected function LogMessage(string $message, int $type): void { throw new RuntimeException('Unexpected module log: ' . $message); }
protected function RegisterHook(string $path): bool { return true; }
protected function UpdateFormField(string $name, string $key, mixed $value): void { $this->fields[$name][$key] = $value; }
protected function UpdateVisualizationValue(string $value): void {}
}
function IPS_GetKernelRunlevel(): int { return KR_READY; }
function IPS_GetInstanceListByModuleID(string $module): array { return $module === '{43192F0B-135B-4CE7-A0A7-1475603F3060}' ? [700] : []; }
function fixtureObjects(): array
{
return [1 => [0, 0, 'Gebäude'], 10 => [1, 0, 'Büro 2'], 20 => [1, 0, 'Büro 3'], 900 => [20, 1, 'Privates Gerät'],
101 => [10, 2, 'Licht'], 102 => [10, 2, 'Wallbox schalten'], 103 => [10, 2, 'Wallbox Leistung'], 104 => [10, 2, 'Raumtemperatur'],
105 => [10, 4, 'Schaltuhr'], 201 => [900, 2, 'Licht privat'], 203 => [900, 2, 'Leistung privat'], 204 => [20, 2, 'Temperatur privat'],
999 => [1, 2, 'Gesamtleistung'], 888 => [1, 2, 'Nicht mit NextFloor verknüpftes Geheimnis'], 109 => [10, 6, 'Link auf privaten Datenpunkt']];
}
function IPS_ObjectExists(int $id): bool { return isset(fixtureObjects()[$id]); }
function IPS_VariableExists(int $id): bool { return (fixtureObjects()[$id][1] ?? -1) === 2; }
function IPS_EventExists(int $id): bool { return $id === 105; }
function IPS_GetName(int $id): string { return fixtureObjects()[$id][2]; }
function IPS_GetObject(int $id): array { $o = fixtureObjects()[$id]; return ['ParentID' => $o[0], 'ObjectType' => $o[1], 'ObjectPosition' => $id, 'ObjectIsHidden' => false, 'ObjectIcon' => '']; }
function IPS_GetChildrenIDs(int $id): array { return array_keys(array_filter(fixtureObjects(), static fn(array $o): bool => $o[0] === $id)); }
function IPS_GetLink(int $id): array { return ['TargetID' => 201]; }
function IPS_GetInstance(int $id): array { return ['ModuleInfo' => ['ModuleType' => 3, 'ModuleID' => '{00000000-0000-0000-0000-000000000001}']]; }
function IPS_GetVariable(int $id): array { return ['VariableType' => in_array($id, [101, 102, 201], true) ? 0 : 2, 'VariableCustomAction' => 0, 'VariableAction' => in_array($id, [101, 102, 201], true) ? 1 : 0, 'VariableCustomProfile' => '', 'VariableProfile' => '']; }
function IPS_GetVariablePresentation(int $id): array { return ['SUFFIX' => in_array($id, [104, 204], true) ? '°C' : (in_array($id, [103, 203, 999], true) ? 'W' : ''), 'MIN' => 0, 'MAX' => 100]; }
function IPS_VariableProfileExists(string $name): bool { return false; }
function GetValue(int $id): mixed { global $fixture; return $fixture['values'][$id] ?? match ($id) { 101, 102 => true, 201 => false, 104 => 22.3, 204 => 26.7, 103 => 7400.0, 203 => 531.0, default => 7931.0 }; }
function GetValueFormatted(int $id): string { $v = GetValue($id); return is_bool($v) ? ($v ? 'An' : 'Aus') : (string) $v; }
function RequestAction(int $id, mixed $value): void { global $fixture; $fixture['writes'][] = [$id, $value]; $fixture['values'][$id] = $value; persistFixture(); }
function SetValue(int $id, mixed $value): void { RequestAction($id, $value); }
function IPS_GetEvent(int $id): array { global $fixture; return ['EventType' => 2, 'EventActive' => $fixture['values'][105] ?? true, 'ScheduleActions' => [], 'ScheduleGroups' => []]; }
function IPS_SetEventActive(int $id, bool $active): bool { RequestAction($id, $active); return true; }
function AC_GetAggregationVariables(int $id, bool $all): array { return array_map(static fn(int $v): array => ['VariableID' => $v, 'AggregationActive' => true, 'AggregationType' => 0], [104, 204]); }
function AC_GetLoggedValues(int $a, int $id, int $start, int $end, int $limit): array { return $start === 0 ? [] : [['TimeStamp' => $start, 'Value' => GetValue($id), 'Duration' => 60], ['TimeStamp' => $end, 'Value' => GetValue($id), 'Duration' => 0]]; }
function AC_GetAggregatedValues(int $a, int $id, int $level, int $start, int $end, int $limit): array { return []; }
require_once __DIR__ . '/../../NextFloor/module.php';
class AccessFixtureModule extends NextFloor { public function hook(): void { $this->ProcessHookData(); } }
function fixtureBuilding(): array
{
$room = static fn(string $id, string $name, int $x, int $category, string $temperature): array => ['id' => $id, 'name' => $name, 'area_id' => 'symcon-category-' . $category, 'points' => [[$x, 0], [$x + 4, 0], [$x + 4, 3], [$x, 3]], 'floor_material' => 'wood', 'climate_card' => true, 'climate' => ['temperature' => $temperature]];
return ['version' => 1, 'settings' => ['grid' => 0.1, 'north' => 0, 'wall_exterior' => 0.24, 'wall_interior' => 0.12, 'roof' => ['type' => 'none'], 'plugins' => []],
'energy' => ['consumption' => 'sensor.999'], 'presence' => [], 'floors' => [['id' => 'eg', 'name' => 'Erdgeschoss', 'elevation' => 0, 'height' => 2.7, 'cut_height' => 1.2,
'rooms' => [$room('office2', 'Büro 2', 0, 10, 'sensor.104'), $room('office3', 'Büro 3', 5, 20, 'sensor.204')],
'openings' => [], 'walls' => [], 'outdoor' => [], 'background' => null,
'placements' => [['entity_id' => 'light.101', 'x' => 2, 'z' => 1, 'y' => null], ['entity_id' => 'light.201', 'x' => 7, 'z' => 1, 'y' => null]],
'furniture' => [['id' => 'wallbox', 'type' => 'wallbox', 'name' => 'Wallbox Büro 2', 'x' => 3, 'z' => 2, 'w' => 0.3, 'd' => 0.3, 'h' => 0.4, 'rotation' => 0, 'entity' => 'light.102', 'power' => 'sensor.103', 'power_card' => true]]]]];
}
function initializeAccessFixture(AccessFixtureModule $module): void
{
global $fixture;
$module->Create();
if ($fixture['initialized']) return;
$fixture['properties']['Title'] = 'Bürogebäude';
$fixture['attributes']['Building'] = json_encode(fixtureBuilding(), JSON_THROW_ON_ERROR);
$fixture['attributes']['BuildingRevision'] = 1;
$make = static function (string $name, string $role, bool $viewAll, bool $controlAll, array $rooms = [], array $devices = [], array $objects = []) use ($module): void {
$result = $module->SaveAccessUser('', $name, $role, true, $viewAll, $controlAll, json_encode($rooms), json_encode($devices), json_encode($objects), $name . '-test-password');
check(str_starts_with($result, 'Benutzer gespeichert'), $result);
};
$make('admin', 'admin', true, true);
$make('reader', 'user', true, false);
$make('office', 'user', false, false, [['target' => 'room:eg:office2', 'access' => 'control']]);
$make('officeview', 'user', false, false, [['target' => 'room:eg:office2', 'access' => 'view']]);
$make('device', 'user', false, false, [], [['target' => 'furniture:eg:wallbox', 'access' => 'control']]);
$make('empty', 'user', false, false);
$make('operator', 'user', true, true);
$make('native', 'user', false, false, [], [], [['target' => 900, 'access' => 'view']]);
$fixture['initialized'] = true; persistFixture();
}
+3
View File
@@ -56,6 +56,9 @@ export function validateSymconPackage(root = fileURLToPath(new URL("../", import
ids.add(module.id);
assert.equal(entry.name, module.name.replaceAll(" ", ""), "Module directory must match its PHP class name");
const php = readFileSync(join(directory, "module.php"), "utf8");
for (const helper of ["Access.php", "Users.php", "Permissions.php"]) {
assert.ok(readFileSync(join(directory, "libs", helper)).length > 0, `Missing server access helper: ${helper}`);
}
assert.match(php, new RegExp(`class\\s+${entry.name}\\s+extends\\s+IPSModuleStrict\\b`), "Module PHP class is missing or mismatched");
const form = readJson(join(directory, "form.json"));
assert.ok(Array.isArray(form.elements) && Array.isArray(form.actions), "Module form must contain elements and actions");
+7 -2
View File
@@ -144,7 +144,10 @@ $earlyFailure->RetryWebHook();
check(isset($nativeHooks['/hook/nextfloor/34567']) && $earlyFailure->status === 102, 'Unavailable early WebHook Control must recover automatically');
// Verify that returned URLs reach the real dispatcher, including Symcon's SCRIPT_NAME fallback.
parse_str((string) parse_url(substr($link, 5), PHP_URL_QUERY), $_GET);
$_GET = [];
$browserToken = str_repeat('a', 64);
$_COOKIE = ['NFSC_Session_12345' => $browserToken];
$module->attributes['Sessions'] = json_encode([hash('sha256', $browserToken) => ['account' => '__console__', 'epoch' => $token, 'csrf' => 'fixture', 'expires' => time() + 3600, 'seen' => time()]]);
$_SERVER['REQUEST_URI'] = $hook . '/designer';
$process = new ReflectionMethod($module, 'ProcessHookData');
ob_start();
@@ -163,9 +166,11 @@ $process->invoke($module);
$fallback = ob_get_clean();
check(str_contains($fallback, 'window.__NEXTFLOOR_SYMCON__='), 'Dispatcher must accept SCRIPT_NAME when REQUEST_URI is absent');
$_GET['token'] = 'wrong-token';
$_COOKIE = [];
$_SERVER['SCRIPT_NAME'] = $hook . '/api';
ob_start();
$process->invoke($module);
$unauthorized = ob_get_clean();
check(http_response_code() === 403 && str_contains($unauthorized, 'forbidden'), 'Recovery must not bypass hook authentication');
check(http_response_code() === 401 && str_contains($unauthorized, 'authentication_required'), 'Recovery and legacy URL tokens must not bypass session authentication');
echo "OK: early registration, startup/update and delayed reset recovery, ongoing maintenance, titles, data preservation, routing and authentication\n";