feat: add scoped user accounts, password login and garden paving materials
This commit is contained in:
1 parent
c56f1a5ba9
commit
1d67e8ceba
43 files changed
+2024
-625
No files matched your search
+93
-46
@@ -2,15 +2,20 @@
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
require_once __DIR__ . '/libs/Access.php';
|
||||
require_once __DIR__ . '/libs/Users.php';
|
||||
require_once __DIR__ . '/libs/Permissions.php';
|
||||
|
||||
/**
|
||||
* NextFloor for IP-Symcon.
|
||||
*
|
||||
* One visualization instance owns a floor-plan project. Its protected WebHook serves the designer as
|
||||
* a console tab and the same viewer in an HTML-SDK tile iframe. The frontend receives every variable
|
||||
* in the object tree with a friendly path; it never asks an end user to type an object id.
|
||||
* a console tab and the same viewer in an HTML-SDK tile iframe. Admins receive the native object tree;
|
||||
* user sessions receive only authorized live bindings. Object selections always use named choices.
|
||||
*/
|
||||
class NextFloor extends IPSModuleStrict
|
||||
{
|
||||
use NextFloorAccess, NextFloorUsers, NextFloorPermissions;
|
||||
private const MAX_BUILDING_BYTES = 8_000_000;
|
||||
private const MAX_IMAGE_BYTES = 8_000_000;
|
||||
private const MAX_HISTORY = 20;
|
||||
@@ -31,6 +36,12 @@ class NextFloor extends IPSModuleStrict
|
||||
$this->RegisterAttributeString('Packs', '[]');
|
||||
$this->RegisterAttributeString('History', '[]');
|
||||
$this->RegisterAttributeString('AccessToken', '');
|
||||
$this->RegisterAttributeString('Accounts', '{}');
|
||||
$this->RegisterAttributeString('Sessions', '{}');
|
||||
$this->RegisterAttributeString('ConsoleTickets', '{}');
|
||||
$this->RegisterAttributeString('LoginThrottle', '{}');
|
||||
$this->RegisterAttributeString('LoginDummyHash', '');
|
||||
$this->RegisterAttributeString('SelectedAccount', '');
|
||||
$this->RegisterAttributeString('StateHash', '');
|
||||
$this->RegisterAttributeString('HookError', '');
|
||||
$this->RegisterAttributeInteger('BuildingRevision', 0);
|
||||
@@ -40,6 +51,7 @@ class NextFloor extends IPSModuleStrict
|
||||
$this->RegisterTimer('WebHookRetry', 0, 'NFSC_RetryWebHook($_IPS[\'TARGET\']);');
|
||||
|
||||
$this->ensureAccessToken();
|
||||
if ($this->ReadAttributeString('LoginDummyHash') === '') $this->WriteAttributeString('LoginDummyHash', $this->passwordHash($this->newToken()));
|
||||
$this->SetVisualizationType(1);
|
||||
$this->ensureWebHook(true);
|
||||
}
|
||||
@@ -84,11 +96,13 @@ class NextFloor extends IPSModuleStrict
|
||||
return 'link:' . $this->designerUrl('designer');
|
||||
}
|
||||
|
||||
/** Invalidates links from copied browser history and returns a fresh designer URL. */
|
||||
/** Revoke all logins and outstanding console tickets, then issue a fresh one-use designer link. */
|
||||
public function RotateAccessToken(): string
|
||||
{
|
||||
$this->requireWebHook();
|
||||
$this->WriteAttributeString('AccessToken', $this->newToken());
|
||||
$this->WriteAttributeString('Sessions', '{}');
|
||||
$this->WriteAttributeString('ConsoleTickets', '{}');
|
||||
return 'link:' . $this->designerUrl('designer');
|
||||
}
|
||||
|
||||
@@ -108,24 +122,52 @@ class NextFloor extends IPSModuleStrict
|
||||
/** IP-Symcon calls this for /hook/nextfloor/<instance id>/... */
|
||||
protected function ProcessHookData(): void
|
||||
{
|
||||
$this->requestUser = null;
|
||||
$this->requestScope = null;
|
||||
// Keep a same-origin Origin on native form POSTs; no-referrer can turn it into "null".
|
||||
header('Referrer-Policy: same-origin');
|
||||
header('X-Content-Type-Options: nosniff');
|
||||
header('X-Frame-Options: SAMEORIGIN');
|
||||
header("Content-Security-Policy: frame-ancestors 'self'; object-src 'none'; base-uri 'none'");
|
||||
$requestPath = (string) ($_SERVER['REQUEST_URI'] ?? '');
|
||||
if ($requestPath === '') {
|
||||
$requestPath = (string) ($_SERVER['SCRIPT_NAME'] ?? '');
|
||||
}
|
||||
$path = (string) (parse_url($requestPath, PHP_URL_PATH) ?? '');
|
||||
$prefix = '/hook/' . $this->hookPath();
|
||||
if (!str_starts_with($path, $prefix)) {
|
||||
if ($path !== $prefix && !str_starts_with($path, $prefix . '/')) {
|
||||
$this->sendError(404, 'not_found');
|
||||
return;
|
||||
}
|
||||
if (!$this->hasValidToken()) {
|
||||
$this->sendError(403, 'forbidden');
|
||||
return;
|
||||
}
|
||||
|
||||
$tail = trim(substr($path, strlen($prefix)), '/');
|
||||
try {
|
||||
$method = (string) ($_SERVER['REQUEST_METHOD'] ?? 'GET');
|
||||
$this->requestUser = $this->resolveSession();
|
||||
if ($tail === 'login') {
|
||||
if ($method === 'POST') $this->passwordLogin();
|
||||
elseif ($method !== 'GET') $this->sendError(405, 'method_not_allowed');
|
||||
elseif ($this->requestUser !== null) $this->accessRedirect($this->entryUrl());
|
||||
else $this->loginPage();
|
||||
return;
|
||||
}
|
||||
if (($tail === 'designer' || $tail === '') && $method === 'GET' && isset($_GET['ticket'])) {
|
||||
// Always exchange and remove a ticket, even if another user was already logged in.
|
||||
if (is_string($_GET['ticket']) && $this->exchangeConsoleTicket($_GET['ticket'])) $this->accessRedirect($this->entryUrl());
|
||||
else $this->loginPage('Der Konsolen-Link ist abgelaufen oder wurde schon verwendet. Bitte erneut in der Konsole öffnen.', 401);
|
||||
return;
|
||||
}
|
||||
if ($this->requestUser === null) {
|
||||
if ($tail === '' || $tail === 'designer') $this->accessRedirect($this->entryUrl('login'));
|
||||
else $this->sendError(401, 'authentication_required');
|
||||
return;
|
||||
}
|
||||
if ($tail === 'logout') {
|
||||
if ($method !== 'POST' || !$this->validCsrf()) $this->sendError(403, 'csrf_invalid');
|
||||
else $this->logoutSession();
|
||||
return;
|
||||
}
|
||||
if ($tail === '' || $tail === 'designer') {
|
||||
if ($method !== 'GET') { $this->sendError(405, 'method_not_allowed'); return; }
|
||||
$this->sendDesignerPage();
|
||||
return;
|
||||
}
|
||||
@@ -134,6 +176,8 @@ class NextFloor extends IPSModuleStrict
|
||||
return;
|
||||
}
|
||||
if (str_starts_with($tail, 'assets/')) {
|
||||
if ($method !== 'GET') { $this->sendError(405, 'method_not_allowed'); return; }
|
||||
if (!$this->isAdministrator() && preg_match('#^assets/nextfloor-(?:editor|card-editor)\.js$#D', $tail)) { $this->sendError(403, 'admin_required'); return; }
|
||||
$this->sendAsset(substr($tail, strlen('assets/')));
|
||||
return;
|
||||
}
|
||||
@@ -216,7 +260,7 @@ class NextFloor extends IPSModuleStrict
|
||||
|
||||
private function designerUrl(string $mode): string
|
||||
{
|
||||
return '/hook/' . $this->hookPath() . '/designer?mode=' . rawurlencode($mode) . '&token=' . rawurlencode($this->ensureAccessToken());
|
||||
return $mode === 'tile' ? '/hook/' . $this->hookPath() . '/designer?mode=tile' : $this->consoleUrl();
|
||||
}
|
||||
|
||||
private function ensureAccessToken(): string
|
||||
@@ -234,46 +278,21 @@ class NextFloor extends IPSModuleStrict
|
||||
return bin2hex(random_bytes(32));
|
||||
}
|
||||
|
||||
private function hasValidToken(): bool
|
||||
{
|
||||
// The first HTML request carries the random URL token. It also sets an HttpOnly cookie
|
||||
// below, so lazy ES-module imports (which cannot inherit a query string) stay protected.
|
||||
$provided = (string) ($_GET['token'] ?? $_COOKIE[$this->cookieName()] ?? '');
|
||||
return $provided !== '' && hash_equals($this->ensureAccessToken(), $provided);
|
||||
}
|
||||
|
||||
private function cookieName(): string
|
||||
{
|
||||
return 'NFSC_' . $this->InstanceID;
|
||||
}
|
||||
|
||||
private function setAccessCookie(): void
|
||||
{
|
||||
setcookie($this->cookieName(), $this->ensureAccessToken(), [
|
||||
'expires' => 0,
|
||||
'path' => '/hook/' . $this->hookPath() . '/',
|
||||
'secure' => (($_SERVER['HTTPS'] ?? '') !== '' && ($_SERVER['HTTPS'] ?? '') !== 'off'),
|
||||
'httponly' => true,
|
||||
'samesite' => 'Strict'
|
||||
]);
|
||||
}
|
||||
|
||||
private function sendDesignerPage(): void
|
||||
{
|
||||
$this->setAccessCookie();
|
||||
$config = [
|
||||
'endpoint' => '/hook/' . $this->hookPath(),
|
||||
'token' => $this->ensureAccessToken(),
|
||||
'csrf' => $this->requestUser['csrf'],
|
||||
'user' => $this->publicAccess(),
|
||||
'language' => 'de',
|
||||
'title' => $this->viewTitle()
|
||||
];
|
||||
$asset = '/hook/' . $this->hookPath() . '/assets/nextfloor-designer.js?v=' . rawurlencode($this->moduleVersion())
|
||||
. '&token=' . rawurlencode($this->ensureAccessToken());
|
||||
$asset = '/hook/' . $this->hookPath() . '/assets/nextfloor-designer.js?v=' . rawurlencode($this->moduleVersion());
|
||||
header('Content-Type: text/html; charset=utf-8');
|
||||
header('Cache-Control: no-store');
|
||||
echo '<!doctype html><html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">'
|
||||
. '<title>' . htmlspecialchars($config['title'], ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '</title>'
|
||||
. '<style>html,body{width:100%;height:100%;margin:0;background:#111;color:#e1e1e1}body>nextfloor-panel,body>nextfloor-card{display:block;width:100%;height:100%}</style>'
|
||||
. '<style>html,body{width:100%;height:100%;margin:0;background:#111;color:#e1e1e1}body{display:flex;flex-direction:column}body>nextfloor-panel,body>nextfloor-card{display:block;flex:1;min-height:0;width:100%}.nf-session-bar{display:flex;align-items:center;gap:10px;padding:5px 12px;font:12px/1.4 system-ui;background:#20252d;border-bottom:1px solid #ffffff15}.nf-session-bar span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.nf-session-bar form{margin:0 0 0 auto;flex-shrink:0}.nf-session-bar button{font:inherit;padding:5px 12px;border:1px solid #ffffff25;border-radius:7px;background:#ffffff0a;color:inherit;cursor:pointer}</style>'
|
||||
. '</head><body><p style="padding:1rem;font-family:system-ui">NextFloor wird geladen …</p>'
|
||||
. '<script>window.__NEXTFLOOR_SYMCON__=' . json_encode($config, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) . ';</script>'
|
||||
. '<script type="module" src="' . htmlspecialchars($asset, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '"></script></body></html>';
|
||||
@@ -304,18 +323,23 @@ class NextFloor extends IPSModuleStrict
|
||||
$this->sendError(405, 'method_not_allowed');
|
||||
return;
|
||||
}
|
||||
$request = json_decode((string) file_get_contents('php://input'), true);
|
||||
if (!$this->validCsrf()) { $this->sendError(403, 'csrf_invalid'); return; }
|
||||
$limit = $this->isAdministrator() ? self::MAX_TRANSFER_BYTES : 65536;
|
||||
$raw = (string) file_get_contents('php://input', false, null, 0, $limit + 1);
|
||||
if (strlen($raw) > $limit) { $this->sendError(413, 'request_too_large'); return; }
|
||||
$request = json_decode($raw, true);
|
||||
if (!is_array($request) || !is_string($request['action'] ?? null)) {
|
||||
$this->sendError(400, 'invalid_request');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$this->authorizeApi($request['action'], $request);
|
||||
$result = match ($request['action']) {
|
||||
'bootstrap' => $this->bootstrap(),
|
||||
'variables/snapshot' => $this->variablesSnapshot((int) ($request['revision'] ?? -1)),
|
||||
'archive/trend' => $this->archiveTrend($request),
|
||||
'building/get' => ['building' => $this->building(), 'revision' => $this->ReadAttributeInteger('BuildingRevision'), 'version' => $this->moduleVersion()],
|
||||
'building/get' => ['building' => $this->visibleBuilding(), 'revision' => $this->ReadAttributeInteger('BuildingRevision'), 'version' => $this->moduleVersion()],
|
||||
'building/save' => ['revision' => $this->saveBuilding($this->arrayValue($request, 'building'))],
|
||||
'image/get' => $this->imageGet((string) ($request['image_id'] ?? '')),
|
||||
'image/set' => $this->imageSet((string) ($request['image_id'] ?? ''), (string) ($request['data'] ?? '')),
|
||||
@@ -336,6 +360,8 @@ class NextFloor extends IPSModuleStrict
|
||||
default => throw new RuntimeException('unknown_action')
|
||||
};
|
||||
$this->sendApiResult($result, ($request['transport'] ?? '') === 'nextfloor-chunks-v1');
|
||||
} catch (NextFloorDenied $error) {
|
||||
$this->sendError(403, $error->getMessage());
|
||||
} catch (InvalidArgumentException $error) {
|
||||
$this->sendError(400, $error->getMessage());
|
||||
} catch (RuntimeException $error) {
|
||||
@@ -345,9 +371,10 @@ class NextFloor extends IPSModuleStrict
|
||||
|
||||
private function bootstrap(): array
|
||||
{
|
||||
$objects = $this->objectTree();
|
||||
$objects = $this->visibleTree($this->objectTree());
|
||||
$stateRevision = $this->stateRevision($objects);
|
||||
return [
|
||||
'access' => $this->publicAccess(),
|
||||
'state_revision' => $stateRevision,
|
||||
'building_revision' => $this->ReadAttributeInteger('BuildingRevision'),
|
||||
'variables' => $objects['variables'],
|
||||
@@ -358,7 +385,7 @@ class NextFloor extends IPSModuleStrict
|
||||
|
||||
private function variablesSnapshot(int $knownRevision): array
|
||||
{
|
||||
$objects = $this->objectTree();
|
||||
$objects = $this->visibleTree($this->objectTree());
|
||||
$stateRevision = $this->stateRevision($objects);
|
||||
$result = [
|
||||
'state_revision' => $stateRevision,
|
||||
@@ -487,7 +514,7 @@ class NextFloor extends IPSModuleStrict
|
||||
'symcon_path' => $path,
|
||||
'symcon_profile' => $profile,
|
||||
'symcon_variable_type' => (int) $variable['VariableType'],
|
||||
'symcon_has_action' => ((int) ($variable['VariableCustomAction'] ?: $variable['VariableAction'])) !== 0,
|
||||
'symcon_has_action' => ((int) ($variable['VariableCustomAction'] ?: $variable['VariableAction'])) > 0,
|
||||
'symcon_formatted' => GetValueFormatted($variableID),
|
||||
'symcon_value' => $value,
|
||||
'device_class' => $this->deviceClassFor($profile, $name, $unit)
|
||||
@@ -648,6 +675,8 @@ class NextFloor extends IPSModuleStrict
|
||||
private function stateRevision(array $objects): int
|
||||
{
|
||||
$hash = hash('sha256', $this->encodeResponse($objects));
|
||||
// Distinct user scopes must not invalidate one global revision on every alternating poll.
|
||||
if ($this->requestUser !== null && !$this->isAdministrator()) return (int) hexdec(substr($hash, 0, 12));
|
||||
if (!hash_equals($this->ReadAttributeString('StateHash'), $hash)) {
|
||||
$this->WriteAttributeString('StateHash', $hash);
|
||||
$this->WriteAttributeInteger('StateRevision', $this->ReadAttributeInteger('StateRevision') + 1);
|
||||
@@ -1129,6 +1158,7 @@ class NextFloor extends IPSModuleStrict
|
||||
if (preg_match('/^[a-f0-9]{32}\.json$/D', basename($file)) !== 1 || is_link($file)) continue;
|
||||
if ((int) filemtime($file) < time() - self::TRANSFER_TTL) {
|
||||
unlink($file);
|
||||
if (is_file($file . '.owner') && !is_link($file . '.owner')) unlink($file . '.owner');
|
||||
} else {
|
||||
$active++;
|
||||
}
|
||||
@@ -1152,15 +1182,32 @@ class NextFloor extends IPSModuleStrict
|
||||
throw $error;
|
||||
}
|
||||
fclose($handle);
|
||||
if (file_put_contents($file . '.owner', $this->transferOwner(), LOCK_EX) === false) {
|
||||
unlink($file);
|
||||
throw new RuntimeException('transfer_storage_unavailable');
|
||||
}
|
||||
chmod($file . '.owner', 0600);
|
||||
return ['id' => $id, 'bytes' => $bytes, 'chunk_bytes' => self::TRANSFER_CHUNK_BYTES, 'chunks' => (int) ceil($bytes / self::TRANSFER_CHUNK_BYTES)];
|
||||
}
|
||||
|
||||
private function transferOwner(): string
|
||||
{
|
||||
return hash('sha256', (string) ($this->requestUser['session_id'] ?? 'internal') . ':' . (string) ($this->requestUser['epoch'] ?? ''));
|
||||
}
|
||||
|
||||
private function ownsTransfer(string $file): bool
|
||||
{
|
||||
$owner = $file . '.owner';
|
||||
return is_file($owner) && !is_link($owner) && hash_equals($this->transferOwner(), (string) file_get_contents($owner));
|
||||
}
|
||||
|
||||
private function readTransfer(string $id, int $index): array
|
||||
{
|
||||
$file = $this->transferFile($id);
|
||||
if (!is_file($file) || is_link($file)) throw new RuntimeException('transfer_not_found');
|
||||
if (!is_file($file) || is_link($file) || !$this->ownsTransfer($file)) throw new RuntimeException('transfer_not_found');
|
||||
if ((int) filemtime($file) < time() - self::TRANSFER_TTL) {
|
||||
unlink($file);
|
||||
unlink($file . '.owner');
|
||||
throw new RuntimeException('transfer_expired: Bitte erneut laden.');
|
||||
}
|
||||
$bytes = (int) filesize($file);
|
||||
@@ -1183,7 +1230,7 @@ class NextFloor extends IPSModuleStrict
|
||||
private function releaseTransfer(string $id): array
|
||||
{
|
||||
$file = $this->transferFile($id);
|
||||
if (is_file($file) && !is_link($file)) unlink($file);
|
||||
if (is_file($file) && !is_link($file) && $this->ownsTransfer($file)) { unlink($file); unlink($file . '.owner'); }
|
||||
return [];
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user