AP password mode: deterministic factory password from serial, UI fixes for WiFi input, backend adjustments, stage_wifi installer update
This commit is contained in:
parent
c8adc3920c
commit
a374b24401
|
|
@ -1,10 +1,13 @@
|
|||
#!/usr/bin/env python3
|
||||
import glob
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from urllib.parse import urlparse
|
||||
|
|
@ -21,6 +24,12 @@ DEFAULT_CONFIG = {
|
|||
}
|
||||
|
||||
_CACHE = {"expires_at": 0.0, "payload": None}
|
||||
AP_ENV_PATH = "/etc/iomatex/ap.env"
|
||||
AP_SYNC_SCRIPT = "/usr/local/sbin/iomatex-ap-sync-config"
|
||||
AP_RESET_SCRIPT = "/usr/local/sbin/iomatex-ap-reset-password"
|
||||
AP_UP_SCRIPT = "/usr/local/sbin/iomatex-ap-up"
|
||||
AP_DOWN_SCRIPT = "/usr/local/sbin/iomatex-ap-down"
|
||||
AP_PASSWORD_RE = re.compile(r"^[a-z0-9]{8,}$")
|
||||
|
||||
|
||||
def load_config():
|
||||
|
|
@ -90,6 +99,167 @@ def read_env_file(path):
|
|||
return data
|
||||
|
||||
|
||||
def write_env_file(path, values):
|
||||
directory = os.path.dirname(path) or "."
|
||||
os.makedirs(directory, exist_ok=True)
|
||||
fd, tmp_path = tempfile.mkstemp(prefix=".tmp-", dir=directory, text=True)
|
||||
try:
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as fh:
|
||||
for key, value in values.items():
|
||||
safe = str(value).replace("\n", "").replace("\r", "")
|
||||
fh.write(f'{key}="{safe}"\n')
|
||||
os.chmod(tmp_path, 0o644)
|
||||
os.replace(tmp_path, path)
|
||||
finally:
|
||||
if os.path.exists(tmp_path):
|
||||
os.unlink(tmp_path)
|
||||
|
||||
|
||||
def get_system_hostname():
|
||||
hostname = ""
|
||||
try:
|
||||
hostname = os.uname().nodename
|
||||
except Exception:
|
||||
hostname = ""
|
||||
hostname = str(hostname).strip()
|
||||
if hostname:
|
||||
return hostname.split(".", 1)[0]
|
||||
rc, stdout, _ = run(["hostname", "-s"])
|
||||
if rc == 0 and stdout.strip():
|
||||
return stdout.strip()
|
||||
rc, stdout, _ = run(["hostname"])
|
||||
if rc == 0 and stdout.strip():
|
||||
return stdout.strip()
|
||||
return ""
|
||||
|
||||
|
||||
def get_device_serial():
|
||||
raw = read_text("/proc/cpuinfo")
|
||||
for line in raw.splitlines():
|
||||
if line.strip().lower().startswith("serial"):
|
||||
_, _, value = line.partition(":")
|
||||
serial = value.strip().lower()
|
||||
if serial:
|
||||
return serial
|
||||
return ""
|
||||
|
||||
|
||||
def build_ap_ssid():
|
||||
hostname = get_system_hostname()
|
||||
return f"Iomatex {hostname}" if hostname else "Iomatex"
|
||||
|
||||
|
||||
def generate_factory_ap_password():
|
||||
serial = get_device_serial()
|
||||
if not serial:
|
||||
raise RuntimeError("Failed to read device serial")
|
||||
digest = hashlib.sha256(f"iomatex_the_best{serial}".encode("utf-8")).hexdigest().lower()
|
||||
password = re.sub(r"[^a-z0-9]", "", digest)[:8]
|
||||
if not AP_PASSWORD_RE.fullmatch(password):
|
||||
raise RuntimeError("Failed to generate valid factory AP password")
|
||||
return password
|
||||
|
||||
|
||||
def normalize_password_mode(mode, custom_password=""):
|
||||
mode_text = str(mode or "").strip().lower()
|
||||
if mode_text == "custom" and str(custom_password or "").strip():
|
||||
return "custom"
|
||||
return "factory"
|
||||
|
||||
|
||||
def load_ap_state():
|
||||
env = read_env_file(AP_ENV_PATH)
|
||||
ssid = build_ap_ssid()
|
||||
custom_password = str(env.get("CUSTOM_PASSWORD", "")).strip()
|
||||
password_mode = normalize_password_mode(env.get("PASSWORD_MODE", "factory"), custom_password)
|
||||
factory_password = generate_factory_ap_password()
|
||||
active_password = custom_password if password_mode == "custom" and custom_password else factory_password
|
||||
hostapd_unit = systemd_unit("iomatex-hostapd.service")
|
||||
ap_enabled = bool(hostapd_unit["active"])
|
||||
return {
|
||||
"ok": True,
|
||||
"ap_enabled": ap_enabled,
|
||||
"ssid": ssid,
|
||||
"password_mode": password_mode,
|
||||
"custom_password": custom_password if password_mode == "custom" else "",
|
||||
"factory_password": factory_password,
|
||||
"active_password": active_password,
|
||||
"iface": str(env.get("IFACE", "wlan0")).strip() or "wlan0",
|
||||
"ui_port": str(env.get("UI_PORT", "18080")).strip() or "18080",
|
||||
"service_state": hostapd_unit["active_state"],
|
||||
"service_installed": hostapd_unit["installed"],
|
||||
}
|
||||
|
||||
|
||||
def write_ap_state(password_mode, custom_password):
|
||||
current = load_ap_state()
|
||||
normalized_mode = normalize_password_mode(password_mode, custom_password)
|
||||
env = {
|
||||
"IFACE": current["iface"],
|
||||
"AP_IP": str(read_env_file(AP_ENV_PATH).get("AP_IP", "10.10.10.1")).strip() or "10.10.10.1",
|
||||
"AP_CIDR": str(read_env_file(AP_ENV_PATH).get("AP_CIDR", "10.10.10.1/24")).strip() or "10.10.10.1/24",
|
||||
"DHCP_START": str(read_env_file(AP_ENV_PATH).get("DHCP_START", "10.10.10.50")).strip() or "10.10.10.50",
|
||||
"DHCP_END": str(read_env_file(AP_ENV_PATH).get("DHCP_END", "10.10.10.150")).strip() or "10.10.10.150",
|
||||
"DHCP_LEASE": str(read_env_file(AP_ENV_PATH).get("DHCP_LEASE", "12h")).strip() or "12h",
|
||||
"SSID": current["ssid"],
|
||||
"PASSWORD_MODE": normalized_mode,
|
||||
"CUSTOM_PASSWORD": custom_password if normalized_mode == "custom" else "",
|
||||
"UI_PORT": current["ui_port"],
|
||||
}
|
||||
write_env_file(AP_ENV_PATH, env)
|
||||
|
||||
|
||||
def restart_ap_soft(ap_state):
|
||||
if not ap_state.get("service_installed"):
|
||||
return
|
||||
if ap_state.get("ap_enabled"):
|
||||
run([AP_DOWN_SCRIPT], timeout=10)
|
||||
run([AP_UP_SCRIPT], timeout=10)
|
||||
|
||||
|
||||
def public_ap_status():
|
||||
state = load_ap_state()
|
||||
return {
|
||||
"ok": True,
|
||||
"ap_enabled": state["ap_enabled"],
|
||||
"ssid": state["ssid"],
|
||||
"password_mode": state["password_mode"],
|
||||
"iface": state["iface"],
|
||||
"service_state": state["service_state"],
|
||||
}
|
||||
|
||||
|
||||
def ap_status_card():
|
||||
status = load_ap_state()
|
||||
installed = status["service_installed"] or file_exists(AP_ENV_PATH)
|
||||
configured = file_exists(AP_SYNC_SCRIPT)
|
||||
active = bool(status["ap_enabled"])
|
||||
state = "active" if active else "inactive"
|
||||
status_text = "AP enabled" if active else "AP disabled"
|
||||
return {
|
||||
"id": "access_point",
|
||||
"title": "Access Point",
|
||||
"installed": installed,
|
||||
"configured": configured,
|
||||
"active": active,
|
||||
"state": state,
|
||||
"status_text": status_text,
|
||||
"details": [
|
||||
{"label": "SSID", "value": status["ssid"]},
|
||||
{"label": "Password mode", "value": status["password_mode"].capitalize()},
|
||||
{"label": "Interface", "value": status["iface"]},
|
||||
],
|
||||
"ap_status": public_ap_status(),
|
||||
"errors": [],
|
||||
"warnings": [],
|
||||
}
|
||||
|
||||
|
||||
def invalidate_cache():
|
||||
_CACHE["payload"] = None
|
||||
_CACHE["expires_at"] = 0.0
|
||||
|
||||
|
||||
def systemd_unit(unit_name):
|
||||
properties = [
|
||||
"LoadState",
|
||||
|
|
@ -158,6 +328,8 @@ def normalize_card(card):
|
|||
item["connectors"] = [connector for connector in item.get("connectors", []) if isinstance(connector, dict)]
|
||||
status = item.get("display_status")
|
||||
item["display_status"] = status if isinstance(status, dict) else {}
|
||||
ap_status = item.get("ap_status")
|
||||
item["ap_status"] = ap_status if isinstance(ap_status, dict) else {}
|
||||
return item
|
||||
|
||||
|
||||
|
|
@ -192,6 +364,7 @@ def build_status_payload():
|
|||
"read_env_file": read_env_file,
|
||||
"systemd_unit": systemd_unit,
|
||||
"run": run,
|
||||
"get_ap_status_card": ap_status_card,
|
||||
}
|
||||
cards = []
|
||||
provider_names = []
|
||||
|
|
@ -250,6 +423,15 @@ class Handler(BaseHTTPRequestHandler):
|
|||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def read_json_body(self):
|
||||
size = int(self.headers.get("Content-Length", "0") or "0")
|
||||
raw = self.rfile.read(size) if size > 0 else b"{}"
|
||||
try:
|
||||
data = json.loads(raw.decode("utf-8"))
|
||||
except Exception:
|
||||
return None
|
||||
return data if isinstance(data, dict) else None
|
||||
|
||||
def send_file(self, path, content_type):
|
||||
try:
|
||||
with open(path, "rb") as fh:
|
||||
|
|
@ -275,6 +457,12 @@ class Handler(BaseHTTPRequestHandler):
|
|||
return
|
||||
self.send_json(payload)
|
||||
return
|
||||
if parsed.path == "/api/ap/status":
|
||||
try:
|
||||
self.send_json(public_ap_status())
|
||||
except Exception as exc:
|
||||
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")
|
||||
return
|
||||
|
|
@ -292,6 +480,91 @@ class Handler(BaseHTTPRequestHandler):
|
|||
return
|
||||
self.send_error(404)
|
||||
|
||||
def do_POST(self):
|
||||
parsed = urlparse(self.path)
|
||||
if parsed.path == "/api/ap/password/change":
|
||||
payload = self.read_json_body()
|
||||
if payload is None:
|
||||
self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400)
|
||||
return
|
||||
current_password = str(payload.get("current_password", ""))
|
||||
new_password = str(payload.get("new_password", ""))
|
||||
confirm_password = str(payload.get("confirm_password", ""))
|
||||
|
||||
if not current_password.strip():
|
||||
self.send_json({"ok": False, "error": "Current password is required"}, code=400)
|
||||
return
|
||||
if not new_password.strip() or not confirm_password.strip():
|
||||
self.send_json({"ok": False, "error": "New password and confirmation are required"}, code=400)
|
||||
return
|
||||
if new_password != confirm_password:
|
||||
self.send_json({"ok": False, "error": "Passwords do not match"}, code=400)
|
||||
return
|
||||
if not AP_PASSWORD_RE.fullmatch(new_password):
|
||||
self.send_json({"ok": False, "error": "Password must be at least 8 characters long and contain only lowercase letters and digits"}, code=400)
|
||||
return
|
||||
|
||||
try:
|
||||
state = load_ap_state()
|
||||
except Exception as exc:
|
||||
self.send_json({"ok": False, "error": str(exc)}, code=500)
|
||||
return
|
||||
if current_password != state["active_password"]:
|
||||
self.send_json({"ok": False, "error": "Current password is incorrect"}, code=403)
|
||||
return
|
||||
|
||||
try:
|
||||
write_ap_state("custom", new_password)
|
||||
rc, _, stderr = run([AP_SYNC_SCRIPT], timeout=10)
|
||||
if rc != 0:
|
||||
raise RuntimeError(stderr or "Failed to apply AP config")
|
||||
restart_ap_soft(state)
|
||||
invalidate_cache()
|
||||
fresh = load_ap_state()
|
||||
self.send_json({
|
||||
"ok": True,
|
||||
"password_mode": fresh["password_mode"],
|
||||
"ssid": fresh["ssid"],
|
||||
"message": "AP password changed successfully",
|
||||
})
|
||||
return
|
||||
except Exception as exc:
|
||||
self.send_json({"ok": False, "error": str(exc)}, code=500)
|
||||
return
|
||||
|
||||
if parsed.path == "/api/ap/password/reset":
|
||||
payload = self.read_json_body()
|
||||
if payload is None:
|
||||
self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400)
|
||||
return
|
||||
current_password = str(payload.get("current_password", ""))
|
||||
if not current_password.strip():
|
||||
self.send_json({"ok": False, "error": "Current password is required"}, code=400)
|
||||
return
|
||||
|
||||
try:
|
||||
state = load_ap_state()
|
||||
except Exception as exc:
|
||||
self.send_json({"ok": False, "error": str(exc)}, code=500)
|
||||
return
|
||||
if current_password != state["active_password"]:
|
||||
self.send_json({"ok": False, "error": "Current password is incorrect"}, code=403)
|
||||
return
|
||||
rc, _, stderr = run([AP_RESET_SCRIPT], timeout=15)
|
||||
if rc != 0:
|
||||
self.send_json({"ok": False, "error": stderr or "Failed to reset AP password"}, code=500)
|
||||
return
|
||||
invalidate_cache()
|
||||
fresh = load_ap_state()
|
||||
self.send_json({
|
||||
"ok": True,
|
||||
"password_mode": fresh["password_mode"],
|
||||
"message": "AP password reset to factory mode",
|
||||
})
|
||||
return
|
||||
|
||||
self.send_error(404)
|
||||
|
||||
|
||||
def main():
|
||||
cfg = load_config()
|
||||
|
|
|
|||
|
|
@ -75,6 +75,7 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
|
|||
.empty{
|
||||
padding:32px;border:1px dashed var(--line);border-radius:18px;background:rgba(255,255,255,.6);color:var(--muted);text-align:center;
|
||||
}
|
||||
.accessPointCard{grid-column:span 2}
|
||||
.displayCard{grid-column:span 2}
|
||||
.displayHero{
|
||||
margin-top:16px;padding:16px 18px;border-radius:16px;border:1px solid var(--line);
|
||||
|
|
@ -93,11 +94,46 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
|
|||
.connectorState.is-idle{background:rgba(154,106,0,.10);color:var(--warn)}
|
||||
.connectorMeta{margin-top:0}
|
||||
.emptyInline{color:var(--muted);font-size:14px}
|
||||
.apHero{
|
||||
margin-top:16px;padding:16px 18px;border-radius:16px;border:1px solid var(--line);
|
||||
display:flex;justify-content:space-between;gap:14px;align-items:flex-start;flex-wrap:wrap;
|
||||
}
|
||||
.apHero.is-enabled{background:rgba(14,122,83,.08)}
|
||||
.apHero.is-disabled{background:#f7f8f7}
|
||||
.modeBadge{
|
||||
display:inline-flex;align-items:center;border-radius:999px;padding:6px 10px;font-size:12px;font-weight:700;
|
||||
}
|
||||
.modeBadge.is-factory{background:rgba(154,106,0,.10);color:var(--warn)}
|
||||
.modeBadge.is-custom{background:rgba(14,122,83,.10);color:var(--accent)}
|
||||
.actionRow{display:flex;gap:10px;flex-wrap:wrap}
|
||||
.actionBtn{
|
||||
border:0;border-radius:12px;background:var(--ink);color:#fff;padding:10px 14px;font-weight:700;cursor:pointer;
|
||||
}
|
||||
.actionBtn.secondary{background:#eef3f1;color:var(--ink);border:1px solid var(--line)}
|
||||
.actionBtn:disabled{opacity:.5;cursor:not-allowed}
|
||||
.apForm{display:grid;gap:12px}
|
||||
.field{display:grid;gap:6px;font-size:13px;color:var(--ink)}
|
||||
.passwordField{display:flex;gap:8px;align-items:center}
|
||||
.field input{
|
||||
width:100%;padding:10px 12px;border-radius:12px;border:1px solid var(--line);background:#fff;color:var(--ink);
|
||||
}
|
||||
.passwordField input{flex:1 1 auto}
|
||||
.toggleInlineBtn{
|
||||
border:1px solid var(--line);border-radius:12px;background:#f6f8f7;color:var(--ink);padding:10px 12px;font-weight:700;cursor:pointer;white-space:nowrap;
|
||||
}
|
||||
.formHint{font-size:12px;color:var(--muted)}
|
||||
.formError{font-size:12px;color:var(--error);font-weight:600}
|
||||
.banner{
|
||||
margin-top:14px;padding:12px 14px;border-radius:14px;font-size:13px;font-weight:600;
|
||||
}
|
||||
.banner.success{background:rgba(14,122,83,.10);color:var(--accent)}
|
||||
.banner.error{background:rgba(185,52,52,.10);color:var(--error)}
|
||||
@media (max-width:720px){
|
||||
.summary{grid-template-columns:1fr}
|
||||
.meta{grid-template-columns:1fr 1fr}
|
||||
.brand{align-items:center}
|
||||
.brandLogo{width:58px;height:58px}
|
||||
.accessPointCard{grid-column:auto}
|
||||
.displayCard{grid-column:auto}
|
||||
.displayHeroText{font-size:18px}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,6 +9,22 @@
|
|||
serviceCount: document.getElementById("serviceCount"),
|
||||
deviceName: document.getElementById("deviceName")
|
||||
};
|
||||
const apUi = {
|
||||
formOpen: false,
|
||||
resetOpen: false,
|
||||
busy: false,
|
||||
message: "",
|
||||
error: "",
|
||||
currentPassword: "",
|
||||
newPassword: "",
|
||||
confirmPassword: "",
|
||||
resetPassword: "",
|
||||
showCurrentPassword: false,
|
||||
showNewPassword: false,
|
||||
showConfirmPassword: false,
|
||||
showResetPassword: false
|
||||
};
|
||||
let latestPayload = null;
|
||||
|
||||
function esc(value) {
|
||||
return (value ?? "").toString().replace(/[&<>"']/g, (m) => ({
|
||||
|
|
@ -35,6 +51,37 @@
|
|||
return "warn";
|
||||
}
|
||||
|
||||
function clearApFeedback() {
|
||||
apUi.message = "";
|
||||
apUi.error = "";
|
||||
}
|
||||
|
||||
function changePasswordError() {
|
||||
const current = apUi.currentPassword.trim();
|
||||
const next = apUi.newPassword.trim();
|
||||
const confirm = apUi.confirmPassword.trim();
|
||||
if (!current) return "Current password is required";
|
||||
if (!next) return "Password must be at least 8 characters long";
|
||||
if (next.length < 8) return "Password must be at least 8 characters long";
|
||||
if (!/^[a-z0-9]+$/.test(next)) return "Password must contain only lowercase letters and digits";
|
||||
if (next !== confirm) return "Passwords do not match";
|
||||
return "";
|
||||
}
|
||||
|
||||
async function postJson(url, body) {
|
||||
const response = await fetch(url, {
|
||||
method: "POST",
|
||||
cache: "no-store",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body)
|
||||
});
|
||||
const payload = await response.json().catch(() => ({}));
|
||||
if (!response.ok || payload.ok === false) {
|
||||
throw new Error(payload.error || `HTTP ${response.status}`);
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
|
||||
function renderKeyValueRows(items) {
|
||||
return items.map((item) => `
|
||||
<div class="key">${esc(item.label || "-")}</div>
|
||||
|
|
@ -126,8 +173,162 @@
|
|||
`;
|
||||
}
|
||||
|
||||
function updateApFeedback() {
|
||||
const success = document.getElementById("apBannerSuccess");
|
||||
const error = document.getElementById("apBannerError");
|
||||
if (success) {
|
||||
success.textContent = apUi.message || "";
|
||||
success.hidden = !apUi.message;
|
||||
}
|
||||
if (error) {
|
||||
error.textContent = apUi.error || "";
|
||||
error.hidden = !apUi.error;
|
||||
}
|
||||
}
|
||||
|
||||
function updateApFormUi() {
|
||||
const validationError = changePasswordError();
|
||||
const applyBtn = document.getElementById("apApplyBtn");
|
||||
const errorNode = document.getElementById("apFormError");
|
||||
const resetBtn = document.getElementById("apResetBtn");
|
||||
const currentInput = document.getElementById("apCurrentPassword");
|
||||
const newInput = document.getElementById("apNewPassword");
|
||||
const confirmInput = document.getElementById("apConfirmPassword");
|
||||
const resetInput = document.getElementById("apResetPassword");
|
||||
const currentToggle = document.getElementById("apCurrentPasswordToggle");
|
||||
const newToggle = document.getElementById("apNewPasswordToggle");
|
||||
const confirmToggle = document.getElementById("apConfirmPasswordToggle");
|
||||
const resetToggle = document.getElementById("apResetPasswordToggle");
|
||||
|
||||
if (applyBtn) applyBtn.disabled = !!(apUi.busy || !apUi.formOpen || validationError);
|
||||
if (errorNode) {
|
||||
errorNode.textContent = validationError || "";
|
||||
errorNode.hidden = !validationError;
|
||||
}
|
||||
if (resetBtn) resetBtn.disabled = !!(apUi.busy || !apUi.resetPassword.trim());
|
||||
|
||||
if (currentInput) currentInput.type = apUi.showCurrentPassword ? "text" : "password";
|
||||
if (newInput) newInput.type = apUi.showNewPassword ? "text" : "password";
|
||||
if (confirmInput) confirmInput.type = apUi.showConfirmPassword ? "text" : "password";
|
||||
if (resetInput) resetInput.type = apUi.showResetPassword ? "text" : "password";
|
||||
|
||||
if (currentToggle) currentToggle.textContent = apUi.showCurrentPassword ? "Hide" : "Show";
|
||||
if (newToggle) newToggle.textContent = apUi.showNewPassword ? "Hide" : "Show";
|
||||
if (confirmToggle) confirmToggle.textContent = apUi.showConfirmPassword ? "Hide" : "Show";
|
||||
if (resetToggle) resetToggle.textContent = apUi.showResetPassword ? "Hide" : "Show";
|
||||
|
||||
updateApFeedback();
|
||||
}
|
||||
|
||||
function renderAccessPointCard(card) {
|
||||
const tone = statusTone(card);
|
||||
const ap = card.ap_status || {};
|
||||
const details = Array.isArray(card.details) ? card.details : [];
|
||||
const mode = (ap.password_mode || "factory").toString().toLowerCase();
|
||||
const changeError = changePasswordError();
|
||||
const canApply = !apUi.busy && apUi.formOpen && !changeError;
|
||||
const canReset = !apUi.busy && apUi.resetPassword.trim();
|
||||
|
||||
return `
|
||||
<article class="panel card accessPointCard">
|
||||
<div class="cardTop">
|
||||
<div>
|
||||
<h2>${esc(card.title)}</h2>
|
||||
<div class="badge"><span class="dot ${tone}"></span>${esc(card.status_text || card.state || "Unknown")}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<section class="apHero ${ap.ap_enabled ? "is-enabled" : "is-disabled"}">
|
||||
<div>
|
||||
<div class="displayHeroLabel">Access point</div>
|
||||
<div class="displayHeroText">${esc(ap.ap_enabled ? "Enabled" : "Disabled")}</div>
|
||||
</div>
|
||||
<div class="displayHeroMeta">
|
||||
<span class="modeBadge ${mode === "custom" ? "is-custom" : "is-factory"}">${esc(mode === "custom" ? "Custom" : "Factory")}</span>
|
||||
<span>${esc(`SSID: ${textValue(ap.ssid)}`)}</span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div class="meta">${renderKeyValueRows(details)}</div>
|
||||
|
||||
<div id="apBannerSuccess" class="banner success" ${apUi.message ? "" : "hidden"}>${esc(apUi.message)}</div>
|
||||
<div id="apBannerError" class="banner error" ${apUi.error ? "" : "hidden"}>${esc(apUi.error)}</div>
|
||||
|
||||
<div class="list">
|
||||
<div class="listTitle">Actions</div>
|
||||
<div class="actionRow">
|
||||
<button class="actionBtn" type="button" ${apUi.busy ? "disabled" : ""} onclick="window.__toggleApForm()">
|
||||
${esc(mode === "custom" ? "Change password" : "Set custom password")}
|
||||
</button>
|
||||
${mode === "custom"
|
||||
? `<button class="actionBtn secondary" type="button" ${apUi.busy ? "disabled" : ""} onclick="window.__toggleApReset()">Reset to factory password</button>`
|
||||
: ""}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
${apUi.formOpen ? `
|
||||
<div class="list">
|
||||
<div class="listTitle">Set custom password</div>
|
||||
<div class="apForm">
|
||||
<label class="field">
|
||||
<span>Current password</span>
|
||||
<div class="passwordField">
|
||||
<input id="apCurrentPassword" type="${apUi.showCurrentPassword ? "text" : "password"}" value="${esc(apUi.currentPassword)}" oninput="window.__setApField('currentPassword', this.value)">
|
||||
<button id="apCurrentPasswordToggle" class="toggleInlineBtn" type="button" onclick="window.__toggleApPasswordVisibility('showCurrentPassword')">${esc(apUi.showCurrentPassword ? "Hide" : "Show")}</button>
|
||||
</div>
|
||||
</label>
|
||||
<label class="field">
|
||||
<span>New password</span>
|
||||
<div class="passwordField">
|
||||
<input id="apNewPassword" type="${apUi.showNewPassword ? "text" : "password"}" value="${esc(apUi.newPassword)}" oninput="window.__setApField('newPassword', this.value)">
|
||||
<button id="apNewPasswordToggle" class="toggleInlineBtn" type="button" onclick="window.__toggleApPasswordVisibility('showNewPassword')">${esc(apUi.showNewPassword ? "Hide" : "Show")}</button>
|
||||
</div>
|
||||
</label>
|
||||
<label class="field">
|
||||
<span>Confirm new password</span>
|
||||
<div class="passwordField">
|
||||
<input id="apConfirmPassword" type="${apUi.showConfirmPassword ? "text" : "password"}" value="${esc(apUi.confirmPassword)}" oninput="window.__setApField('confirmPassword', this.value)">
|
||||
<button id="apConfirmPasswordToggle" class="toggleInlineBtn" type="button" onclick="window.__toggleApPasswordVisibility('showConfirmPassword')">${esc(apUi.showConfirmPassword ? "Hide" : "Show")}</button>
|
||||
</div>
|
||||
</label>
|
||||
<div class="formHint">Use at least 8 characters. Allowed symbols: lowercase letters and digits.</div>
|
||||
<div id="apFormError" class="formError" ${changeError ? "" : "hidden"}>${esc(changeError)}</div>
|
||||
<div class="actionRow">
|
||||
<button id="apApplyBtn" class="actionBtn" type="button" ${canApply ? "" : "disabled"} onclick="window.__submitApPasswordChange()">
|
||||
${esc(apUi.busy ? "Applying..." : "Apply")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
` : ""}
|
||||
|
||||
${apUi.resetOpen ? `
|
||||
<div class="list">
|
||||
<div class="listTitle">Reset to factory password</div>
|
||||
<div class="apForm">
|
||||
<label class="field">
|
||||
<span>Current password</span>
|
||||
<div class="passwordField">
|
||||
<input id="apResetPassword" type="${apUi.showResetPassword ? "text" : "password"}" value="${esc(apUi.resetPassword)}" oninput="window.__setApField('resetPassword', this.value)">
|
||||
<button id="apResetPasswordToggle" class="toggleInlineBtn" type="button" onclick="window.__toggleApPasswordVisibility('showResetPassword')">${esc(apUi.showResetPassword ? "Hide" : "Show")}</button>
|
||||
</div>
|
||||
</label>
|
||||
<div class="formHint">Reset returns Access Point authentication to deterministic factory mode.</div>
|
||||
<div class="actionRow">
|
||||
<button id="apResetBtn" class="actionBtn secondary" type="button" ${canReset ? "" : "disabled"} onclick="window.__submitApPasswordReset()">
|
||||
${esc(apUi.busy ? "Resetting..." : "Confirm reset")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
` : ""}
|
||||
</article>
|
||||
`;
|
||||
}
|
||||
|
||||
function renderCard(card) {
|
||||
if (card.id === "display") return renderDisplayCard(card);
|
||||
if (card.id === "access_point") return renderAccessPointCard(card);
|
||||
|
||||
const tone = statusTone(card);
|
||||
const warnings = Array.isArray(card.warnings) ? card.warnings : [];
|
||||
|
|
@ -183,6 +384,7 @@
|
|||
}
|
||||
|
||||
function render(payload) {
|
||||
latestPayload = payload;
|
||||
const services = Array.isArray(payload.services) ? payload.services : [];
|
||||
const providers = Array.isArray(payload.providers) ? payload.providers : [];
|
||||
|
||||
|
|
@ -199,6 +401,13 @@
|
|||
nodes.cards.innerHTML = services.map(renderCard).join("");
|
||||
}
|
||||
|
||||
function rerender() {
|
||||
if (latestPayload) {
|
||||
render(latestPayload);
|
||||
updateApFormUi();
|
||||
}
|
||||
}
|
||||
|
||||
async function load() {
|
||||
nodes.refreshBtn.disabled = true;
|
||||
try {
|
||||
|
|
@ -213,6 +422,103 @@
|
|||
}
|
||||
}
|
||||
|
||||
window.__toggleApForm = function () {
|
||||
apUi.formOpen = !apUi.formOpen;
|
||||
if (!apUi.formOpen) {
|
||||
apUi.currentPassword = "";
|
||||
apUi.newPassword = "";
|
||||
apUi.confirmPassword = "";
|
||||
apUi.showCurrentPassword = false;
|
||||
apUi.showNewPassword = false;
|
||||
apUi.showConfirmPassword = false;
|
||||
}
|
||||
clearApFeedback();
|
||||
rerender();
|
||||
};
|
||||
|
||||
window.__toggleApReset = function () {
|
||||
apUi.resetOpen = !apUi.resetOpen;
|
||||
if (!apUi.resetOpen) {
|
||||
apUi.resetPassword = "";
|
||||
apUi.showResetPassword = false;
|
||||
}
|
||||
clearApFeedback();
|
||||
rerender();
|
||||
};
|
||||
|
||||
window.__setApField = function (field, value) {
|
||||
apUi[field] = value;
|
||||
clearApFeedback();
|
||||
updateApFormUi();
|
||||
};
|
||||
|
||||
window.__toggleApPasswordVisibility = function (field) {
|
||||
apUi[field] = !apUi[field];
|
||||
updateApFormUi();
|
||||
};
|
||||
|
||||
window.__submitApPasswordChange = async function () {
|
||||
const validationError = changePasswordError();
|
||||
if (validationError) {
|
||||
apUi.error = validationError;
|
||||
updateApFormUi();
|
||||
return;
|
||||
}
|
||||
apUi.busy = true;
|
||||
clearApFeedback();
|
||||
rerender();
|
||||
try {
|
||||
await postJson("/api/ap/password/change", {
|
||||
current_password: apUi.currentPassword,
|
||||
new_password: apUi.newPassword,
|
||||
confirm_password: apUi.confirmPassword
|
||||
});
|
||||
apUi.message = "Access point password changed. Reconnect using the new password.";
|
||||
apUi.formOpen = false;
|
||||
apUi.currentPassword = "";
|
||||
apUi.newPassword = "";
|
||||
apUi.confirmPassword = "";
|
||||
apUi.showCurrentPassword = false;
|
||||
apUi.showNewPassword = false;
|
||||
apUi.showConfirmPassword = false;
|
||||
await load();
|
||||
} catch (error) {
|
||||
apUi.error = error.message || "Failed to apply AP password change";
|
||||
await load();
|
||||
} finally {
|
||||
apUi.busy = false;
|
||||
await load();
|
||||
}
|
||||
};
|
||||
|
||||
window.__submitApPasswordReset = async function () {
|
||||
if (!apUi.resetPassword.trim()) {
|
||||
apUi.error = "Current password is required";
|
||||
updateApFormUi();
|
||||
return;
|
||||
}
|
||||
if (!window.confirm("Reset Access Point password to factory mode?")) return;
|
||||
apUi.busy = true;
|
||||
clearApFeedback();
|
||||
rerender();
|
||||
try {
|
||||
await postJson("/api/ap/password/reset", {
|
||||
current_password: apUi.resetPassword
|
||||
});
|
||||
apUi.message = "Access point password reset to factory mode.";
|
||||
apUi.resetOpen = false;
|
||||
apUi.resetPassword = "";
|
||||
apUi.showResetPassword = false;
|
||||
await load();
|
||||
} catch (error) {
|
||||
apUi.error = error.message || "Failed to apply AP password change";
|
||||
await load();
|
||||
} finally {
|
||||
apUi.busy = false;
|
||||
await load();
|
||||
}
|
||||
};
|
||||
|
||||
nodes.refreshBtn.addEventListener("click", load);
|
||||
load();
|
||||
})();
|
||||
|
|
|
|||
|
|
@ -674,6 +674,24 @@ def display_card(ctx):
|
|||
)
|
||||
|
||||
|
||||
def access_point_card(ctx):
|
||||
payload = ctx["get_ap_status_card"]()
|
||||
return _service_card(
|
||||
payload["id"],
|
||||
payload["title"],
|
||||
"",
|
||||
payload["installed"],
|
||||
payload["configured"],
|
||||
payload["active"],
|
||||
payload["state"],
|
||||
payload["status_text"],
|
||||
payload.get("errors", []),
|
||||
payload.get("warnings", []),
|
||||
details=payload.get("details", []),
|
||||
ap_status=payload.get("ap_status", {}),
|
||||
)
|
||||
|
||||
|
||||
def placeholder_card(service_id, title):
|
||||
state, status_text = _lifecycle(False, False, False)
|
||||
return _service_card(
|
||||
|
|
@ -697,6 +715,7 @@ def get_cards(ctx):
|
|||
mqtt_bridge_card(ctx),
|
||||
zigbee_card(ctx),
|
||||
reverse_tunnel_card(ctx),
|
||||
access_point_card(ctx),
|
||||
display_card(ctx),
|
||||
placeholder_card("edge_api", "Edge API"),
|
||||
]
|
||||
|
|
|
|||
|
|
@ -12,8 +12,8 @@ set -euo pipefail
|
|||
# - UI "Connect" => AP down -> try STA connect -> if fail -> AP back
|
||||
#
|
||||
# Defaults:
|
||||
# - AP SSID = hostname
|
||||
# - AP PASS = iomatex123
|
||||
# - AP SSID = Iomatex <hostname>
|
||||
# - AP PASS = factory/custom mode (factory derived from device serial)
|
||||
# - AP IP = 10.10.10.1/24
|
||||
# - UI port = 18080
|
||||
# ======================================
|
||||
|
|
@ -33,8 +33,8 @@ DHCP_START="10.10.10.50"
|
|||
DHCP_END="10.10.10.150"
|
||||
DHCP_LEASE="12h"
|
||||
UI_PORT="18080"
|
||||
SSID="$(hostname -s)"
|
||||
PASS="iomatex123"
|
||||
SSID=""
|
||||
PASS=""
|
||||
COUNTRY_CODE="NL"
|
||||
AP_CHANNEL="6"
|
||||
|
||||
|
|
@ -43,6 +43,9 @@ LAST_WRITE_CHANGED=0
|
|||
SYSTEMD_UNITS_CHANGED=0
|
||||
UI_SERVICE_CHANGED=0
|
||||
WATCH_SERVICE_CHANGED=0
|
||||
RESETD_SERVICE_CHANGED=0
|
||||
EXISTING_PASSWORD_MODE=""
|
||||
EXISTING_CUSTOM_PASSWORD=""
|
||||
|
||||
log() {
|
||||
local line="[$(date -u +'%F %T UTC')] $*"
|
||||
|
|
@ -79,6 +82,105 @@ have() {
|
|||
command -v "$1" >/dev/null 2>&1
|
||||
}
|
||||
|
||||
trim_text() {
|
||||
printf '%s' "$1" | sed -E 's/^[[:space:]]+//; s/[[:space:]]+$//'
|
||||
}
|
||||
|
||||
load_env_value() {
|
||||
local path="$1"
|
||||
local key="$2"
|
||||
awk -F= -v k="$key" '
|
||||
$0 ~ "^[[:space:]]*" k "=" {
|
||||
v = substr($0, index($0, "=") + 1)
|
||||
gsub(/^[[:space:]]+|[[:space:]]+$/, "", v)
|
||||
gsub(/^["\047]|["\047]$/, "", v)
|
||||
print v
|
||||
exit
|
||||
}
|
||||
' "$path" 2>/dev/null || true
|
||||
}
|
||||
|
||||
get_system_hostname() {
|
||||
local host=""
|
||||
host="$(hostname -s 2>/dev/null || hostname 2>/dev/null || true)"
|
||||
host="$(trim_text "$host")"
|
||||
if [[ -z "$host" ]]; then
|
||||
log "ERROR: failed to determine system hostname"
|
||||
exit 1
|
||||
fi
|
||||
printf '%s\n' "$host"
|
||||
}
|
||||
|
||||
get_device_serial() {
|
||||
local serial=""
|
||||
serial="$(cat /proc/cpuinfo | grep Serial | awk '{print $3}' | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]' | head -n1)"
|
||||
if [[ -z "$serial" ]]; then
|
||||
log "ERROR: failed to read device serial from /proc/cpuinfo"
|
||||
exit 1
|
||||
fi
|
||||
printf '%s\n' "$serial"
|
||||
}
|
||||
|
||||
build_ap_ssid() {
|
||||
local host="$1"
|
||||
printf 'Iomatex %s\n' "$host"
|
||||
}
|
||||
|
||||
generate_factory_ap_password() {
|
||||
local serial="$1"
|
||||
local secret="iomatex_the_best"
|
||||
local digest=""
|
||||
local password=""
|
||||
|
||||
if [[ -z "$serial" ]]; then
|
||||
log "ERROR: device serial is empty; cannot generate factory AP password"
|
||||
exit 1
|
||||
fi
|
||||
if ! have sha256sum; then
|
||||
log "ERROR: required command not found: sha256sum"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
digest="$(printf '%s' "${secret}${serial}" | sha256sum | awk '{print $1}' | tr '[:upper:]' '[:lower:]' | tr -cd 'a-z0-9')"
|
||||
password="${digest:0:8}"
|
||||
if [[ ! "$password" =~ ^[a-z0-9]{8}$ ]]; then
|
||||
log "ERROR: failed to generate valid factory AP password from device serial"
|
||||
exit 1
|
||||
fi
|
||||
printf '%s\n' "$password"
|
||||
}
|
||||
|
||||
normalize_password_mode() {
|
||||
local mode
|
||||
mode="$(printf '%s' "${1:-}" | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]')"
|
||||
case "$mode" in
|
||||
custom) printf 'custom\n' ;;
|
||||
*) printf 'factory\n' ;;
|
||||
esac
|
||||
}
|
||||
|
||||
load_existing_ap_state() {
|
||||
local env_path="/etc/iomatex/ap.env"
|
||||
if [[ ! -f "$env_path" ]]; then
|
||||
EXISTING_PASSWORD_MODE="factory"
|
||||
EXISTING_CUSTOM_PASSWORD=""
|
||||
return 0
|
||||
fi
|
||||
EXISTING_PASSWORD_MODE="$(normalize_password_mode "$(load_env_value "$env_path" "PASSWORD_MODE")")"
|
||||
EXISTING_CUSTOM_PASSWORD="$(load_env_value "$env_path" "CUSTOM_PASSWORD")"
|
||||
}
|
||||
|
||||
get_active_ap_password() {
|
||||
local mode="$1"
|
||||
local custom_password="$2"
|
||||
local factory_password="$3"
|
||||
if [[ "$mode" == "custom" && -n "$custom_password" ]]; then
|
||||
printf '%s\n' "$custom_password"
|
||||
return 0
|
||||
fi
|
||||
printf '%s\n' "$factory_password"
|
||||
}
|
||||
|
||||
backup_if_exists() {
|
||||
local path="$1"
|
||||
local ts
|
||||
|
|
@ -151,6 +253,23 @@ apt_install_missing() {
|
|||
apt-get install -y "${missing[@]}"
|
||||
}
|
||||
|
||||
HOSTNAME_SHORT="$(get_system_hostname)"
|
||||
DEVICE_SERIAL="$(get_device_serial)"
|
||||
FACTORY_AP_PASSWORD="$(generate_factory_ap_password "$DEVICE_SERIAL")"
|
||||
load_existing_ap_state
|
||||
PASSWORD_MODE="$(normalize_password_mode "$EXISTING_PASSWORD_MODE")"
|
||||
CUSTOM_PASSWORD="$EXISTING_CUSTOM_PASSWORD"
|
||||
if [[ "$PASSWORD_MODE" == "custom" && -z "$CUSTOM_PASSWORD" ]]; then
|
||||
PASSWORD_MODE="factory"
|
||||
fi
|
||||
SSID="$(build_ap_ssid "$HOSTNAME_SHORT")"
|
||||
PASS="$(get_active_ap_password "$PASSWORD_MODE" "$CUSTOM_PASSWORD" "$FACTORY_AP_PASSWORD")"
|
||||
log "Resolved hostname for AP SSID: ${HOSTNAME_SHORT}"
|
||||
log "Resolved device serial from system"
|
||||
log "Factory AP password computed from device serial"
|
||||
log "AP password mode resolved: ${PASSWORD_MODE}"
|
||||
log "Selected AP SSID: ${SSID}"
|
||||
|
||||
systemctl_try() {
|
||||
systemctl "$@" >/dev/null 2>&1 || true
|
||||
}
|
||||
|
|
@ -238,7 +357,8 @@ DHCP_START="$DHCP_START"
|
|||
DHCP_END="$DHCP_END"
|
||||
DHCP_LEASE="$DHCP_LEASE"
|
||||
SSID="$SSID"
|
||||
WPA_PASSPHRASE="$PASS"
|
||||
PASSWORD_MODE="$PASSWORD_MODE"
|
||||
CUSTOM_PASSWORD="$CUSTOM_PASSWORD"
|
||||
UI_PORT="$UI_PORT"
|
||||
EOF
|
||||
|
||||
|
|
@ -472,11 +592,182 @@ if [[ "$LAST_WRITE_CHANGED" -eq 1 ]]; then
|
|||
fi
|
||||
|
||||
step "Write control scripts"
|
||||
write_managed_file /usr/local/sbin/iomatex-ap-sync-config 0755 <<'EOF'
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
ENV_PATH="/etc/iomatex/ap.env"
|
||||
HOSTAPD_PATH="/etc/hostapd/iomatex-ap.conf"
|
||||
COUNTRY_CODE="NL"
|
||||
AP_CHANNEL="6"
|
||||
|
||||
trim_text() {
|
||||
printf '%s' "$1" | sed -E 's/^[[:space:]]+//; s/[[:space:]]+$//'
|
||||
}
|
||||
|
||||
get_system_hostname() {
|
||||
local host=""
|
||||
host="$(hostname -s 2>/dev/null || hostname 2>/dev/null || true)"
|
||||
host="$(trim_text "$host")"
|
||||
[[ -n "$host" ]] || { echo "ERROR: failed to determine system hostname" >&2; exit 1; }
|
||||
printf '%s\n' "$host"
|
||||
}
|
||||
|
||||
get_device_serial() {
|
||||
local serial=""
|
||||
serial="$(cat /proc/cpuinfo | grep Serial | awk '{print $3}' | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]' | head -n1)"
|
||||
[[ -n "$serial" ]] || { echo "ERROR: failed to read device serial from /proc/cpuinfo" >&2; exit 1; }
|
||||
printf '%s\n' "$serial"
|
||||
}
|
||||
|
||||
build_ap_ssid() {
|
||||
printf 'Iomatex %s\n' "$1"
|
||||
}
|
||||
|
||||
generate_factory_ap_password() {
|
||||
local serial="$1"
|
||||
local digest=""
|
||||
digest="$(printf '%s' "iomatex_the_best${serial}" | sha256sum | awk '{print $1}' | tr '[:upper:]' '[:lower:]' | tr -cd 'a-z0-9')"
|
||||
local password="${digest:0:8}"
|
||||
[[ "$password" =~ ^[a-z0-9]{8}$ ]] || { echo "ERROR: failed to generate valid factory AP password" >&2; exit 1; }
|
||||
printf '%s\n' "$password"
|
||||
}
|
||||
|
||||
normalize_password_mode() {
|
||||
local mode
|
||||
mode="$(printf '%s' "${1:-}" | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]')"
|
||||
case "$mode" in
|
||||
custom) printf 'custom\n' ;;
|
||||
*) printf 'factory\n' ;;
|
||||
esac
|
||||
}
|
||||
|
||||
get_active_ap_password() {
|
||||
local mode="$1"
|
||||
local custom_password="$2"
|
||||
local factory_password="$3"
|
||||
if [[ "$mode" == "custom" && -n "$custom_password" ]]; then
|
||||
printf '%s\n' "$custom_password"
|
||||
return 0
|
||||
fi
|
||||
printf '%s\n' "$factory_password"
|
||||
}
|
||||
|
||||
IFACE="wlan0"
|
||||
AP_IP="10.10.10.1"
|
||||
AP_CIDR="${AP_IP}/24"
|
||||
DHCP_START="10.10.10.50"
|
||||
DHCP_END="10.10.10.150"
|
||||
DHCP_LEASE="12h"
|
||||
UI_PORT="18080"
|
||||
PASSWORD_MODE="factory"
|
||||
CUSTOM_PASSWORD=""
|
||||
|
||||
if [[ -f "$ENV_PATH" ]]; then
|
||||
. "$ENV_PATH"
|
||||
fi
|
||||
|
||||
PASSWORD_MODE="$(normalize_password_mode "${PASSWORD_MODE:-factory}")"
|
||||
CUSTOM_PASSWORD="${CUSTOM_PASSWORD:-}"
|
||||
if [[ "$PASSWORD_MODE" == "custom" && -z "$CUSTOM_PASSWORD" ]]; then
|
||||
PASSWORD_MODE="factory"
|
||||
fi
|
||||
|
||||
HOSTNAME_SHORT="$(get_system_hostname)"
|
||||
DEVICE_SERIAL="$(get_device_serial)"
|
||||
SSID="$(build_ap_ssid "$HOSTNAME_SHORT")"
|
||||
FACTORY_PASSWORD="$(generate_factory_ap_password "$DEVICE_SERIAL")"
|
||||
ACTIVE_PASSWORD="$(get_active_ap_password "$PASSWORD_MODE" "$CUSTOM_PASSWORD" "$FACTORY_PASSWORD")"
|
||||
|
||||
tmp_env="$(mktemp)"
|
||||
cat >"$tmp_env" <<ENVEOF
|
||||
IFACE="$IFACE"
|
||||
AP_IP="$AP_IP"
|
||||
AP_CIDR="$AP_CIDR"
|
||||
DHCP_START="$DHCP_START"
|
||||
DHCP_END="$DHCP_END"
|
||||
DHCP_LEASE="$DHCP_LEASE"
|
||||
SSID="$SSID"
|
||||
PASSWORD_MODE="$PASSWORD_MODE"
|
||||
CUSTOM_PASSWORD="$CUSTOM_PASSWORD"
|
||||
UI_PORT="$UI_PORT"
|
||||
ENVEOF
|
||||
install -D -m 0644 "$tmp_env" "$ENV_PATH"
|
||||
rm -f "$tmp_env"
|
||||
|
||||
tmp_hostapd="$(mktemp)"
|
||||
cat >"$tmp_hostapd" <<HOSTEOF
|
||||
interface=$IFACE
|
||||
driver=nl80211
|
||||
ssid=$SSID
|
||||
hw_mode=g
|
||||
channel=$AP_CHANNEL
|
||||
country_code=$COUNTRY_CODE
|
||||
ieee80211n=1
|
||||
wmm_enabled=1
|
||||
auth_algs=1
|
||||
ignore_broadcast_ssid=0
|
||||
wpa=2
|
||||
wpa_passphrase=$ACTIVE_PASSWORD
|
||||
wpa_key_mgmt=WPA-PSK
|
||||
rsn_pairwise=CCMP
|
||||
HOSTEOF
|
||||
install -D -m 0600 "$tmp_hostapd" "$HOSTAPD_PATH"
|
||||
rm -f "$tmp_hostapd"
|
||||
EOF
|
||||
|
||||
write_managed_file /usr/local/sbin/iomatex-ap-reset-password 0755 <<'EOF'
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
ENV_PATH="/etc/iomatex/ap.env"
|
||||
IFACE="wlan0"
|
||||
AP_IP="10.10.10.1"
|
||||
AP_CIDR="${AP_IP}/24"
|
||||
DHCP_START="10.10.10.50"
|
||||
DHCP_END="10.10.10.150"
|
||||
DHCP_LEASE="12h"
|
||||
UI_PORT="18080"
|
||||
SSID=""
|
||||
|
||||
if [[ -f "$ENV_PATH" ]]; then
|
||||
. "$ENV_PATH"
|
||||
fi
|
||||
|
||||
tmp_env="$(mktemp)"
|
||||
cat >"$tmp_env" <<ENVEOF
|
||||
IFACE="$IFACE"
|
||||
AP_IP="$AP_IP"
|
||||
AP_CIDR="$AP_CIDR"
|
||||
DHCP_START="$DHCP_START"
|
||||
DHCP_END="$DHCP_END"
|
||||
DHCP_LEASE="$DHCP_LEASE"
|
||||
SSID="$SSID"
|
||||
PASSWORD_MODE="factory"
|
||||
CUSTOM_PASSWORD=""
|
||||
UI_PORT="$UI_PORT"
|
||||
ENVEOF
|
||||
install -D -m 0644 "$tmp_env" "$ENV_PATH"
|
||||
rm -f "$tmp_env"
|
||||
|
||||
/usr/local/sbin/iomatex-ap-sync-config
|
||||
/usr/local/sbin/iomatex-ap-down >/dev/null 2>&1 || true
|
||||
if command -v nmcli >/dev/null 2>&1; then
|
||||
nmcli dev disconnect "$IFACE" >/dev/null 2>&1 || true
|
||||
fi
|
||||
/usr/local/sbin/iomatex-ap-up >/dev/null 2>&1 || true
|
||||
|
||||
echo "OK: AP password reset to factory mode"
|
||||
EOF
|
||||
|
||||
write_managed_file /usr/local/sbin/iomatex-ap-up 0755 <<'EOF'
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
. /etc/iomatex/ap.env
|
||||
|
||||
/usr/local/sbin/iomatex-ap-sync-config >/dev/null 2>&1 || true
|
||||
. /etc/iomatex/ap.env
|
||||
|
||||
rfkill unblock all >/dev/null 2>&1 || true
|
||||
|
||||
if command -v nmcli >/dev/null 2>&1; then
|
||||
|
|
@ -488,6 +779,7 @@ ip link set "$IFACE" up >/dev/null 2>&1 || true
|
|||
ip addr flush dev "$IFACE" >/dev/null 2>&1 || true
|
||||
ip addr add "$AP_CIDR" dev "$IFACE"
|
||||
|
||||
systemctl start iomatex-wifi-ui.service >/dev/null 2>&1 || true
|
||||
systemctl start iomatex-dnsmasq.service
|
||||
systemctl start iomatex-hostapd.service
|
||||
|
||||
|
|
@ -559,6 +851,10 @@ LOCK="/run/iomatex-wifi-setup.lock"
|
|||
exec 9>"$LOCK"
|
||||
flock -n 9 || { echo "ERROR: busy" >&2; exit 4; }
|
||||
|
||||
AP_LOCK="/run/iomatex-ap.lock"
|
||||
exec 8>"$AP_LOCK"
|
||||
flock 8
|
||||
|
||||
CN="$(echo "$SSID_IN" | tr -cd "[:alnum:] ._-" | sed -E "s/[[:space:]]+/ /g" | cut -c1-64)"
|
||||
[ -n "$CN" ] || CN="iomatex-wifi"
|
||||
|
||||
|
|
@ -568,11 +864,27 @@ sta_ok() {
|
|||
return 0
|
||||
}
|
||||
|
||||
wait_for_nm_device_ready() {
|
||||
local attempt state=""
|
||||
for attempt in $(seq 1 20); do
|
||||
state="$(nmcli -t -f DEVICE,STATE dev | awk -F: -v d="$IFACE" '$1==d{print $2; exit}' || true)"
|
||||
case "$state" in
|
||||
disconnected|connecting|connected)
|
||||
return 0
|
||||
;;
|
||||
esac
|
||||
sleep 1
|
||||
done
|
||||
echo "ERROR: NetworkManager did not reclaim $IFACE (state=${state:-unknown})" >&2
|
||||
return 1
|
||||
}
|
||||
|
||||
/usr/local/sbin/iomatex-ap-down >/dev/null 2>&1 || true
|
||||
|
||||
nmcli dev set "$IFACE" managed yes >/dev/null 2>&1 || true
|
||||
ip addr flush dev "$IFACE" >/dev/null 2>&1 || true
|
||||
ip link set "$IFACE" up >/dev/null 2>&1 || true
|
||||
wait_for_nm_device_ready
|
||||
|
||||
existing_type="$(nmcli -g connection.type con show "$CN" 2>/dev/null || true)"
|
||||
case "$existing_type" in
|
||||
|
|
@ -595,20 +907,26 @@ else
|
|||
fi
|
||||
|
||||
nmcli con mod "$CN" connection.autoconnect yes connection.autoconnect-priority 10 ipv4.method auto ipv6.method ignore >/dev/null
|
||||
nmcli dev disconnect "$IFACE" >/dev/null 2>&1 || true
|
||||
nmcli con up id "$CN" >/dev/null 2>&1 || true
|
||||
|
||||
up_output=""
|
||||
if ! up_output="$(nmcli --wait 25 con up id "$CN" 2>&1)"; then
|
||||
echo "ERROR: failed to start Wi-Fi profile '$CN': ${up_output}" >&2
|
||||
else
|
||||
echo "INFO: Wi-Fi profile '$CN' activation requested: ${up_output}" >&2
|
||||
fi
|
||||
|
||||
sleep 10
|
||||
|
||||
if sta_ok; then
|
||||
{ echo "WIFI_PROFILE=\"$CN\""; echo "WIFI_SSID=\"$SSID_IN\""; } > /etc/iomatex/wifi.env
|
||||
ip4="$(ip -4 -o addr show dev "$IFACE" 2>/dev/null | awk '{print $4}' | head -n1 || true)"
|
||||
{ echo "WIFI_PROFILE=\"$CN\""; echo "WIFI_SSID=\"$SSID_IN\""; echo "WIFI_IP4=\"${ip4:-}\""; } > /etc/iomatex/wifi.env
|
||||
chmod 0644 /etc/iomatex/wifi.env
|
||||
echo "OK: STA connected (profile=$CN)"
|
||||
echo "OK: STA connected (profile=$CN) IP=${ip4:-n/a}"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
/usr/local/sbin/iomatex-ap-up >/dev/null 2>&1 || true
|
||||
echo "ERROR: STA not connected / no IPv4; AP restored" >&2
|
||||
echo "ERROR: STA not connected / no IPv4; AP restored (NM_STATE=$(nmcli -t -f DEVICE,STATE dev | awk -F: -v d=\"$IFACE\" '\$1==d{print \$2; exit}' || echo unknown))" >&2
|
||||
exit 10
|
||||
EOF
|
||||
|
||||
|
|
@ -650,6 +968,174 @@ if [[ "$LAST_WRITE_CHANGED" -eq 1 ]]; then
|
|||
WATCH_SERVICE_CHANGED=1
|
||||
fi
|
||||
|
||||
write_managed_file /usr/local/sbin/iomatex-ap-resetd 0755 <<'EOF'
|
||||
#!/usr/bin/env python3
|
||||
import os
|
||||
import select
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
|
||||
EVENT_PATH = "/dev/input/event8"
|
||||
RESET_HELPER = "/usr/local/sbin/iomatex-ap-reset-password"
|
||||
|
||||
EV_KEY = 0x01
|
||||
KEY_VOLUMEUP = 115
|
||||
INPUT_EVENT = struct.Struct("llHHI")
|
||||
HOLD_SECONDS = 10.0
|
||||
RETRY_DELAY_SECONDS = 1.0
|
||||
|
||||
|
||||
def log(message):
|
||||
timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
|
||||
print(f"[{timestamp} UTC] {message}", flush=True)
|
||||
|
||||
|
||||
def run_reset():
|
||||
result = subprocess.run(
|
||||
[RESET_HELPER],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
output = (result.stdout or "").strip()
|
||||
if result.returncode == 0:
|
||||
if output:
|
||||
log(f"AP password reset helper completed: {output}")
|
||||
else:
|
||||
log("AP password reset helper completed successfully")
|
||||
return True
|
||||
if output:
|
||||
log(f"ERROR: AP password reset helper failed: {output}")
|
||||
else:
|
||||
log(f"ERROR: AP password reset helper failed with rc={result.returncode}")
|
||||
return False
|
||||
|
||||
|
||||
def open_event_device():
|
||||
return os.open(EVENT_PATH, os.O_RDONLY)
|
||||
|
||||
|
||||
def main():
|
||||
pressed_since = None
|
||||
reset_triggered = False
|
||||
event_fd = None
|
||||
last_button_open_error = 0.0
|
||||
|
||||
log("iomatex-ap-resetd started")
|
||||
|
||||
while True:
|
||||
now = time.monotonic()
|
||||
|
||||
if event_fd is None:
|
||||
try:
|
||||
event_fd = open_event_device()
|
||||
log(f"button device opened: {EVENT_PATH}")
|
||||
except FileNotFoundError:
|
||||
if now - last_button_open_error >= 30.0:
|
||||
log(f"WARNING: button device not found: {EVENT_PATH}")
|
||||
last_button_open_error = now
|
||||
time.sleep(RETRY_DELAY_SECONDS)
|
||||
continue
|
||||
except Exception as exc:
|
||||
if now - last_button_open_error >= 30.0:
|
||||
log(f"WARNING: failed to open button device {EVENT_PATH}: {exc}")
|
||||
last_button_open_error = now
|
||||
time.sleep(RETRY_DELAY_SECONDS)
|
||||
continue
|
||||
|
||||
if pressed_since is not None and not reset_triggered:
|
||||
hold_seconds = now - pressed_since
|
||||
if hold_seconds >= HOLD_SECONDS:
|
||||
log(f"reset threshold reached: hold duration {hold_seconds:.1f}s")
|
||||
reset_triggered = True
|
||||
if run_reset():
|
||||
log("AP password reset to factory")
|
||||
|
||||
try:
|
||||
readable, _, _ = select.select([event_fd], [], [], 0.1)
|
||||
except OSError as exc:
|
||||
log(f"WARNING: button device select failed, reopening: {exc}")
|
||||
try:
|
||||
os.close(event_fd)
|
||||
except Exception:
|
||||
pass
|
||||
event_fd = None
|
||||
pressed_since = None
|
||||
reset_triggered = False
|
||||
continue
|
||||
|
||||
if not readable:
|
||||
continue
|
||||
|
||||
try:
|
||||
payload = os.read(event_fd, INPUT_EVENT.size)
|
||||
except OSError as exc:
|
||||
log(f"WARNING: button device read failed, reopening: {exc}")
|
||||
try:
|
||||
os.close(event_fd)
|
||||
except Exception:
|
||||
pass
|
||||
event_fd = None
|
||||
pressed_since = None
|
||||
reset_triggered = False
|
||||
continue
|
||||
|
||||
if len(payload) != INPUT_EVENT.size:
|
||||
continue
|
||||
|
||||
_, _, event_type, event_code, event_value = INPUT_EVENT.unpack(payload)
|
||||
if event_type != EV_KEY or event_code != KEY_VOLUMEUP:
|
||||
continue
|
||||
|
||||
if event_value == 1:
|
||||
if pressed_since is None:
|
||||
pressed_since = time.monotonic()
|
||||
reset_triggered = False
|
||||
log("button press detected")
|
||||
elif event_value == 0:
|
||||
hold_seconds = 0.0 if pressed_since is None else time.monotonic() - pressed_since
|
||||
log(f"button release detected: hold duration {hold_seconds:.1f}s")
|
||||
pressed_since = None
|
||||
reset_triggered = False
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
except Exception as exc:
|
||||
log(f"FATAL: {exc}")
|
||||
sys.exit(1)
|
||||
EOF
|
||||
if [[ "$LAST_WRITE_CHANGED" -eq 1 ]]; then
|
||||
RESETD_SERVICE_CHANGED=1
|
||||
fi
|
||||
|
||||
write_managed_file /etc/systemd/system/iomatex-ap-resetd.service 0644 <<'EOF'
|
||||
[Unit]
|
||||
Description=IOMATEX AP password reset daemon
|
||||
After=network.target
|
||||
Wants=network.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
ExecStart=/usr/local/sbin/iomatex-ap-resetd
|
||||
Restart=on-failure
|
||||
RestartSec=2
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
EOF
|
||||
mark_unit_change_if_needed
|
||||
if [[ "$LAST_WRITE_CHANGED" -eq 1 ]]; then
|
||||
RESETD_SERVICE_CHANGED=1
|
||||
fi
|
||||
|
||||
write_managed_file /etc/systemd/system/iomatex-ap-watch.service 0644 <<'EOF'
|
||||
[Unit]
|
||||
Description=IOMATEX AP Watch
|
||||
|
|
@ -688,8 +1174,11 @@ if [[ "$SYSTEMD_UNITS_CHANGED" -eq 1 ]]; then
|
|||
systemctl daemon-reload
|
||||
fi
|
||||
|
||||
/usr/local/sbin/iomatex-ap-sync-config
|
||||
|
||||
systemctl enable iomatex-wifi-ui.service >/dev/null 2>&1 || true
|
||||
systemctl enable iomatex-ap-watch.timer >/dev/null 2>&1 || true
|
||||
systemctl enable iomatex-ap-resetd.service >/dev/null 2>&1 || true
|
||||
|
||||
if [[ "$UI_SERVICE_CHANGED" -eq 1 ]]; then
|
||||
if systemctl is-active --quiet iomatex-wifi-ui.service; then
|
||||
|
|
@ -711,6 +1200,16 @@ else
|
|||
systemctl_start_safe iomatex-ap-watch.timer
|
||||
fi
|
||||
|
||||
if [[ "$RESETD_SERVICE_CHANGED" -eq 1 ]]; then
|
||||
if systemctl is-active --quiet iomatex-ap-resetd.service; then
|
||||
systemctl_restart_safe iomatex-ap-resetd.service
|
||||
else
|
||||
systemctl_start_safe iomatex-ap-resetd.service
|
||||
fi
|
||||
else
|
||||
systemctl_start_safe iomatex-ap-resetd.service
|
||||
fi
|
||||
|
||||
step "Initial enforce"
|
||||
/usr/local/sbin/iomatex-ap-watch || true
|
||||
|
||||
|
|
@ -720,7 +1219,8 @@ curl -m 2 -fsS "http://127.0.0.1:${UI_PORT}/api/status" >/dev/null 2>&1 || true
|
|||
echo
|
||||
echo "=== INSTALL DONE ==="
|
||||
echo "AP SSID : ${SSID}"
|
||||
echo "AP PASS : ${PASS}"
|
||||
echo "AP MODE : ${PASSWORD_MODE}"
|
||||
echo "FACTORY AP PASS : ${FACTORY_AP_PASSWORD}"
|
||||
echo "AP IP : ${AP_IP}"
|
||||
echo "UI : http://${AP_IP}:${UI_PORT} (also: http://${AP_IP} via captive HTTP)"
|
||||
echo
|
||||
|
|
@ -730,5 +1230,6 @@ echo " - Open: http://10.10.10.1 (NOT https)"
|
|||
echo
|
||||
echo "DIAG:"
|
||||
echo " /usr/local/sbin/iomatex-wifi-status"
|
||||
echo " systemctl status iomatex-wifi-ui.service iomatex-ap-watch.timer --no-pager"
|
||||
echo " journalctl -u iomatex-wifi-ui.service -u iomatex-ap-watch.service --no-pager -n 200"
|
||||
echo " /usr/local/sbin/iomatex-ap-reset-password"
|
||||
echo " systemctl status iomatex-wifi-ui.service iomatex-ap-watch.timer iomatex-ap-resetd.service --no-pager"
|
||||
echo " journalctl -u iomatex-wifi-ui.service -u iomatex-ap-watch.service -u iomatex-ap-resetd.service --no-pager -n 200"
|
||||
|
|
|
|||
Loading…
Reference in New Issue