diff --git a/stage_ui/console_core/backend/app.py b/stage_ui/console_core/backend/app.py index eaf5fad..36e63f0 100644 --- a/stage_ui/console_core/backend/app.py +++ b/stage_ui/console_core/backend/app.py @@ -6,12 +6,17 @@ import json import os import shutil import re +import secrets import select +import threading import subprocess import sys import tempfile import time +import crypt +import spwd from datetime import datetime +from http.cookies import SimpleCookie from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from urllib.parse import parse_qs, urlparse from itscreen_registration import get_registration_status, register_device, reset_registration @@ -95,6 +100,30 @@ CAPTIVE_REDIRECT_PATHS = ( | WINDOWS_CAPTIVE_PATHS | GENERIC_CAPTIVE_PATHS ) +AUTH_USERNAME = "iomatex" +AUTH_COOKIE_NAME = "iomatex_edge_session" +AUTH_SESSION_TTL_SEC = 60 * 60 +PUBLIC_PATHS = { + "/", + "/index.html", + "/console.css", + "/console.i18n.js", + "/console.js", + "/logo.png", + "/g-box.png", + "/favicon.png", +} +PUBLIC_API_PATHS = { + "/api/auth/session", + "/api/auth/login", + "/api/auth/logout", +} +STATIC_NO_CACHE_HEADERS = { + "Cache-Control": "no-store, no-cache, must-revalidate", + "Pragma": "no-cache", +} +_AUTH_SESSIONS = {} +_AUTH_SESSIONS_LOCK = threading.Lock() def load_config(): @@ -124,6 +153,89 @@ def run(cmd, timeout=4): return 1, "", str(exc) +def _auth_now(): + return time.time() + + +def cleanup_auth_sessions(now=None): + current = _auth_now() if now is None else float(now) + with _AUTH_SESSIONS_LOCK: + expired = [token for token, session in _AUTH_SESSIONS.items() if float(session.get("expires_at", 0.0)) <= current] + for token in expired: + _AUTH_SESSIONS.pop(token, None) + + +def verify_system_password(username, password): + user = str(username or "").strip() + secret = str(password or "") + if user != AUTH_USERNAME or not secret: + return False + try: + shadow_hash = spwd.getspnam(user).sp_pwdp + except Exception: + return False + if not shadow_hash or shadow_hash in {"!", "*", "!!"}: + return False + try: + calculated = crypt.crypt(secret, shadow_hash) + except Exception: + return False + return bool(calculated) and secrets.compare_digest(calculated, shadow_hash) + + +def create_auth_session(username): + now = _auth_now() + token = secrets.token_urlsafe(32) + session = { + "username": str(username), + "created_at": now, + "expires_at": now + AUTH_SESSION_TTL_SEC, + "last_seen_at": now, + } + with _AUTH_SESSIONS_LOCK: + _AUTH_SESSIONS[token] = session + cleanup_auth_sessions(now) + return token, dict(session) + + +def get_auth_session(token, refresh=False): + value = str(token or "").strip() + if not value: + return None + now = _auth_now() + cleanup_auth_sessions(now) + with _AUTH_SESSIONS_LOCK: + session = _AUTH_SESSIONS.get(value) + if not session: + return None + if float(session.get("expires_at", 0.0)) <= now: + _AUTH_SESSIONS.pop(value, None) + return None + if refresh: + session["last_seen_at"] = now + session["expires_at"] = now + AUTH_SESSION_TTL_SEC + return dict(session) + + +def delete_auth_session(token): + value = str(token or "").strip() + if not value: + return + with _AUTH_SESSIONS_LOCK: + _AUTH_SESSIONS.pop(value, None) + + +def build_session_cookie(token, max_age_sec): + parts = [ + f"{AUTH_COOKIE_NAME}={token}", + "Path=/", + "HttpOnly", + "SameSite=Lax", + f"Max-Age={int(max_age_sec)}", + ] + return "; ".join(parts) + + def command_exists(name): return shutil.which(name) is not None @@ -1907,11 +2019,14 @@ class Handler(BaseHTTPRequestHandler): return False return True - def send_json(self, payload, code=200): + def send_json(self, payload, code=200, extra_headers=None): body = json.dumps(payload, indent=2).encode("utf-8") self.send_response(code) self.send_header("Content-Type", "application/json; charset=utf-8") self.send_header("Content-Length", str(len(body))) + if extra_headers: + for key, value in extra_headers.items(): + self.send_header(key, value) self.end_headers() self._write_response_body(body) @@ -1948,7 +2063,7 @@ class Handler(BaseHTTPRequestHandler): return None return data if isinstance(data, dict) else None - def send_file(self, path, content_type): + def send_file(self, path, content_type, extra_headers=None): try: with open(path, "rb") as fh: data = fh.read() @@ -1958,18 +2073,55 @@ class Handler(BaseHTTPRequestHandler): self.send_response(200) self.send_header("Content-Type", content_type) self.send_header("Content-Length", str(len(data))) + if extra_headers: + for key, value in extra_headers.items(): + self.send_header(key, value) self.end_headers() self._write_response_body(data) - def send_sse_headers(self): + def send_sse_headers(self, extra_headers=None): self.send_response(200) self.send_header("Content-Type", "text/event-stream; charset=utf-8") self.send_header("Cache-Control", "no-store, no-cache, must-revalidate") self.send_header("Pragma", "no-cache") self.send_header("Connection", "keep-alive") self.send_header("X-Accel-Buffering", "no") + if extra_headers: + for key, value in extra_headers.items(): + self.send_header(key, value) self.end_headers() + def parsed_cookies(self): + raw = self.headers.get("Cookie", "") + cookie = SimpleCookie() + if raw: + try: + cookie.load(raw) + except Exception: + return {} + return {key: morsel.value for key, morsel in cookie.items()} + + def auth_session(self, refresh=False): + cookies = self.parsed_cookies() + return get_auth_session(cookies.get(AUTH_COOKIE_NAME), refresh=refresh) + + def require_auth(self, parsed): + if parsed.path in PUBLIC_PATHS or parsed.path in PUBLIC_API_PATHS: + return True + session = self.auth_session(refresh=True) + if session: + self._auth_session = session + return True + self._auth_session = None + if parsed.path.startswith("/api/"): + self.send_json({"ok": False, "error": "Authorization required"}, code=401) + return False + if parsed.path == "/api/itscreen/logs/stream": + self.send_json({"ok": False, "error": "Authorization required"}, code=401) + return False + self.send_redirect("/") + return False + def stream_itscreen_logs(self): if not shutil.which("journalctl"): self.send_json({"ok": False, "error": "Logs are unavailable"}, code=503) @@ -2063,6 +2215,20 @@ class Handler(BaseHTTPRequestHandler): query = parse_qs(parsed.query or "") if self.handle_captive_portal_probe(parsed): return + if parsed.path == "/api/auth/session": + session = self.auth_session(refresh=True) + if not session: + self.send_json({"ok": True, "authenticated": False, "username": AUTH_USERNAME}) + return + self.send_json({ + "ok": True, + "authenticated": True, + "username": session.get("username", AUTH_USERNAME), + "expires_at": int(session.get("expires_at", 0)), + }) + return + if not self.require_auth(parsed): + return if parsed.path == "/api/status": self.send_json(build_status_payload()) return @@ -2183,16 +2349,16 @@ class Handler(BaseHTTPRequestHandler): self.send_json({"ok": False, "error": str(exc)}, code=500) return if parsed.path in ("/", "/index.html"): - self.send_file(os.path.join(PUBLIC_DIR, "index.html"), "text/html; charset=utf-8") + self.send_file(os.path.join(PUBLIC_DIR, "index.html"), "text/html; charset=utf-8", extra_headers=STATIC_NO_CACHE_HEADERS) return if parsed.path == "/console.css": - self.send_file(os.path.join(PUBLIC_DIR, "console.css"), "text/css; charset=utf-8") + self.send_file(os.path.join(PUBLIC_DIR, "console.css"), "text/css; charset=utf-8", extra_headers=STATIC_NO_CACHE_HEADERS) return if parsed.path == "/console.i18n.js": - self.send_file(os.path.join(PUBLIC_DIR, "console.i18n.js"), "application/javascript; charset=utf-8") + self.send_file(os.path.join(PUBLIC_DIR, "console.i18n.js"), "application/javascript; charset=utf-8", extra_headers=STATIC_NO_CACHE_HEADERS) return if parsed.path == "/console.js": - self.send_file(os.path.join(PUBLIC_DIR, "console.js"), "application/javascript; charset=utf-8") + self.send_file(os.path.join(PUBLIC_DIR, "console.js"), "application/javascript; charset=utf-8", extra_headers=STATIC_NO_CACHE_HEADERS) return if parsed.path == "/logo.png": self.send_file(os.path.join(PUBLIC_DIR, "logo.png"), "image/png") @@ -2211,6 +2377,30 @@ class Handler(BaseHTTPRequestHandler): def do_POST(self): parsed = urlparse(self.path) + if parsed.path == "/api/auth/login": + payload = self.read_json_body() + if payload is None: + self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400) + return + username = str(payload.get("username", AUTH_USERNAME)).strip() + password = str(payload.get("password", "")) + if not verify_system_password(username, password): + self.send_json({"ok": False, "error": "Invalid password"}, code=401) + return + token, session = create_auth_session(username) + self.send_json({ + "ok": True, + "authenticated": True, + "username": session.get("username", AUTH_USERNAME), + "expires_at": int(session.get("expires_at", 0)), + }, extra_headers={"Set-Cookie": build_session_cookie(token, AUTH_SESSION_TTL_SEC)}) + return + if parsed.path == "/api/auth/logout": + delete_auth_session(self.parsed_cookies().get(AUTH_COOKIE_NAME)) + self.send_json({"ok": True, "authenticated": False}, extra_headers={"Set-Cookie": build_session_cookie("", 0)}) + return + if not self.require_auth(parsed): + return if parsed.path == "/api/ap/password/change": payload = self.read_json_body() if payload is None: diff --git a/stage_ui/console_core/frontend/console.css b/stage_ui/console_core/frontend/console.css index 6bcb660..dff61e0 100644 --- a/stage_ui/console_core/frontend/console.css +++ b/stage_ui/console_core/frontend/console.css @@ -196,6 +196,9 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e .menuActionBtn.is-danger:hover:not(:disabled){ background:rgba(185,52,52,.10); } +.menuActionBtn[hidden]{ + display:none !important; +} .menuActionIcon{ width:18px; height:18px; @@ -721,6 +724,80 @@ html[dir="rtl"] .itscreenLogsActions{ .actionBtn.secondary{background:var(--button-secondary);color:var(--ink);border:1px solid var(--line)} .actionBtn.secondary:hover:not(:disabled){background:var(--button-secondary-hover)} .actionBtn:disabled{opacity:.5;cursor:not-allowed} +.authScreen{ + min-height:min(72vh,720px); + display:flex; + align-items:center; + justify-content:center; + padding:12px 0 24px; +} +.authCard{ + width:min(460px,100%); + padding:28px; + display:grid; + gap:20px; +} +.authCardLoading{ + min-height:260px; + align-content:center; +} +.authBrand{ + display:grid; + gap:8px; + justify-items:center; + text-align:center; +} +.authSessionHint{ + margin:0; + color:var(--muted); + font-size:13px; + line-height:1.45; +} +.authLogo{ + width:88px; + height:88px; + object-fit:contain; +} +.authBrand h2{ + margin:0; + font-size:30px; + line-height:1.05; + letter-spacing:-.03em; +} +.authForm{ + display:grid; + gap:12px; +} +.fieldLabel{ + font-size:13px; + font-weight:700; + color:var(--muted); +} +.textInput{ + width:100%; + border:1px solid var(--line); + border-radius:14px; + background:var(--surface-soft); + color:var(--ink); + padding:13px 14px; + font:inherit; +} +.textInput:focus-visible{ + outline:2px solid rgba(14,122,83,.22); + outline-offset:1px; +} +.passwordInputRow{ + display:grid; + grid-template-columns:minmax(0,1fr) auto; + gap:10px; + align-items:center; +} +.passwordToggleBtn{ + min-width:88px; +} +.authSubmitBtn{ + margin-top:4px; +} .serviceActionRow{align-items:center} .actionBadge{ display:inline-flex;align-items:center;border-radius:999px;padding:6px 10px; @@ -1059,6 +1136,14 @@ html[dir="rtl"] .itscreenLogsActions{ .writeLogCard{ margin-top:14px; } +.panel.is-disabled{ + opacity:.6; +} +.panel.is-disabled .writeConfigSection, +.panel.is-disabled .writeLogCard, +.panel.is-disabled .actionRow{ + pointer-events:none; +} .modbusWriteLogBody{ min-height:160px; max-height:160px; @@ -1072,6 +1157,33 @@ html[dir="rtl"] .itscreenLogsActions{ font-size:12px; line-height:1.5; } +.modalBackdrop{ + position:fixed; + inset:0; + display:flex; + align-items:center; + justify-content:center; + padding:20px; + background:rgba(8,12,18,.56); + z-index:1200; +} +.modalCard{ + width:min(520px,100%); + padding:20px; + border:1px solid var(--line); + border-radius:18px; + background:var(--panel); + box-shadow:0 24px 80px rgba(0,0,0,.28); +} +.modalCard h3{ + margin:0 0 10px; + font-size:20px; +} +.modalCard p{ + margin:0 0 18px; + color:var(--muted); + line-height:1.5; +} @keyframes pulse{ 0%,100%{opacity:.35;transform:scale(.9)} 50%{opacity:1;transform:scale(1)} @@ -1098,6 +1210,8 @@ html[dir="rtl"] .itscreenLogsActions{ .itscreenLogsActions{justify-content:flex-start} .modbusGrid{grid-template-columns:1fr} .modbusDiscoveryGrid{grid-template-columns:1fr} + .passwordInputRow{grid-template-columns:1fr} + .authCard{padding:22px} } @media (max-width:680px){ .menuToggleBtn{ diff --git a/stage_ui/console_core/frontend/console.js b/stage_ui/console_core/frontend/console.js index cce023e..e311ddb 100644 --- a/stage_ui/console_core/frontend/console.js +++ b/stage_ui/console_core/frontend/console.js @@ -10,6 +10,8 @@ languageSelect: document.getElementById("languageSelect"), themeToggleBtn: document.getElementById("themeToggleBtn"), themeToggleIcon: document.getElementById("themeToggleIcon"), + logoutBtn: document.getElementById("logoutBtn"), + logoutMenuLabel: document.getElementById("logoutMenuLabel"), tabs: Array.from(document.querySelectorAll("[data-tab]")), brandEyebrow: document.getElementById("brandEyebrow"), heroTitle: document.getElementById("heroTitle"), @@ -212,6 +214,9 @@ selectedDevice: null, currentConfig: null, lastWriteResult: null, + readConfigStatus: "idle", + readConfigMessage: "", + confirmStopItscreenOpen: false, writeLog: [], writeForm: { slave: "", @@ -254,6 +259,17 @@ busyTarget: "", results: {} }, + auth: { + loading: true, + authenticated: false, + username: "iomatex", + password: "", + showPassword: false, + busy: false, + error: "", + info: "", + expiresAt: 0 + }, menuOpen: false, rebootPending: false, isPolling: false @@ -438,6 +454,7 @@ if (nodes.themeMenuLabel) nodes.themeMenuLabel.textContent = t("Theme"); if (nodes.refreshMenuLabel) nodes.refreshMenuLabel.textContent = t("Refresh"); if (nodes.rebootMenuLabel) nodes.rebootMenuLabel.textContent = t("Reboot"); + if (nodes.logoutMenuLabel) nodes.logoutMenuLabel.textContent = t("Logout"); if (nodes.tabHealth) nodes.tabHealth.textContent = t("Health"); if (nodes.tabNetwork) nodes.tabNetwork.textContent = t("Network"); if (nodes.tabModbus) nodes.tabModbus.textContent = t("Modbus"); @@ -464,6 +481,10 @@ } function syncActionMenu() { + const authenticated = !!state.auth.authenticated; + if (nodes.refreshBtn) nodes.refreshBtn.hidden = !authenticated; + if (nodes.rebootBtn) nodes.rebootBtn.hidden = !authenticated; + if (nodes.logoutBtn) nodes.logoutBtn.hidden = !authenticated; const isOpen = !!state.menuOpen; if (nodes.actionMenu) nodes.actionMenu.hidden = !isOpen; if (nodes.menuBackdrop) nodes.menuBackdrop.hidden = !isOpen; @@ -486,6 +507,46 @@ syncActionMenu(); } + function setPrimaryUiLocked(locked) { + const hide = !!locked; + const tabsNode = document.querySelector(".tabs"); + const identityPanel = document.querySelector(".identityPanel"); + if (tabsNode) tabsNode.hidden = hide; + if (identityPanel) identityPanel.hidden = hide; + if (nodes.refreshBtn) nodes.refreshBtn.disabled = hide || state.rebootPending; + if (nodes.rebootBtn) nodes.rebootBtn.disabled = hide || state.rebootPending; + } + + function setAuthRequired(message) { + state.auth.loading = false; + state.auth.authenticated = false; + state.auth.busy = false; + state.auth.password = ""; + state.auth.showPassword = false; + state.auth.error = ""; + state.auth.info = message || t("Authorization required"); + state.auth.expiresAt = 0; + state.itscreen.loading = false; + deactivateItscreenLogs({ status: "disconnected" }); + closeActionMenu(); + setPrimaryUiLocked(true); + renderActiveTab(); + } + + function applyAuthSession(payload, message) { + state.auth.loading = false; + state.auth.authenticated = !!(payload && payload.authenticated); + state.auth.busy = false; + state.auth.error = ""; + state.auth.info = message || ""; + state.auth.password = ""; + state.auth.showPassword = false; + state.auth.username = textValue(payload && payload.username, "iomatex"); + state.auth.expiresAt = Number(payload && payload.expires_at) || 0; + setPrimaryUiLocked(!state.auth.authenticated); + syncActionMenu(); + } + function applyTheme(theme) { state.theme = theme === "dark" ? "dark" : "light"; document.documentElement.setAttribute("data-theme", state.theme); @@ -555,6 +616,15 @@ return `${date.getUTCFullYear()}-${pad(date.getUTCMonth() + 1)}-${pad(date.getUTCDate())} ${pad(date.getUTCHours())}:${pad(date.getUTCMinutes())}:${pad(date.getUTCSeconds())} (UTC)`; } + function formatTimestamp(value) { + const text = (value ?? "").toString().trim(); + if (!text) return "-"; + const date = new Date(text); + if (Number.isNaN(date.getTime())) return text.replace("T", " ").replace(/\.\d+Z?$/, "").replace(/Z$/, ""); + const pad = (number) => String(number).padStart(2, "0"); + return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`; + } + function showToast(kind, message) { if (!nodes.toastStack || !message) return; const toast = document.createElement("div"); @@ -959,7 +1029,7 @@ return `${days}d ${hours}h`; } - function formatTimestamp(value) { + function formatEpochTimestamp(value) { const ms = Number(value); if (!Number.isFinite(ms) || ms <= 0) return "—"; const date = new Date(ms); @@ -969,7 +1039,7 @@ } function formatHealthLastStart(value) { - const formatted = formatTimestamp(value); + const formatted = formatEpochTimestamp(value); return formatted === "—" ? t("unknown") : formatted; } @@ -1876,12 +1946,12 @@
${esc(t("Server sync"))}
${esc(t("Server sync interval"))}
${esc(formatInterval(runtime.update_interval, t("Disabled")))}
-
${esc(t("Last contact with server"))}
${esc(formatTimestamp(runtime.last_contact_ts))}
-
${esc(t("Next scheduled contact"))}
${esc(formatTimestamp(runtime.next_contact_ts))}
+
${esc(t("Last contact with server"))}
${esc(formatEpochTimestamp(runtime.last_contact_ts))}
+
${esc(t("Next scheduled contact"))}
${esc(formatEpochTimestamp(runtime.next_contact_ts))}
${esc(t("Auto reboot interval"))}
${esc(runtime.enable_reboot_repeat === false ? t("Disabled") : (runtime.enable_reboot_repeat === true ? formatRepeatInterval(runtime.reboot_repeat_time) : "—"))}
${esc(t("Daily reboot time"))}
${esc(runtime.enable_reboot === false ? t("Disabled") : (runtime.enable_reboot === true ? textValue(runtime.reboot_time, t("Not set")) : "—"))}
-
${esc(t("Next shutdown"))}
${esc(runtime.enable_off_time === false ? t("Disabled") : (runtime.enable_off_time === true ? (runtime.next_off_time === 0 ? t("Not scheduled") : formatTimestamp(runtime.next_off_time)) : "—"))}
-
${esc(t("Next startup"))}
${esc(runtime.enable_on_time === false ? t("Disabled") : (runtime.enable_on_time === true ? (runtime.next_on_time === 0 ? t("Not scheduled") : formatTimestamp(runtime.next_on_time)) : "—"))}
+
${esc(t("Next shutdown"))}
${esc(runtime.enable_off_time === false ? t("Disabled") : (runtime.enable_off_time === true ? (runtime.next_off_time === 0 ? t("Not scheduled") : formatEpochTimestamp(runtime.next_off_time)) : "—"))}
+
${esc(t("Next startup"))}
${esc(runtime.enable_on_time === false ? t("Disabled") : (runtime.enable_on_time === true ? (runtime.next_on_time === 0 ? t("Not scheduled") : formatEpochTimestamp(runtime.next_on_time)) : "—"))}
@@ -2170,11 +2240,7 @@ if (logs.request) return logs.request; logs.request = (async () => { try { - const response = await fetch(`/api/itscreen/logs?lines=${encodeURIComponent(String(lines))}`, { cache: "no-store" }); - const payload = await response.json().catch(() => ({ ok: false, error: t("Logs are unavailable") })); - if (!response.ok || payload.ok === false) { - throw new Error(payload.error || t("Logs are unavailable")); - } + const payload = await fetchJson(`/api/itscreen/logs?lines=${encodeURIComponent(String(lines))}`, { cache: "no-store" }); const incoming = Array.isArray(payload.lines) ? payload.lines.map((line) => (line ?? "").toString()) : []; logs.buffer = replace ? trimItscreenLogBuffer(incoming) : trimItscreenLogBuffer(logs.buffer.concat(incoming)); logs.available = true; @@ -2366,12 +2432,31 @@ return ""; } + function modbusHasValidCurrentConfig() { + const currentConfig = modbusState().currentConfig; + return !!(currentConfig && currentConfig.ok !== false && textValue(currentConfig.status, "ok") === "ok" && currentConfig.current_config); + } + + function modbusWriteAccessState() { + const log = modbusState(); + if (!log.selectedDevice) { + return { enabled: false, reason: t("Select a device to enable write"), tone: "warn" }; + } + if (!modbusHasValidCurrentConfig()) { + if (log.readConfigStatus === "error" && log.readConfigMessage) { + return { enabled: false, reason: log.readConfigMessage, tone: "error" }; + } + return { enabled: false, reason: t("Read configuration to enable write"), tone: "warn" }; + } + return { enabled: true, reason: "", tone: "success" }; + } + function modbusCanWrite() { const log = modbusState(); const capabilities = modbusWriteCapabilities(); const strategy = normalizeModbusWriteStrategy(log.writeForm.strategy); const strategyAllowed = strategy === "id" ? capabilities.supportsIdWrite : capabilities.supportsSerialWrite; - return !!(log.currentConfig && log.selectedDevice && strategyAllowed && !modbusWriteValidationError()); + return !!(modbusWriteAccessState().enabled && strategyAllowed && !modbusWriteValidationError()); } function modbusBusy(action) { @@ -2468,21 +2553,23 @@ const strategySelect = document.getElementById("modbusWriteStrategySelect"); const applyBtn = document.getElementById("modbusWriteApplyBtn"); const errorNode = document.getElementById("modbusWriteError"); + const writeAccess = modbusWriteAccessState(); const capabilities = modbusWriteCapabilities(); const strategy = normalizeModbusWriteStrategy(modbusState().writeForm.strategy); const validationError = modbusWriteValidationError(); if (strategySelect) strategySelect.value = strategy; if (slaveInput) { - slaveInput.disabled = !capabilities.supportsIdWrite || strategy !== "id"; + slaveInput.disabled = !writeAccess.enabled || !capabilities.supportsIdWrite || strategy !== "id"; if (typeof slaveInput.setCustomValidity === "function") { slaveInput.setCustomValidity(slaveInput.disabled ? "" : modbusWriteSlaveValidationError(modbusState().writeForm.slave)); } } - if (baudSelect) baudSelect.disabled = !capabilities.supportsSerialWrite || strategy !== "baud"; + if (strategySelect) strategySelect.disabled = !writeAccess.enabled; + if (baudSelect) baudSelect.disabled = !writeAccess.enabled || !capabilities.supportsSerialWrite || strategy !== "baud"; if (applyBtn) applyBtn.disabled = !!(modbusBusy("write_config") || !modbusCanWrite()); if (errorNode) { - errorNode.textContent = validationError || ""; - errorNode.hidden = !validationError; + errorNode.textContent = validationError || writeAccess.reason || ""; + errorNode.hidden = !(validationError || writeAccess.reason); } } @@ -2571,6 +2658,7 @@ function renderModbusFoundDevices() { const devices = modbusState().discovery.devices || []; + const log = modbusState(); if (!devices.length) { return `
${esc(t("No devices discovered yet."))}
`; } @@ -2591,7 +2679,7 @@ ${devices.map((item, index) => ` - + ${esc(item.port)} ${esc(item.family_display_name || item.family)} ${esc(String(item.slave))} @@ -2602,7 +2690,7 @@
- +
@@ -2623,12 +2711,39 @@ { label: t("Current baud"), value: textValue(currentConfig.current_config && currentConfig.current_config.baud, t("Unknown")) }, { label: t("Current parity"), value: textValue(currentConfig.current_config && currentConfig.current_config.parity, t("Unknown")) }, { label: t("Config register values"), value: JSON.stringify(currentConfig.raw_values || {}) }, - { label: t("Last successful read"), value: textValue(currentConfig.last_successful_read, "-") }, - { label: t("Last communication timestamp"), value: textValue(currentConfig.last_communication_timestamp, "-") } + { label: t("Last successful read"), value: formatTimestamp(currentConfig.last_successful_read) }, + { label: t("Last communication timestamp"), value: formatTimestamp(currentConfig.last_communication_timestamp) } ]; return `
${renderKeyValueRows(rows)}
`; } + function renderModbusReadConfigState() { + const log = modbusState(); + if (log.readConfigStatus === "success" && log.readConfigMessage) { + return ``; + } + if (log.readConfigStatus === "error" && log.readConfigMessage) { + return ``; + } + return ""; + } + + function renderModbusReadConfigDialog() { + if (!modbusState().confirmStopItscreenOpen) return ""; + return ` + + `; + } + function modbusWriteStatusMeta() { const result = modbusState().lastWriteResult; if (!result) return ""; @@ -2682,6 +2797,7 @@ const portInfo = modbusSelectedPortStatus() || {}; const zeroBased = !!profileTransport.zero_based; const scanRunning = modbusScanRunning(); + const writeAccess = modbusWriteAccessState(); const scanStatus = textValue(log.discovery.message, scanRunning ? t("Scanning in progress. It may take some minutes.") : ""); const scanLogLines = modbusDiscoveryLogLines(); const writeCurrentConfig = modbusWriteCurrentConfigView(); @@ -2741,7 +2857,6 @@
- ${scanRunning ? `
${esc(t("Scanning in progress. It may take some minutes."))}${log.discovery.currentSlave ? ` ${esc(t("Current slave"))}: ${esc(String(log.discovery.currentSlave))}` : ""}${log.discovery.total ? ` (${esc(String(log.discovery.checked || 0))}/${esc(String(log.discovery.total))})` : ""}
` : ""}
${scanStatus && !scanRunning ? `
${esc(scanStatus)}
` : ""} @@ -2759,13 +2874,15 @@

${esc(t("Current Config"))}

+ ${renderModbusReadConfigState()} ${renderModbusCurrentConfig()}
-
+

${esc(t("Configuration Write"))}

${modbusWriteStatusMeta()} ${!supportsSerialWrite ? `
${esc(t("Baud rate and parity write are not configured for this family yet. Slave ID write is available."))}
` : ""} + ${writeAccess.enabled ? "" : ``}
${esc(t("Current config"))}
@@ -2782,8 +2899,8 @@
${esc(modbusWriteValidationError())}
-
${esc(t("Write is disabled until a device has been selected and its current config has been read."))}
+
${esc(writeAccess.enabled ? t("Configuration write is enabled.") : t("Write is disabled until a device has been selected and its current config has been read."))}
${renderModbusWriteProcessLog()}
@@ -2876,11 +2993,25 @@ ${renderModbusLogPanel()}
+ ${renderModbusReadConfigDialog()} `; } function renderActiveTab() { + if (state.auth.loading) { + setPrimaryUiLocked(true); + nodes.tabs.forEach((button) => button.classList.remove("is-active")); + nodes.content.innerHTML = renderAuthLoadingScreen(); + return; + } + if (!state.auth.authenticated) { + setPrimaryUiLocked(true); + nodes.tabs.forEach((button) => button.classList.remove("is-active")); + nodes.content.innerHTML = renderLoginScreen(); + return; + } + setPrimaryUiLocked(false); if (state.activeTab === "tscreen") { captureItscreenLogViewport(); } @@ -2909,6 +3040,53 @@ nodes.content.innerHTML = renderHealthTab(); } + function renderAuthLoadingScreen() { + return ` +
+
+
+ +
${esc(t("IOMATEX EDGE"))}
+

${esc(t("WEB UI"))}

+

${esc(t("Checking session..."))}

+
+
+
+ `; + } + + function renderLoginScreen() { + const auth = state.auth; + const infoMessage = !auth.loading && auth.info ? auth.info : ""; + const errorMessage = auth.error ? auth.error : ""; + const disabled = auth.loading || auth.busy; + return ` +
+
+
+ +
${esc(t("IOMATEX EDGE"))}
+

${esc(t("WEB UI"))}

+

${esc(t("Use device credentials to continue"))}

+

${esc(t("Session stays active for up to 1 hour after your last action."))}

+
+
+ + + +
+ + +
+ ${infoMessage ? `` : ""} + ${errorMessage ? `` : ""} + +
+
+
+ `; + } + function updateIdentity(identity) { const safe = identity || {}; nodes.edgeId.textContent = safe.serial_number || "-"; @@ -2922,9 +3100,41 @@ } } + async function loadAuthSession(options = {}) { + const silent = !!options.silent; + if (!silent) { + state.auth.loading = true; + state.auth.error = ""; + state.auth.info = ""; + renderActiveTab(); + } + try { + const response = await fetch("/api/auth/session", { cache: "no-store" }); + const payload = await response.json().catch(() => ({ ok: false, authenticated: false })); + if (!response.ok) { + throw new Error(payload.error || `HTTP ${response.status}`); + } + if (payload.authenticated) { + applyAuthSession(payload); + } else { + setAuthRequired(silent ? "" : t("Authorization required")); + } + return payload; + } catch (error) { + setAuthRequired(t("Authorization required")); + throw error; + } + } + async function fetchJson(url, options) { const response = await fetch(url, options || { cache: "no-store" }); const payload = await response.json().catch(() => ({})); + if (response.status === 401) { + if (String(url || "").indexOf("/api/auth/login") !== 0) { + setAuthRequired(t("Session expired, please sign in again")); + } + throw new Error(payload.error || t("Session expired, please sign in again")); + } if (!response.ok || payload.ok === false) { throw new Error(payload.error || `HTTP ${response.status}`); } @@ -3017,34 +3227,12 @@ } async function requestItscreenStatus() { - const response = await fetch("/api/itscreen/status", { cache: "no-store" }); - const payload = await response.json().catch(() => ({ - ok: false, - error: t("It-screen status is unavailable"), - details: t("Invalid backend response") - })); - if (!response.ok && payload.ok !== false) { - payload.ok = false; - payload.error = payload.error || `HTTP ${response.status}`; - } - return payload; + return fetchJson("/api/itscreen/status", { cache: "no-store" }); } async function requestItscreenRuntime() { - const response = await fetch("/api/itscreen/runtime", { cache: "no-store" }); - const payload = await response.json().catch(() => ({ - status: "error", - message: t("invalid runtime response"), - current_time: "", - service_started_at: null, - uptime_seconds: null, - service_state: "unknown", - registration: { registered: null, server: null }, - sync: { interval_sec: null, interval_human: null, last_contact_ts: null, last_contact_iso: null, next_contact_ts: null, next_contact_iso: null }, - schedule: { shutdown_enabled: null, shutdown_time: null, startup_enabled: null, startup_time: null, next_shutdown_ts: null, next_shutdown_iso: null, next_startup_ts: null, next_startup_iso: null }, - reboot: { enabled: null, repeat_enabled: null, repeat_interval: null, daily_time: null } - })); - if (!response.ok || payload.status === "not_installed" || payload.status === "error") { + const payload = await fetchJson("/api/itscreen/runtime", { cache: "no-store" }); + if (payload.status === "not_installed" || payload.status === "error") { return { current_time: textValue(payload.current_time, ""), service_started_at: null, @@ -3167,6 +3355,10 @@ } async function loadForActiveTab(options = {}) { + if (!state.auth.authenticated) { + renderActiveTab(); + return; + } const preserveEditing = !!options.preserveEditing; nodes.refreshBtn.disabled = true; if (nodes.rebootBtn) nodes.rebootBtn.disabled = state.rebootPending; @@ -3679,6 +3871,9 @@ log.currentConfig = null; log.selectedDevice = null; log.lastWriteResult = null; + log.readConfigStatus = "idle"; + log.readConfigMessage = ""; + log.confirmStopItscreenOpen = false; const profile = modbusSelectedProfile(); if (profile && profile.transport) { log.discovery.baud = String(profile.transport.default_baud || 9600); @@ -3755,6 +3950,8 @@ if (!item) return; log.selectedDevice = item; log.currentConfig = null; + log.readConfigStatus = "idle"; + log.readConfigMessage = ""; log.writeForm.slave = String(item.slave); log.writeForm.baud = String(item.baud); log.writeForm.parity = item.parity; @@ -3891,13 +4088,31 @@ await window.__modbusReadConfig(); }; - window.__modbusReadConfig = async function () { + async function getItscreenServiceStatusFresh() { + try { + const payload = await fetchJson("/api/itscreen/status", { cache: "no-store" }); + state.itscreen.data = payload; + state.itscreen.error = ""; + state.itscreen.details = ""; + return payload.service || {}; + } catch (error) { + return itscreenService() || {}; + } + } + + async function executeModbusReadConfig(options = {}) { const log = modbusState(); - const current = modbusCurrentConnection(); log.busyAction = "read_config"; log.error = ""; + log.readConfigStatus = "loading"; + log.readConfigMessage = ""; if (state.activeTab === "modbus") renderActiveTab(); try { + if (options.stopItscreenFirst) { + log.stopItscreen = true; + appendModbusLog(t("it-screen client will be stopped for Modbus access"), "warn"); + } + const current = modbusCurrentConnection(); await modbusEnsureSession(); const payload = await fetchJson("/api/modbus/read-config", { method: "POST", @@ -3923,16 +4138,44 @@ log.writeForm.baud = String(payload.current && payload.current.baud || current.baud); log.writeForm.parity = textValue(payload.current && payload.current.parity, current.parity); log.writeForm.strategy = normalizeModbusWriteStrategy(log.writeForm.strategy); + log.readConfigStatus = "success"; + log.readConfigMessage = t("Current config read completed"); ingestModbusPayload(payload); - appendModbusLog(t("Current config read completed"), "success"); + appendModbusLog(log.readConfigMessage, "success"); + showToast("success", log.readConfigMessage); } catch (error) { log.error = error.message || t("Failed to read current config"); + log.currentConfig = null; + log.readConfigStatus = "error"; + log.readConfigMessage = log.error; appendModbusLog(log.error, "error"); showToast("error", log.error); } finally { log.busyAction = ""; if (state.activeTab === "modbus") renderActiveTab(); } + } + + window.__modbusCancelReadConfigPrompt = function () { + modbusState().confirmStopItscreenOpen = false; + if (state.activeTab === "modbus") renderActiveTab(); + }; + + window.__modbusConfirmReadConfigPrompt = async function () { + modbusState().confirmStopItscreenOpen = false; + if (state.activeTab === "modbus") renderActiveTab(); + await executeModbusReadConfig({ stopItscreenFirst: true }); + }; + + window.__modbusReadConfig = async function () { + const log = modbusState(); + const service = await getItscreenServiceStatusFresh(); + if (service && service.active) { + log.confirmStopItscreenOpen = true; + if (state.activeTab === "modbus") renderActiveTab(); + return; + } + await executeModbusReadConfig(); }; window.__modbusApplyConfig = async function () { @@ -3959,7 +4202,7 @@ log.writeForm.slave = modbusCurrentSlaveFallback(); } const writeTarget = modbusWriteTargetFromForm(current); - const response = await fetch("/api/modbus/write-config", { + const payload = await fetchJson("/api/modbus/write-config", { method: "POST", cache: "no-store", headers: { "Content-Type": "application/json" }, @@ -3975,10 +4218,6 @@ strategy: modbusWriteStrategyForPayload(writeTarget.strategy) }) }); - const payload = await response.json().catch(() => ({})); - if (!response.ok && payload.ok !== false) { - throw new Error(payload.error || `HTTP ${response.status}`); - } log.lastWriteResult = payload; ingestModbusPayload(payload); ingestModbusWritePayload(payload); @@ -4087,8 +4326,73 @@ } }; + window.__authSetField = function (field, value) { + if (field !== "username" && field !== "password") return; + state.auth[field] = (value ?? "").toString(); + state.auth.error = ""; + state.auth.info = ""; + }; + + window.__authTogglePassword = function () { + state.auth.showPassword = !state.auth.showPassword; + renderActiveTab(); + }; + + window.__authSubmit = async function (event) { + if (event && typeof event.preventDefault === "function") event.preventDefault(); + if (state.auth.busy || state.auth.loading) return; + const username = textValue(state.auth.username, "iomatex"); + const password = state.auth.password || ""; + if (!password.trim()) { + state.auth.error = t("Invalid password"); + renderActiveTab(); + return; + } + state.auth.busy = true; + state.auth.error = ""; + state.auth.info = ""; + renderActiveTab(); + try { + const payload = await fetchJson("/api/auth/login", { + method: "POST", + cache: "no-store", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ username, password }) + }); + applyAuthSession(payload); + await loadForActiveTab(); + if (state.activeTab === "tscreen") { + activateItscreenLogs().catch(() => {}); + } + } catch (error) { + state.auth.busy = false; + state.auth.authenticated = false; + state.auth.error = error.message || t("Invalid password"); + renderActiveTab(); + } + }; + + window.__logout = async function () { + if (state.auth.busy) return; + state.auth.busy = true; + syncActionMenu(); + try { + await fetchJson("/api/auth/logout", { + method: "POST", + cache: "no-store", + headers: { "Content-Type": "application/json" }, + body: "{}" + }); + } catch (error) { + // Logout should still clear the local UI state even if the backend session already expired. + } finally { + setAuthRequired(""); + } + }; + nodes.tabs.forEach((button) => { button.addEventListener("click", async () => { + if (!state.auth.authenticated) return; const nextTab = button.dataset.tab; if (!nextTab || nextTab === state.activeTab) return; if (state.activeTab === "tscreen" && nextTab !== "tscreen") { @@ -4104,11 +4408,16 @@ if (nodes.refreshBtn) { nodes.refreshBtn.addEventListener("click", async () => { + if (!state.auth.authenticated) return; closeActionMenu(); await loadForActiveTab(); }); } if (nodes.rebootBtn) nodes.rebootBtn.addEventListener("click", window.__rebootDevice); + if (nodes.logoutBtn) nodes.logoutBtn.addEventListener("click", async () => { + closeActionMenu(); + await window.__logout(); + }); if (nodes.themeToggleBtn) nodes.themeToggleBtn.addEventListener("click", toggleTheme); if (nodes.languageSelect) { nodes.languageSelect.addEventListener("change", (event) => { @@ -4154,6 +4463,7 @@ deactivateItscreenLogs(); return; } + if (!state.auth.authenticated) return; if (state.activeTab === "tscreen") { activateItscreenLogs().catch(() => {}); } @@ -4164,12 +4474,18 @@ applyLanguage(state.language); applyTheme(loadThemePreference()); syncActionMenu(); - loadForActiveTab().then(() => { - if (state.activeTab === "tscreen") { - activateItscreenLogs().catch(() => {}); - } - }); + setPrimaryUiLocked(true); + renderActiveTab(); + loadAuthSession().then(() => { + if (!state.auth.authenticated) return; + return loadForActiveTab().then(() => { + if (state.activeTab === "tscreen") { + activateItscreenLogs().catch(() => {}); + } + }); + }).catch(() => {}); setInterval(() => { + if (!state.auth.authenticated) return; loadForActiveTab({ preserveEditing: true }).catch(() => {}); }, 15000); })(); diff --git a/stage_ui/console_core/frontend/index.html b/stage_ui/console_core/frontend/index.html index 5d10997..8090674 100644 --- a/stage_ui/console_core/frontend/index.html +++ b/stage_ui/console_core/frontend/index.html @@ -78,6 +78,10 @@ Reboot +
diff --git a/stage_ui/ui_installer.sh b/stage_ui/ui_installer.sh index a2425b3..5fc512f 100644 --- a/stage_ui/ui_installer.sh +++ b/stage_ui/ui_installer.sh @@ -73,30 +73,51 @@ rollback_deploy() { } wait_for_local_http() { - local attempt - for attempt in $(seq 1 30); do + local attempt max_attempts url_root url_auth code_root code_auth + max_attempts=45 + url_root="http://127.0.0.1:${APP_PORT}/" + url_auth="http://127.0.0.1:${APP_PORT}/api/auth/session" + echo "Smoke-check: waiting for local HTTP readiness on ${url_root}" + for attempt in $(seq 1 "${max_attempts}"); do if ! systemctl is-active --quiet "${SERVICE_NAME}"; then + echo "Smoke-check attempt ${attempt}/${max_attempts}: ${SERVICE_NAME} is not active yet" sleep 1 continue fi - if ! ss -ltnp 2>/dev/null | grep -q ':80 '; then + if ! ss -ltnp 2>/dev/null | grep -q ":${APP_PORT} "; then + echo "Smoke-check attempt ${attempt}/${max_attempts}: nothing is listening on :${APP_PORT} yet" sleep 1 continue fi - if python3 - <<'PY' >/dev/null 2>&1 -import sys -import urllib.request -try: - with urllib.request.urlopen("http://127.0.0.1/api/status", timeout=5) as response: - sys.exit(0 if response.status == 200 else 1) -except Exception: - sys.exit(1) -PY - then + code_root="$(curl -sS -o /tmp/iomatex-console-smoke-root.$$ -w '%{http_code}' --max-time 5 "${url_root}" 2>/tmp/iomatex-console-smoke-root.err || true)" + code_auth="$(curl -sS -o /tmp/iomatex-console-smoke-auth.$$ -w '%{http_code}' --max-time 5 "${url_auth}" 2>/tmp/iomatex-console-smoke-auth.err || true)" + echo "Smoke-check attempt ${attempt}/${max_attempts}: GET ${url_root} -> ${code_root:-curl_failed}; GET ${url_auth} -> ${code_auth:-curl_failed}" + if [ "${code_root}" = "200" ] && [ "${code_auth}" = "200" ]; then + if grep -Eq 'IOMATEX Console|console\.js|console\.css' "/tmp/iomatex-console-smoke-root.$$"; then + echo "Smoke-check passed: public shell and unauthenticated auth endpoint are reachable" + rm -f "/tmp/iomatex-console-smoke-root.$$" "/tmp/iomatex-console-smoke-auth.$$" "/tmp/iomatex-console-smoke-root.err" "/tmp/iomatex-console-smoke-auth.err" + return 0 + fi + echo "Smoke-check attempt ${attempt}/${max_attempts}: root page returned 200 but did not look like the WEB UI shell yet" + elif [ "${code_root}" = "200" ] && [ "${code_auth}" = "401" -o "${code_auth}" = "302" ]; then + echo "Smoke-check passed: login/public shell is up and auth flow responded with ${code_auth}" + rm -f "/tmp/iomatex-console-smoke-root.$$" "/tmp/iomatex-console-smoke-auth.$$" "/tmp/iomatex-console-smoke-root.err" "/tmp/iomatex-console-smoke-auth.err" return 0 fi sleep 1 done + echo "Smoke-check failed after ${max_attempts} attempts" >&2 + echo "Listener snapshot on :${APP_PORT}:" >&2 + ss -ltnp 2>/dev/null | grep ":${APP_PORT} " >&2 || echo " nothing listening on :${APP_PORT}" >&2 + if [ -f "/tmp/iomatex-console-smoke-root.err" ] && [ -s "/tmp/iomatex-console-smoke-root.err" ]; then + echo "Last curl stderr for ${url_root}:" >&2 + cat "/tmp/iomatex-console-smoke-root.err" >&2 || true + fi + if [ -f "/tmp/iomatex-console-smoke-auth.err" ] && [ -s "/tmp/iomatex-console-smoke-auth.err" ]; then + echo "Last curl stderr for ${url_auth}:" >&2 + cat "/tmp/iomatex-console-smoke-auth.err" >&2 || true + fi + rm -f "/tmp/iomatex-console-smoke-root.$$" "/tmp/iomatex-console-smoke-auth.$$" "/tmp/iomatex-console-smoke-root.err" "/tmp/iomatex-console-smoke-auth.err" return 1 } @@ -153,7 +174,7 @@ done step "Ensure runtime packages exist" apt-get update -apt-get install -y python3 python3-pil python3-paho-mqtt network-manager iw mbpoll psmisc +apt-get install -y python3 python3-pil python3-paho-mqtt network-manager iw mbpoll psmisc curl python3 --version echo "Skip setcap: service runs as root and can bind port 80 without extra capabilities" @@ -288,10 +309,9 @@ fi step "Summary" echo "Web UI: http://" -echo "Status API: curl -s http://127.0.0.1/api/status | cat" -echo "Health API: curl -s http://127.0.0.1/api/health/summary | cat" -echo "Network API: curl -s http://127.0.0.1/api/network/summary | cat" -echo "Display API: curl -s http://127.0.0.1/api/display | cat" +echo "Login shell: curl -i http://127.0.0.1/ | cat" +echo "Auth session API: curl -i http://127.0.0.1/api/auth/session | cat" +echo "Protected status API (expected 401 without session): curl -i http://127.0.0.1/api/status | cat" echo "Service status: systemctl status ${SERVICE_NAME} --no-pager -n 40" echo "Install dir: ${APP_DIR}" echo "Frontend dir: ${FRONTEND_DIR}"