Password Ui

This commit is contained in:
Andrei Smaliak 2026-04-07 18:43:42 +04:00
parent b98890f5ec
commit 31f1d975a7
5 changed files with 732 additions and 88 deletions

View File

@ -6,12 +6,17 @@ import json
import os import os
import shutil import shutil
import re import re
import secrets
import select import select
import threading
import subprocess import subprocess
import sys import sys
import tempfile import tempfile
import time import time
import crypt
import spwd
from datetime import datetime from datetime import datetime
from http.cookies import SimpleCookie
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlparse from urllib.parse import parse_qs, urlparse
from itscreen_registration import get_registration_status, register_device, reset_registration from itscreen_registration import get_registration_status, register_device, reset_registration
@ -95,6 +100,30 @@ CAPTIVE_REDIRECT_PATHS = (
| WINDOWS_CAPTIVE_PATHS | WINDOWS_CAPTIVE_PATHS
| GENERIC_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(): def load_config():
@ -124,6 +153,89 @@ def run(cmd, timeout=4):
return 1, "", str(exc) 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): def command_exists(name):
return shutil.which(name) is not None return shutil.which(name) is not None
@ -1907,11 +2019,14 @@ class Handler(BaseHTTPRequestHandler):
return False return False
return True 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") body = json.dumps(payload, indent=2).encode("utf-8")
self.send_response(code) self.send_response(code)
self.send_header("Content-Type", "application/json; charset=utf-8") self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(body))) 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.end_headers()
self._write_response_body(body) self._write_response_body(body)
@ -1948,7 +2063,7 @@ class Handler(BaseHTTPRequestHandler):
return None return None
return data if isinstance(data, dict) else 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: try:
with open(path, "rb") as fh: with open(path, "rb") as fh:
data = fh.read() data = fh.read()
@ -1958,18 +2073,55 @@ class Handler(BaseHTTPRequestHandler):
self.send_response(200) self.send_response(200)
self.send_header("Content-Type", content_type) self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(data))) 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.end_headers()
self._write_response_body(data) self._write_response_body(data)
def send_sse_headers(self): def send_sse_headers(self, extra_headers=None):
self.send_response(200) self.send_response(200)
self.send_header("Content-Type", "text/event-stream; charset=utf-8") 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("Cache-Control", "no-store, no-cache, must-revalidate")
self.send_header("Pragma", "no-cache") self.send_header("Pragma", "no-cache")
self.send_header("Connection", "keep-alive") self.send_header("Connection", "keep-alive")
self.send_header("X-Accel-Buffering", "no") 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() 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): def stream_itscreen_logs(self):
if not shutil.which("journalctl"): if not shutil.which("journalctl"):
self.send_json({"ok": False, "error": "Logs are unavailable"}, code=503) self.send_json({"ok": False, "error": "Logs are unavailable"}, code=503)
@ -2063,6 +2215,20 @@ class Handler(BaseHTTPRequestHandler):
query = parse_qs(parsed.query or "") query = parse_qs(parsed.query or "")
if self.handle_captive_portal_probe(parsed): if self.handle_captive_portal_probe(parsed):
return 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": if parsed.path == "/api/status":
self.send_json(build_status_payload()) self.send_json(build_status_payload())
return return
@ -2183,16 +2349,16 @@ class Handler(BaseHTTPRequestHandler):
self.send_json({"ok": False, "error": str(exc)}, code=500) self.send_json({"ok": False, "error": str(exc)}, code=500)
return return
if parsed.path in ("/", "/index.html"): 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 return
if parsed.path == "/console.css": 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 return
if parsed.path == "/console.i18n.js": 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 return
if parsed.path == "/console.js": 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 return
if parsed.path == "/logo.png": if parsed.path == "/logo.png":
self.send_file(os.path.join(PUBLIC_DIR, "logo.png"), "image/png") self.send_file(os.path.join(PUBLIC_DIR, "logo.png"), "image/png")
@ -2211,6 +2377,30 @@ class Handler(BaseHTTPRequestHandler):
def do_POST(self): def do_POST(self):
parsed = urlparse(self.path) 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": if parsed.path == "/api/ap/password/change":
payload = self.read_json_body() payload = self.read_json_body()
if payload is None: if payload is None:

View File

@ -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){ .menuActionBtn.is-danger:hover:not(:disabled){
background:rgba(185,52,52,.10); background:rgba(185,52,52,.10);
} }
.menuActionBtn[hidden]{
display:none !important;
}
.menuActionIcon{ .menuActionIcon{
width:18px; width:18px;
height: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{background:var(--button-secondary);color:var(--ink);border:1px solid var(--line)}
.actionBtn.secondary:hover:not(:disabled){background:var(--button-secondary-hover)} .actionBtn.secondary:hover:not(:disabled){background:var(--button-secondary-hover)}
.actionBtn:disabled{opacity:.5;cursor:not-allowed} .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} .serviceActionRow{align-items:center}
.actionBadge{ .actionBadge{
display:inline-flex;align-items:center;border-radius:999px;padding:6px 10px; display:inline-flex;align-items:center;border-radius:999px;padding:6px 10px;
@ -1059,6 +1136,14 @@ html[dir="rtl"] .itscreenLogsActions{
.writeLogCard{ .writeLogCard{
margin-top:14px; margin-top:14px;
} }
.panel.is-disabled{
opacity:.6;
}
.panel.is-disabled .writeConfigSection,
.panel.is-disabled .writeLogCard,
.panel.is-disabled .actionRow{
pointer-events:none;
}
.modbusWriteLogBody{ .modbusWriteLogBody{
min-height:160px; min-height:160px;
max-height:160px; max-height:160px;
@ -1072,6 +1157,33 @@ html[dir="rtl"] .itscreenLogsActions{
font-size:12px; font-size:12px;
line-height:1.5; 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{ @keyframes pulse{
0%,100%{opacity:.35;transform:scale(.9)} 0%,100%{opacity:.35;transform:scale(.9)}
50%{opacity:1;transform:scale(1)} 50%{opacity:1;transform:scale(1)}
@ -1098,6 +1210,8 @@ html[dir="rtl"] .itscreenLogsActions{
.itscreenLogsActions{justify-content:flex-start} .itscreenLogsActions{justify-content:flex-start}
.modbusGrid{grid-template-columns:1fr} .modbusGrid{grid-template-columns:1fr}
.modbusDiscoveryGrid{grid-template-columns:1fr} .modbusDiscoveryGrid{grid-template-columns:1fr}
.passwordInputRow{grid-template-columns:1fr}
.authCard{padding:22px}
} }
@media (max-width:680px){ @media (max-width:680px){
.menuToggleBtn{ .menuToggleBtn{

View File

@ -10,6 +10,8 @@
languageSelect: document.getElementById("languageSelect"), languageSelect: document.getElementById("languageSelect"),
themeToggleBtn: document.getElementById("themeToggleBtn"), themeToggleBtn: document.getElementById("themeToggleBtn"),
themeToggleIcon: document.getElementById("themeToggleIcon"), themeToggleIcon: document.getElementById("themeToggleIcon"),
logoutBtn: document.getElementById("logoutBtn"),
logoutMenuLabel: document.getElementById("logoutMenuLabel"),
tabs: Array.from(document.querySelectorAll("[data-tab]")), tabs: Array.from(document.querySelectorAll("[data-tab]")),
brandEyebrow: document.getElementById("brandEyebrow"), brandEyebrow: document.getElementById("brandEyebrow"),
heroTitle: document.getElementById("heroTitle"), heroTitle: document.getElementById("heroTitle"),
@ -212,6 +214,9 @@
selectedDevice: null, selectedDevice: null,
currentConfig: null, currentConfig: null,
lastWriteResult: null, lastWriteResult: null,
readConfigStatus: "idle",
readConfigMessage: "",
confirmStopItscreenOpen: false,
writeLog: [], writeLog: [],
writeForm: { writeForm: {
slave: "", slave: "",
@ -254,6 +259,17 @@
busyTarget: "", busyTarget: "",
results: {} results: {}
}, },
auth: {
loading: true,
authenticated: false,
username: "iomatex",
password: "",
showPassword: false,
busy: false,
error: "",
info: "",
expiresAt: 0
},
menuOpen: false, menuOpen: false,
rebootPending: false, rebootPending: false,
isPolling: false isPolling: false
@ -438,6 +454,7 @@
if (nodes.themeMenuLabel) nodes.themeMenuLabel.textContent = t("Theme"); if (nodes.themeMenuLabel) nodes.themeMenuLabel.textContent = t("Theme");
if (nodes.refreshMenuLabel) nodes.refreshMenuLabel.textContent = t("Refresh"); if (nodes.refreshMenuLabel) nodes.refreshMenuLabel.textContent = t("Refresh");
if (nodes.rebootMenuLabel) nodes.rebootMenuLabel.textContent = t("Reboot"); 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.tabHealth) nodes.tabHealth.textContent = t("Health");
if (nodes.tabNetwork) nodes.tabNetwork.textContent = t("Network"); if (nodes.tabNetwork) nodes.tabNetwork.textContent = t("Network");
if (nodes.tabModbus) nodes.tabModbus.textContent = t("Modbus"); if (nodes.tabModbus) nodes.tabModbus.textContent = t("Modbus");
@ -464,6 +481,10 @@
} }
function syncActionMenu() { 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; const isOpen = !!state.menuOpen;
if (nodes.actionMenu) nodes.actionMenu.hidden = !isOpen; if (nodes.actionMenu) nodes.actionMenu.hidden = !isOpen;
if (nodes.menuBackdrop) nodes.menuBackdrop.hidden = !isOpen; if (nodes.menuBackdrop) nodes.menuBackdrop.hidden = !isOpen;
@ -486,6 +507,46 @@
syncActionMenu(); 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) { function applyTheme(theme) {
state.theme = theme === "dark" ? "dark" : "light"; state.theme = theme === "dark" ? "dark" : "light";
document.documentElement.setAttribute("data-theme", state.theme); 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)`; 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) { function showToast(kind, message) {
if (!nodes.toastStack || !message) return; if (!nodes.toastStack || !message) return;
const toast = document.createElement("div"); const toast = document.createElement("div");
@ -959,7 +1029,7 @@
return `${days}d ${hours}h`; return `${days}d ${hours}h`;
} }
function formatTimestamp(value) { function formatEpochTimestamp(value) {
const ms = Number(value); const ms = Number(value);
if (!Number.isFinite(ms) || ms <= 0) return "—"; if (!Number.isFinite(ms) || ms <= 0) return "—";
const date = new Date(ms); const date = new Date(ms);
@ -969,7 +1039,7 @@
} }
function formatHealthLastStart(value) { function formatHealthLastStart(value) {
const formatted = formatTimestamp(value); const formatted = formatEpochTimestamp(value);
return formatted === "—" ? t("unknown") : formatted; return formatted === "—" ? t("unknown") : formatted;
} }
@ -1876,12 +1946,12 @@
<div class="listTitle">${esc(t("Server sync"))}</div> <div class="listTitle">${esc(t("Server sync"))}</div>
<div class="meta compactMeta"> <div class="meta compactMeta">
<div class="key">${esc(t("Server sync interval"))}</div><div>${esc(formatInterval(runtime.update_interval, t("Disabled")))}</div> <div class="key">${esc(t("Server sync interval"))}</div><div>${esc(formatInterval(runtime.update_interval, t("Disabled")))}</div>
<div class="key">${esc(t("Last contact with server"))}</div><div>${esc(formatTimestamp(runtime.last_contact_ts))}</div> <div class="key">${esc(t("Last contact with server"))}</div><div>${esc(formatEpochTimestamp(runtime.last_contact_ts))}</div>
<div class="key">${esc(t("Next scheduled contact"))}</div><div>${esc(formatTimestamp(runtime.next_contact_ts))}</div> <div class="key">${esc(t("Next scheduled contact"))}</div><div>${esc(formatEpochTimestamp(runtime.next_contact_ts))}</div>
<div class="key">${esc(t("Auto reboot interval"))}</div><div>${esc(runtime.enable_reboot_repeat === false ? t("Disabled") : (runtime.enable_reboot_repeat === true ? formatRepeatInterval(runtime.reboot_repeat_time) : "—"))}</div> <div class="key">${esc(t("Auto reboot interval"))}</div><div>${esc(runtime.enable_reboot_repeat === false ? t("Disabled") : (runtime.enable_reboot_repeat === true ? formatRepeatInterval(runtime.reboot_repeat_time) : "—"))}</div>
<div class="key">${esc(t("Daily reboot time"))}</div><div>${esc(runtime.enable_reboot === false ? t("Disabled") : (runtime.enable_reboot === true ? textValue(runtime.reboot_time, t("Not set")) : "—"))}</div> <div class="key">${esc(t("Daily reboot time"))}</div><div>${esc(runtime.enable_reboot === false ? t("Disabled") : (runtime.enable_reboot === true ? textValue(runtime.reboot_time, t("Not set")) : "—"))}</div>
<div class="key">${esc(t("Next shutdown"))}</div><div>${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)) : "—"))}</div> <div class="key">${esc(t("Next shutdown"))}</div><div>${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)) : "—"))}</div>
<div class="key">${esc(t("Next startup"))}</div><div>${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)) : "—"))}</div> <div class="key">${esc(t("Next startup"))}</div><div>${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)) : "—"))}</div>
</div> </div>
</div> </div>
</article> </article>
@ -2170,11 +2240,7 @@
if (logs.request) return logs.request; if (logs.request) return logs.request;
logs.request = (async () => { logs.request = (async () => {
try { try {
const response = await fetch(`/api/itscreen/logs?lines=${encodeURIComponent(String(lines))}`, { cache: "no-store" }); const payload = await fetchJson(`/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 incoming = Array.isArray(payload.lines) ? payload.lines.map((line) => (line ?? "").toString()) : []; const incoming = Array.isArray(payload.lines) ? payload.lines.map((line) => (line ?? "").toString()) : [];
logs.buffer = replace ? trimItscreenLogBuffer(incoming) : trimItscreenLogBuffer(logs.buffer.concat(incoming)); logs.buffer = replace ? trimItscreenLogBuffer(incoming) : trimItscreenLogBuffer(logs.buffer.concat(incoming));
logs.available = true; logs.available = true;
@ -2366,12 +2432,31 @@
return ""; 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() { function modbusCanWrite() {
const log = modbusState(); const log = modbusState();
const capabilities = modbusWriteCapabilities(); const capabilities = modbusWriteCapabilities();
const strategy = normalizeModbusWriteStrategy(log.writeForm.strategy); const strategy = normalizeModbusWriteStrategy(log.writeForm.strategy);
const strategyAllowed = strategy === "id" ? capabilities.supportsIdWrite : capabilities.supportsSerialWrite; const strategyAllowed = strategy === "id" ? capabilities.supportsIdWrite : capabilities.supportsSerialWrite;
return !!(log.currentConfig && log.selectedDevice && strategyAllowed && !modbusWriteValidationError()); return !!(modbusWriteAccessState().enabled && strategyAllowed && !modbusWriteValidationError());
} }
function modbusBusy(action) { function modbusBusy(action) {
@ -2468,21 +2553,23 @@
const strategySelect = document.getElementById("modbusWriteStrategySelect"); const strategySelect = document.getElementById("modbusWriteStrategySelect");
const applyBtn = document.getElementById("modbusWriteApplyBtn"); const applyBtn = document.getElementById("modbusWriteApplyBtn");
const errorNode = document.getElementById("modbusWriteError"); const errorNode = document.getElementById("modbusWriteError");
const writeAccess = modbusWriteAccessState();
const capabilities = modbusWriteCapabilities(); const capabilities = modbusWriteCapabilities();
const strategy = normalizeModbusWriteStrategy(modbusState().writeForm.strategy); const strategy = normalizeModbusWriteStrategy(modbusState().writeForm.strategy);
const validationError = modbusWriteValidationError(); const validationError = modbusWriteValidationError();
if (strategySelect) strategySelect.value = strategy; if (strategySelect) strategySelect.value = strategy;
if (slaveInput) { if (slaveInput) {
slaveInput.disabled = !capabilities.supportsIdWrite || strategy !== "id"; slaveInput.disabled = !writeAccess.enabled || !capabilities.supportsIdWrite || strategy !== "id";
if (typeof slaveInput.setCustomValidity === "function") { if (typeof slaveInput.setCustomValidity === "function") {
slaveInput.setCustomValidity(slaveInput.disabled ? "" : modbusWriteSlaveValidationError(modbusState().writeForm.slave)); 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 (applyBtn) applyBtn.disabled = !!(modbusBusy("write_config") || !modbusCanWrite());
if (errorNode) { if (errorNode) {
errorNode.textContent = validationError || ""; errorNode.textContent = validationError || writeAccess.reason || "";
errorNode.hidden = !validationError; errorNode.hidden = !(validationError || writeAccess.reason);
} }
} }
@ -2571,6 +2658,7 @@
function renderModbusFoundDevices() { function renderModbusFoundDevices() {
const devices = modbusState().discovery.devices || []; const devices = modbusState().discovery.devices || [];
const log = modbusState();
if (!devices.length) { if (!devices.length) {
return `<div class="emptyInline">${esc(t("No devices discovered yet."))}</div>`; return `<div class="emptyInline">${esc(t("No devices discovered yet."))}</div>`;
} }
@ -2591,7 +2679,7 @@
</thead> </thead>
<tbody> <tbody>
${devices.map((item, index) => ` ${devices.map((item, index) => `
<tr class="${modbusState().selectedDevice && modbusState().selectedDevice.port === item.port && modbusState().selectedDevice.slave === item.slave && modbusState().selectedDevice.baud === item.baud && modbusState().selectedDevice.parity === item.parity ? "is-selected" : ""}"> <tr class="${log.selectedDevice && log.selectedDevice.port === item.port && log.selectedDevice.slave === item.slave && log.selectedDevice.baud === item.baud && log.selectedDevice.parity === item.parity ? "is-selected" : ""}">
<td>${esc(item.port)}</td> <td>${esc(item.port)}</td>
<td>${esc(item.family_display_name || item.family)}</td> <td>${esc(item.family_display_name || item.family)}</td>
<td>${esc(String(item.slave))}</td> <td>${esc(String(item.slave))}</td>
@ -2602,7 +2690,7 @@
<td> <td>
<div class="actionRow compactActionRow"> <div class="actionRow compactActionRow">
<button class="actionBtn compactBtn" type="button" onclick="window.__modbusSelectDevice(${index})">${esc(t("Select"))}</button> <button class="actionBtn compactBtn" type="button" onclick="window.__modbusSelectDevice(${index})">${esc(t("Select"))}</button>
<button class="actionBtn secondary compactBtn" type="button" onclick="window.__modbusReadConfigFromDiscovery(${index})">${esc(t("Read config"))}</button> <button class="actionBtn secondary compactBtn" type="button" ${modbusBusy("read_config") ? "disabled" : ""} onclick="window.__modbusReadConfigFromDiscovery(${index})">${esc(modbusBusy("read_config") ? t("Reading...") : t("Read config"))}</button>
</div> </div>
</td> </td>
</tr> </tr>
@ -2623,12 +2711,39 @@
{ label: t("Current baud"), value: textValue(currentConfig.current_config && currentConfig.current_config.baud, t("Unknown")) }, { 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("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("Config register values"), value: JSON.stringify(currentConfig.raw_values || {}) },
{ label: t("Last successful read"), value: textValue(currentConfig.last_successful_read, "-") }, { label: t("Last successful read"), value: formatTimestamp(currentConfig.last_successful_read) },
{ label: t("Last communication timestamp"), value: textValue(currentConfig.last_communication_timestamp, "-") } { label: t("Last communication timestamp"), value: formatTimestamp(currentConfig.last_communication_timestamp) }
]; ];
return `<div class="meta compactMeta">${renderKeyValueRows(rows)}</div>`; return `<div class="meta compactMeta">${renderKeyValueRows(rows)}</div>`;
} }
function renderModbusReadConfigState() {
const log = modbusState();
if (log.readConfigStatus === "success" && log.readConfigMessage) {
return `<div class="banner success">${esc(log.readConfigMessage)}</div>`;
}
if (log.readConfigStatus === "error" && log.readConfigMessage) {
return `<div class="banner error">${esc(log.readConfigMessage)}</div>`;
}
return "";
}
function renderModbusReadConfigDialog() {
if (!modbusState().confirmStopItscreenOpen) return "";
return `
<div class="modalBackdrop" role="presentation">
<div class="modalCard" role="dialog" aria-modal="true" aria-labelledby="modbusStopItscreenTitle">
<h3 id="modbusStopItscreenTitle">${esc(t("Stop it-screen client?"))}</h3>
<p>${esc(t("Reading configuration requires exclusive access to the Modbus port."))}<br>${esc(t("The it-screen client will be temporarily stopped."))}</p>
<div class="actionRow">
<button class="actionBtn secondary" type="button" onclick="window.__modbusCancelReadConfigPrompt()">${esc(t("Cancel"))}</button>
<button class="actionBtn" type="button" onclick="window.__modbusConfirmReadConfigPrompt()">${esc(t("Stop and continue"))}</button>
</div>
</div>
</div>
`;
}
function modbusWriteStatusMeta() { function modbusWriteStatusMeta() {
const result = modbusState().lastWriteResult; const result = modbusState().lastWriteResult;
if (!result) return ""; if (!result) return "";
@ -2682,6 +2797,7 @@
const portInfo = modbusSelectedPortStatus() || {}; const portInfo = modbusSelectedPortStatus() || {};
const zeroBased = !!profileTransport.zero_based; const zeroBased = !!profileTransport.zero_based;
const scanRunning = modbusScanRunning(); const scanRunning = modbusScanRunning();
const writeAccess = modbusWriteAccessState();
const scanStatus = textValue(log.discovery.message, scanRunning ? t("Scanning in progress. It may take some minutes.") : ""); const scanStatus = textValue(log.discovery.message, scanRunning ? t("Scanning in progress. It may take some minutes.") : "");
const scanLogLines = modbusDiscoveryLogLines(); const scanLogLines = modbusDiscoveryLogLines();
const writeCurrentConfig = modbusWriteCurrentConfigView(); const writeCurrentConfig = modbusWriteCurrentConfigView();
@ -2741,7 +2857,6 @@
</div> </div>
<div class="actionRow modbusScanActions"> <div class="actionRow modbusScanActions">
<button class="actionBtn" type="button" ${scanRunning ? "disabled" : ""} onclick="window.__modbusScan('quick')">${esc(modbusBusy("scan_quick") ? t("Scanning...") : t("Quick scan"))}</button> <button class="actionBtn" type="button" ${scanRunning ? "disabled" : ""} onclick="window.__modbusScan('quick')">${esc(modbusBusy("scan_quick") ? t("Scanning...") : t("Quick scan"))}</button>
<button class="actionBtn secondary" type="button" ${scanRunning ? "disabled" : ""} onclick="window.__modbusScan('deep')">${esc(modbusBusy("scan_deep") ? t("Scanning...") : t("Deep scan"))}</button>
${scanRunning ? `<div class="loadingInline"><span class="loadingDot" aria-hidden="true"></span><span>${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))})` : ""}</span></div>` : ""} ${scanRunning ? `<div class="loadingInline"><span class="loadingDot" aria-hidden="true"></span><span>${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))})` : ""}</span></div>` : ""}
</div> </div>
${scanStatus && !scanRunning ? `<div class="formHint">${esc(scanStatus)}</div>` : ""} ${scanStatus && !scanRunning ? `<div class="formHint">${esc(scanStatus)}</div>` : ""}
@ -2759,13 +2874,15 @@
<article class="panel card"> <article class="panel card">
<div class="cardTop"><div><h2>${esc(t("Current Config"))}</h2></div></div> <div class="cardTop"><div><h2>${esc(t("Current Config"))}</h2></div></div>
${renderModbusReadConfigState()}
${renderModbusCurrentConfig()} ${renderModbusCurrentConfig()}
</article> </article>
<article class="panel card"> <article class="panel card${writeAccess.enabled ? "" : " is-disabled"}">
<div class="cardTop"><div><h2>${esc(t("Configuration Write"))}</h2></div></div> <div class="cardTop"><div><h2>${esc(t("Configuration Write"))}</h2></div></div>
${modbusWriteStatusMeta()} ${modbusWriteStatusMeta()}
${!supportsSerialWrite ? `<div class="formHint">${esc(t("Baud rate and parity write are not configured for this family yet. Slave ID write is available."))}</div>` : ""} ${!supportsSerialWrite ? `<div class="formHint">${esc(t("Baud rate and parity write are not configured for this family yet. Slave ID write is available."))}</div>` : ""}
${writeAccess.enabled ? "" : `<div class="banner ${esc(writeAccess.tone)}">${esc(writeAccess.reason)}</div>`}
<div class="writeConfigSection"> <div class="writeConfigSection">
<div class="sectionTitle">${esc(t("Current config"))}</div> <div class="sectionTitle">${esc(t("Current config"))}</div>
<div class="meta compactMeta modbusSummaryMeta"> <div class="meta compactMeta modbusSummaryMeta">
@ -2782,8 +2899,8 @@
<label class="field"> <label class="field">
<span>${esc(t("Apply strategy"))}</span> <span>${esc(t("Apply strategy"))}</span>
<select id="modbusWriteStrategySelect" onchange="window.__modbusSetWriteField('strategy', this.value)"> <select id="modbusWriteStrategySelect" onchange="window.__modbusSetWriteField('strategy', this.value)">
<option value="id" ${log.writeForm.strategy === "id" ? "selected" : ""}>${esc(t("ID only"))}</option> <option value="id" ${log.writeForm.strategy === "id" ? "selected" : ""} ${writeAccess.enabled ? "" : "disabled"}>${esc(t("ID only"))}</option>
<option value="baud" ${log.writeForm.strategy === "baud" ? "selected" : ""} ${supportsSerialWrite ? "" : "disabled"}>${esc(t("Baud rate only"))}</option> <option value="baud" ${log.writeForm.strategy === "baud" ? "selected" : ""} ${supportsSerialWrite && writeAccess.enabled ? "" : "disabled"}>${esc(t("Baud rate only"))}</option>
</select> </select>
</label> </label>
<label class="field"> <label class="field">
@ -2804,7 +2921,7 @@
</label> </label>
<div id="modbusWriteError" class="formHint" ${modbusWriteValidationError() ? "" : "hidden"}>${esc(modbusWriteValidationError())}</div> <div id="modbusWriteError" class="formHint" ${modbusWriteValidationError() ? "" : "hidden"}>${esc(modbusWriteValidationError())}</div>
</div> </div>
<div class="formHint">${esc(t("Write is disabled until a device has been selected and its current config has been read."))}</div> <div class="formHint">${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."))}</div>
${renderModbusWriteProcessLog()} ${renderModbusWriteProcessLog()}
<div class="actionRow"> <div class="actionRow">
<button id="modbusWriteApplyBtn" class="actionBtn" type="button" ${modbusCanWrite() && !modbusBusy("write_config") ? "" : "disabled"} onclick="window.__modbusApplyConfig()">${esc(modbusBusy("write_config") ? t("Applying...") : t("Apply changes"))}</button> <button id="modbusWriteApplyBtn" class="actionBtn" type="button" ${modbusCanWrite() && !modbusBusy("write_config") ? "" : "disabled"} onclick="window.__modbusApplyConfig()">${esc(modbusBusy("write_config") ? t("Applying...") : t("Apply changes"))}</button>
@ -2876,11 +2993,25 @@
${renderModbusLogPanel()} ${renderModbusLogPanel()}
</div> </div>
${renderModbusReadConfigDialog()}
</section> </section>
`; `;
} }
function renderActiveTab() { 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") { if (state.activeTab === "tscreen") {
captureItscreenLogViewport(); captureItscreenLogViewport();
} }
@ -2909,6 +3040,53 @@
nodes.content.innerHTML = renderHealthTab(); nodes.content.innerHTML = renderHealthTab();
} }
function renderAuthLoadingScreen() {
return `
<section class="authScreen">
<div class="authCard panel authCardLoading">
<div class="authBrand">
<img class="authLogo" src="/logo.png" alt="IOMATEX EDGE">
<div class="eyebrow">${esc(t("IOMATEX EDGE"))}</div>
<h2>${esc(t("WEB UI"))}</h2>
<p class="sub">${esc(t("Checking session..."))}</p>
</div>
</div>
</section>
`;
}
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 `
<section class="authScreen">
<div class="authCard panel">
<div class="authBrand">
<img class="authLogo" src="/logo.png" alt="IOMATEX EDGE">
<div class="eyebrow">${esc(t("IOMATEX EDGE"))}</div>
<h2>${esc(t("WEB UI"))}</h2>
<p class="sub">${esc(t("Use device credentials to continue"))}</p>
<p class="authSessionHint">${esc(t("Session stays active for up to 1 hour after your last action."))}</p>
</div>
<form class="authForm" onsubmit="window.__authSubmit(event)">
<label class="fieldLabel" for="authUsername">${esc(t("Username"))}</label>
<input id="authUsername" class="textInput" type="text" autocomplete="username" value="${esc(auth.username)}" oninput="window.__authSetField('username', this.value)" ${disabled ? "disabled" : ""}>
<label class="fieldLabel" for="authPassword">${esc(t("Password"))}</label>
<div class="passwordInputRow">
<input id="authPassword" class="textInput" type="${auth.showPassword ? "text" : "password"}" autocomplete="current-password" value="${esc(auth.password)}" oninput="window.__authSetField('password', this.value)" ${disabled ? "disabled" : ""}>
<button class="actionBtn secondary passwordToggleBtn" type="button" onclick="window.__authTogglePassword()" ${disabled ? "disabled" : ""}>${esc(auth.showPassword ? t("Hide") : t("Show"))}</button>
</div>
${infoMessage ? `<div class="banner info">${esc(infoMessage)}</div>` : ""}
${errorMessage ? `<div class="banner error">${esc(errorMessage)}</div>` : ""}
<button class="actionBtn authSubmitBtn" type="submit" ${disabled ? "disabled" : ""}>${esc(auth.busy ? t("Signing in...") : t("Sign in"))}</button>
</form>
</div>
</section>
`;
}
function updateIdentity(identity) { function updateIdentity(identity) {
const safe = identity || {}; const safe = identity || {};
nodes.edgeId.textContent = safe.serial_number || "-"; 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) { async function fetchJson(url, options) {
const response = await fetch(url, options || { cache: "no-store" }); const response = await fetch(url, options || { cache: "no-store" });
const payload = await response.json().catch(() => ({})); 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) { if (!response.ok || payload.ok === false) {
throw new Error(payload.error || `HTTP ${response.status}`); throw new Error(payload.error || `HTTP ${response.status}`);
} }
@ -3017,34 +3227,12 @@
} }
async function requestItscreenStatus() { async function requestItscreenStatus() {
const response = await fetch("/api/itscreen/status", { cache: "no-store" }); return fetchJson("/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;
} }
async function requestItscreenRuntime() { async function requestItscreenRuntime() {
const response = await fetch("/api/itscreen/runtime", { cache: "no-store" }); const payload = await fetchJson("/api/itscreen/runtime", { cache: "no-store" });
const payload = await response.json().catch(() => ({ if (payload.status === "not_installed" || payload.status === "error") {
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") {
return { return {
current_time: textValue(payload.current_time, ""), current_time: textValue(payload.current_time, ""),
service_started_at: null, service_started_at: null,
@ -3167,6 +3355,10 @@
} }
async function loadForActiveTab(options = {}) { async function loadForActiveTab(options = {}) {
if (!state.auth.authenticated) {
renderActiveTab();
return;
}
const preserveEditing = !!options.preserveEditing; const preserveEditing = !!options.preserveEditing;
nodes.refreshBtn.disabled = true; nodes.refreshBtn.disabled = true;
if (nodes.rebootBtn) nodes.rebootBtn.disabled = state.rebootPending; if (nodes.rebootBtn) nodes.rebootBtn.disabled = state.rebootPending;
@ -3679,6 +3871,9 @@
log.currentConfig = null; log.currentConfig = null;
log.selectedDevice = null; log.selectedDevice = null;
log.lastWriteResult = null; log.lastWriteResult = null;
log.readConfigStatus = "idle";
log.readConfigMessage = "";
log.confirmStopItscreenOpen = false;
const profile = modbusSelectedProfile(); const profile = modbusSelectedProfile();
if (profile && profile.transport) { if (profile && profile.transport) {
log.discovery.baud = String(profile.transport.default_baud || 9600); log.discovery.baud = String(profile.transport.default_baud || 9600);
@ -3755,6 +3950,8 @@
if (!item) return; if (!item) return;
log.selectedDevice = item; log.selectedDevice = item;
log.currentConfig = null; log.currentConfig = null;
log.readConfigStatus = "idle";
log.readConfigMessage = "";
log.writeForm.slave = String(item.slave); log.writeForm.slave = String(item.slave);
log.writeForm.baud = String(item.baud); log.writeForm.baud = String(item.baud);
log.writeForm.parity = item.parity; log.writeForm.parity = item.parity;
@ -3891,13 +4088,31 @@
await window.__modbusReadConfig(); 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 log = modbusState();
const current = modbusCurrentConnection();
log.busyAction = "read_config"; log.busyAction = "read_config";
log.error = ""; log.error = "";
log.readConfigStatus = "loading";
log.readConfigMessage = "";
if (state.activeTab === "modbus") renderActiveTab(); if (state.activeTab === "modbus") renderActiveTab();
try { try {
if (options.stopItscreenFirst) {
log.stopItscreen = true;
appendModbusLog(t("it-screen client will be stopped for Modbus access"), "warn");
}
const current = modbusCurrentConnection();
await modbusEnsureSession(); await modbusEnsureSession();
const payload = await fetchJson("/api/modbus/read-config", { const payload = await fetchJson("/api/modbus/read-config", {
method: "POST", method: "POST",
@ -3923,16 +4138,44 @@
log.writeForm.baud = String(payload.current && payload.current.baud || current.baud); log.writeForm.baud = String(payload.current && payload.current.baud || current.baud);
log.writeForm.parity = textValue(payload.current && payload.current.parity, current.parity); log.writeForm.parity = textValue(payload.current && payload.current.parity, current.parity);
log.writeForm.strategy = normalizeModbusWriteStrategy(log.writeForm.strategy); log.writeForm.strategy = normalizeModbusWriteStrategy(log.writeForm.strategy);
log.readConfigStatus = "success";
log.readConfigMessage = t("Current config read completed");
ingestModbusPayload(payload); ingestModbusPayload(payload);
appendModbusLog(t("Current config read completed"), "success"); appendModbusLog(log.readConfigMessage, "success");
showToast("success", log.readConfigMessage);
} catch (error) { } catch (error) {
log.error = error.message || t("Failed to read current config"); log.error = error.message || t("Failed to read current config");
log.currentConfig = null;
log.readConfigStatus = "error";
log.readConfigMessage = log.error;
appendModbusLog(log.error, "error"); appendModbusLog(log.error, "error");
showToast("error", log.error); showToast("error", log.error);
} finally { } finally {
log.busyAction = ""; log.busyAction = "";
if (state.activeTab === "modbus") renderActiveTab(); 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 () { window.__modbusApplyConfig = async function () {
@ -3959,7 +4202,7 @@
log.writeForm.slave = modbusCurrentSlaveFallback(); log.writeForm.slave = modbusCurrentSlaveFallback();
} }
const writeTarget = modbusWriteTargetFromForm(current); const writeTarget = modbusWriteTargetFromForm(current);
const response = await fetch("/api/modbus/write-config", { const payload = await fetchJson("/api/modbus/write-config", {
method: "POST", method: "POST",
cache: "no-store", cache: "no-store",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
@ -3975,10 +4218,6 @@
strategy: modbusWriteStrategyForPayload(writeTarget.strategy) 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; log.lastWriteResult = payload;
ingestModbusPayload(payload); ingestModbusPayload(payload);
ingestModbusWritePayload(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) => { nodes.tabs.forEach((button) => {
button.addEventListener("click", async () => { button.addEventListener("click", async () => {
if (!state.auth.authenticated) return;
const nextTab = button.dataset.tab; const nextTab = button.dataset.tab;
if (!nextTab || nextTab === state.activeTab) return; if (!nextTab || nextTab === state.activeTab) return;
if (state.activeTab === "tscreen" && nextTab !== "tscreen") { if (state.activeTab === "tscreen" && nextTab !== "tscreen") {
@ -4104,11 +4408,16 @@
if (nodes.refreshBtn) { if (nodes.refreshBtn) {
nodes.refreshBtn.addEventListener("click", async () => { nodes.refreshBtn.addEventListener("click", async () => {
if (!state.auth.authenticated) return;
closeActionMenu(); closeActionMenu();
await loadForActiveTab(); await loadForActiveTab();
}); });
} }
if (nodes.rebootBtn) nodes.rebootBtn.addEventListener("click", window.__rebootDevice); 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.themeToggleBtn) nodes.themeToggleBtn.addEventListener("click", toggleTheme);
if (nodes.languageSelect) { if (nodes.languageSelect) {
nodes.languageSelect.addEventListener("change", (event) => { nodes.languageSelect.addEventListener("change", (event) => {
@ -4154,6 +4463,7 @@
deactivateItscreenLogs(); deactivateItscreenLogs();
return; return;
} }
if (!state.auth.authenticated) return;
if (state.activeTab === "tscreen") { if (state.activeTab === "tscreen") {
activateItscreenLogs().catch(() => {}); activateItscreenLogs().catch(() => {});
} }
@ -4164,12 +4474,18 @@
applyLanguage(state.language); applyLanguage(state.language);
applyTheme(loadThemePreference()); applyTheme(loadThemePreference());
syncActionMenu(); syncActionMenu();
loadForActiveTab().then(() => { setPrimaryUiLocked(true);
renderActiveTab();
loadAuthSession().then(() => {
if (!state.auth.authenticated) return;
return loadForActiveTab().then(() => {
if (state.activeTab === "tscreen") { if (state.activeTab === "tscreen") {
activateItscreenLogs().catch(() => {}); activateItscreenLogs().catch(() => {});
} }
}); });
}).catch(() => {});
setInterval(() => { setInterval(() => {
if (!state.auth.authenticated) return;
loadForActiveTab({ preserveEditing: true }).catch(() => {}); loadForActiveTab({ preserveEditing: true }).catch(() => {});
}, 15000); }, 15000);
})(); })();

View File

@ -78,6 +78,10 @@
<span class="menuActionIcon" aria-hidden="true">⏻</span> <span class="menuActionIcon" aria-hidden="true">⏻</span>
<span class="menuActionLabel" id="rebootMenuLabel">Reboot</span> <span class="menuActionLabel" id="rebootMenuLabel">Reboot</span>
</button> </button>
<button id="logoutBtn" class="menuActionBtn" type="button" hidden>
<span class="menuActionIcon" aria-hidden="true">⇥</span>
<span class="menuActionLabel" id="logoutMenuLabel">Logout</span>
</button>
</div> </div>
</div> </div>
</header> </header>

View File

@ -73,30 +73,51 @@ rollback_deploy() {
} }
wait_for_local_http() { wait_for_local_http() {
local attempt local attempt max_attempts url_root url_auth code_root code_auth
for attempt in $(seq 1 30); do 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 if ! systemctl is-active --quiet "${SERVICE_NAME}"; then
echo "Smoke-check attempt ${attempt}/${max_attempts}: ${SERVICE_NAME} is not active yet"
sleep 1 sleep 1
continue continue
fi 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 sleep 1
continue continue
fi fi
if python3 - <<'PY' >/dev/null 2>&1 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)"
import sys 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)"
import urllib.request echo "Smoke-check attempt ${attempt}/${max_attempts}: GET ${url_root} -> ${code_root:-curl_failed}; GET ${url_auth} -> ${code_auth:-curl_failed}"
try: if [ "${code_root}" = "200" ] && [ "${code_auth}" = "200" ]; then
with urllib.request.urlopen("http://127.0.0.1/api/status", timeout=5) as response: if grep -Eq 'IOMATEX Console|console\.js|console\.css' "/tmp/iomatex-console-smoke-root.$$"; then
sys.exit(0 if response.status == 200 else 1) echo "Smoke-check passed: public shell and unauthenticated auth endpoint are reachable"
except Exception: rm -f "/tmp/iomatex-console-smoke-root.$$" "/tmp/iomatex-console-smoke-auth.$$" "/tmp/iomatex-console-smoke-root.err" "/tmp/iomatex-console-smoke-auth.err"
sys.exit(1) return 0
PY fi
then 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 return 0
fi fi
sleep 1 sleep 1
done 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 return 1
} }
@ -153,7 +174,7 @@ done
step "Ensure runtime packages exist" step "Ensure runtime packages exist"
apt-get update 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 python3 --version
echo "Skip setcap: service runs as root and can bind port 80 without extra capabilities" echo "Skip setcap: service runs as root and can bind port 80 without extra capabilities"
@ -288,10 +309,9 @@ fi
step "Summary" step "Summary"
echo "Web UI: http://<EDGE-IP>" echo "Web UI: http://<EDGE-IP>"
echo "Status API: curl -s http://127.0.0.1/api/status | cat" echo "Login shell: curl -i http://127.0.0.1/ | cat"
echo "Health API: curl -s http://127.0.0.1/api/health/summary | cat" echo "Auth session API: curl -i http://127.0.0.1/api/auth/session | cat"
echo "Network API: curl -s http://127.0.0.1/api/network/summary | cat" echo "Protected status API (expected 401 without session): curl -i http://127.0.0.1/api/status | cat"
echo "Display API: curl -s http://127.0.0.1/api/display | cat"
echo "Service status: systemctl status ${SERVICE_NAME} --no-pager -n 40" echo "Service status: systemctl status ${SERVICE_NAME} --no-pager -n 40"
echo "Install dir: ${APP_DIR}" echo "Install dir: ${APP_DIR}"
echo "Frontend dir: ${FRONTEND_DIR}" echo "Frontend dir: ${FRONTEND_DIR}"