feat(captive-portal): add Windows support (/redirect, /connecttest.txt, /ncsi.txt); restore auto-open Web UI on AP; add DHCP option 114

This commit is contained in:
Andrei Smaliak 2026-03-18 06:44:28 +04:00
parent 13619c2148
commit af34c2eb02
4 changed files with 343 additions and 84 deletions

View File

@ -0,0 +1,47 @@
# Captive Portal Entry Flow
## What changed
`stage_ui` now restores AP onboarding auto-open by handling captive-portal probe endpoints in the console HTTP service itself.
## How it works
- In AP mode, `dnsmasq` resolves all domains to the AP IP.
- The console service listens on port `80`.
- Common OS captive-check paths are redirected to `/portal`.
- `/portal` serves a minimal landing page and immediately redirects to `/`.
- The landing page keeps a visible `Open local console` link as a fallback.
## Endpoints handled
- Android: `/generate_204`, `/gen_204`, `/mobile/status.php`
- Apple CNA: `/hotspot-detect.html`, `/library/test/success.html`, `/success.html`
- Windows: `/redirect`, `/connecttest.txt`, `/ncsi.txt`, `/fwlink`
- Generic vendor probes: `/canonical.html`, `/kindle-wifi/wifiredirect.html`
All of the above redirect to `/portal` only while AP mode is active.
## Redirect logic
- Captive checks: HTTP `302` to `http://10.10.10.1/portal`
- Captive landing: HTML page with meta refresh and JavaScript redirect to `http://10.10.10.1/`
- Non-AP mode: captive-specific paths fall through to normal app routing and are not advertised by DHCP
## DHCP advertisement
`dnsmasq` also advertises DHCP option `114` with the captive URL so clients that support RFC 8910/8908 can discover it directly.
## Limitations
- Captive portal auto-popup behavior is still OS-controlled; some clients only show a banner or login notification.
- HTTPS probe URLs cannot be transparently redirected without certificate errors; the flow relies on standard HTTP captive checks plus DNS interception.
## Test checklist
- Connect Android to the Edge AP and confirm captive prompt or immediate portal window opens.
- Connect iPhone/iPad to the Edge AP and confirm Captive Network Assistant opens the landing page.
- Connect Windows to the Edge AP and confirm hotspot/login prompt opens the portal.
- Connect macOS to the Edge AP and confirm CNA/browser prompt opens.
- Open `http://10.10.10.1/` manually and confirm the normal UI still loads.
- Reboot the device in AP mode and confirm the captive flow still works.
- Reinstall `stage_ui` over an existing deployment and confirm the feature remains active.

View File

@ -1,6 +1,5 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import glob import glob
import hashlib
import importlib.util import importlib.util
import json import json
import os import os
@ -36,6 +35,37 @@ AP_DOWN_SCRIPT = "/usr/local/sbin/iomatex-ap-down"
WIFI_STATUS_SCRIPT = "/usr/local/sbin/iomatex-wifi-status" WIFI_STATUS_SCRIPT = "/usr/local/sbin/iomatex-wifi-status"
WIFI_SETUP_SCRIPT = "/usr/local/sbin/iomatex-wifi-setup" WIFI_SETUP_SCRIPT = "/usr/local/sbin/iomatex-wifi-setup"
AP_PASSWORD_RE = re.compile(r"^[a-z0-9]{8,}$") AP_PASSWORD_RE = re.compile(r"^[a-z0-9]{8,}$")
CAPTIVE_PORTAL_PATH = "/portal"
CAPTIVE_PORTAL_ALIASES = {
"/captive-portal",
}
ANDROID_CAPTIVE_PATHS = {
"/generate_204",
"/gen_204",
"/mobile/status.php",
}
APPLE_CAPTIVE_PATHS = {
"/hotspot-detect.html",
"/library/test/success.html",
"/success.txt",
"/success.html",
}
WINDOWS_CAPTIVE_PATHS = {
"/redirect",
"/connecttest.txt",
"/ncsi.txt",
"/fwlink",
}
GENERIC_CAPTIVE_PATHS = {
"/canonical.html",
"/kindle-wifi/wifiredirect.html",
}
CAPTIVE_REDIRECT_PATHS = (
ANDROID_CAPTIVE_PATHS
| APPLE_CAPTIVE_PATHS
| WINDOWS_CAPTIVE_PATHS
| GENERIC_CAPTIVE_PATHS
)
def load_config(): def load_config():
@ -155,12 +185,16 @@ def build_ap_ssid():
return f"Iomatex {hostname}" if hostname else "Iomatex" return f"Iomatex {hostname}" if hostname else "Iomatex"
def get_ap_password_suffix():
hostname = get_system_hostname().lower()
suffix = re.sub(r"[^a-z0-9]", "", hostname)[-4:]
if len(suffix) != 4:
raise RuntimeError("Failed to derive AP password suffix from hostname")
return suffix
def generate_factory_ap_password(): def generate_factory_ap_password():
serial = get_device_serial() password = f"iomatex{get_ap_password_suffix()}"
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): if not AP_PASSWORD_RE.fullmatch(password):
raise RuntimeError("Failed to generate valid factory AP password") raise RuntimeError("Failed to generate valid factory AP password")
return password return password
@ -235,6 +269,66 @@ def public_ap_status():
} }
def captive_portal_is_active():
try:
return bool(load_ap_state().get("ap_enabled"))
except Exception:
return False
def get_captive_base_url():
env = read_env_file(AP_ENV_PATH)
ap_ip = str(env.get("AP_IP", "10.10.10.1")).strip() or "10.10.10.1"
return f"http://{ap_ip}"
def build_captive_portal_html():
open_url = f"{get_captive_base_url()}/"
return f"""<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta http-equiv="refresh" content="0; url={open_url}">
<title>IOMATEX Edge Console</title>
<style>
body {{
margin: 0;
min-height: 100vh;
display: grid;
place-items: center;
padding: 24px;
background: #eef2f6;
color: #142033;
font: 16px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}}
main {{
max-width: 420px;
padding: 24px;
border-radius: 18px;
background: #ffffff;
box-shadow: 0 12px 40px rgba(20, 32, 51, 0.12);
text-align: center;
}}
a {{
color: #0b63ce;
font-weight: 600;
text-decoration: none;
}}
</style>
</head>
<body>
<main>
<h1>Open local console</h1>
<p>Redirecting to the IOMATEX Edge onboarding page.</p>
<p>If nothing opens automatically, <a href="{open_url}">open the local console</a>.</p>
</main>
<script>window.location.replace("{open_url}");</script>
</body>
</html>
"""
def ap_status_card(): def ap_status_card():
status = load_ap_state() status = load_ap_state()
installed = status["service_installed"] or file_exists(AP_ENV_PATH) installed = status["service_installed"] or file_exists(AP_ENV_PATH)
@ -826,6 +920,30 @@ class Handler(BaseHTTPRequestHandler):
self.end_headers() self.end_headers()
self.wfile.write(body) self.wfile.write(body)
def send_html(self, html, code=200, extra_headers=None):
body = html.encode("utf-8")
self.send_response(code)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Cache-Control", "no-store, no-cache, must-revalidate")
self.send_header("Pragma", "no-cache")
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.wfile.write(body)
def send_redirect(self, location, code=302, extra_headers=None):
self.send_response(code)
self.send_header("Location", location)
self.send_header("Cache-Control", "no-store, no-cache, must-revalidate")
self.send_header("Pragma", "no-cache")
self.send_header("Content-Length", "0")
if extra_headers:
for key, value in extra_headers.items():
self.send_header(key, value)
self.end_headers()
def read_json_body(self): def read_json_body(self):
size = int(self.headers.get("Content-Length", "0") or "0") size = int(self.headers.get("Content-Length", "0") or "0")
raw = self.rfile.read(size) if size > 0 else b"{}" raw = self.rfile.read(size) if size > 0 else b"{}"
@ -848,8 +966,30 @@ class Handler(BaseHTTPRequestHandler):
self.end_headers() self.end_headers()
self.wfile.write(data) self.wfile.write(data)
def handle_captive_portal_probe(self, parsed):
if not captive_portal_is_active():
return False
headers = {
"X-Captive-Portal": "IOMATEX Edge AP",
"X-Login-Page": CAPTIVE_PORTAL_PATH,
}
portal_url = f"{get_captive_base_url()}{CAPTIVE_PORTAL_PATH}"
if parsed.path == CAPTIVE_PORTAL_PATH or parsed.path in CAPTIVE_PORTAL_ALIASES:
self.send_html(build_captive_portal_html(), extra_headers=headers)
return True
if parsed.path in CAPTIVE_REDIRECT_PATHS:
self.send_redirect(portal_url, extra_headers=headers)
return True
return False
def do_GET(self): def do_GET(self):
parsed = urlparse(self.path) parsed = urlparse(self.path)
if self.handle_captive_portal_probe(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

View File

@ -27,6 +27,7 @@ APP_DIR="/opt/iomatex-console"
PUBLIC_DIR="${APP_DIR}/public" PUBLIC_DIR="${APP_DIR}/public"
BACKEND_DIR="${APP_DIR}/backend" BACKEND_DIR="${APP_DIR}/backend"
PROVIDERS_DIR="${APP_DIR}/providers.d" PROVIDERS_DIR="${APP_DIR}/providers.d"
FRONTEND_DIR="${APP_DIR}/frontend"
SERVICE_NAME="iomatex-console.service" SERVICE_NAME="iomatex-console.service"
LEGACY_SERVICE_NAME="iomatex-webipc.service" LEGACY_SERVICE_NAME="iomatex-webipc.service"
CFG_PATH="/etc/iomatex/console.json" CFG_PATH="/etc/iomatex/console.json"
@ -37,6 +38,11 @@ ts="$(date +%s)"
PREV_DIR="${APP_DIR}.prev.${ts}" PREV_DIR="${APP_DIR}.prev.${ts}"
LEGACY_APP_DIR="/opt/iomatex-process1-webipc" LEGACY_APP_DIR="/opt/iomatex-process1-webipc"
LEGACY_PREV_DIR="${LEGACY_APP_DIR}.prev.${ts}" LEGACY_PREV_DIR="${LEGACY_APP_DIR}.prev.${ts}"
STAGE_DIR="${APP_DIR}.staging.${ts}"
STAGE_PUBLIC_DIR="${STAGE_DIR}/public"
STAGE_BACKEND_DIR="${STAGE_DIR}/backend"
STAGE_PROVIDERS_DIR="${STAGE_DIR}/providers.d"
STAGE_FRONTEND_DIR="${STAGE_DIR}/frontend"
IFACE="wlan0" IFACE="wlan0"
AP_IP="10.10.10.1" AP_IP="10.10.10.1"
AP_CIDR="${AP_IP}/24" AP_CIDR="${AP_IP}/24"
@ -54,6 +60,52 @@ copy_tree() {
cp -a "${src}/." "$dst/" cp -a "${src}/." "$dst/"
} }
require_file() {
local path="$1"
[ -f "$path" ] || {
echo "ERROR: required file is missing after deploy step: $path" >&2
exit 1
}
}
rollback_deploy() {
systemctl_try stop "${SERVICE_NAME}"
rm -rf "$APP_DIR"
if [ -d "$PREV_DIR" ]; then
mv "$PREV_DIR" "$APP_DIR"
systemctl daemon-reload >/dev/null 2>&1 || true
systemctl_try start "${SERVICE_NAME}"
fi
}
wait_for_local_http() {
local attempt
for attempt in $(seq 1 15); do
if ! systemctl is-active --quiet "${SERVICE_NAME}"; then
sleep 1
continue
fi
if ! ss -ltnp 2>/dev/null | grep -q ':80 '; then
sleep 1
continue
fi
if python3 - <<'PY' >/dev/null 2>&1
import sys
import urllib.request
try:
with urllib.request.urlopen("http://127.0.0.1/api/status", timeout=2) as response:
sys.exit(0 if response.status == 200 else 1)
except Exception:
sys.exit(1)
PY
then
return 0
fi
sleep 1
done
return 1
}
systemctl_try() { systemctl_try() {
systemctl "$@" >/dev/null 2>&1 || true systemctl "$@" >/dev/null 2>&1 || true
} }
@ -101,11 +153,12 @@ get_system_hostname() {
printf '%s\n' "$host" printf '%s\n' "$host"
} }
get_device_serial() { get_ap_password_suffix() {
local serial="" local host="$1"
serial="$(grep -m1 '^Serial' /proc/cpuinfo 2>/dev/null | awk '{print $3}' | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]')" local suffix=""
[ -n "$serial" ] || { echo "ERROR: failed to read device serial from /proc/cpuinfo" >&2; exit 1; } suffix="$(printf '%s' "$host" | tr '[:upper:]' '[:lower:]' | tr -cd 'a-z0-9' | tail -c 4)"
printf '%s\n' "$serial" [ ${#suffix} -eq 4 ] || { echo "ERROR: failed to derive AP password suffix from hostname '$host'" >&2; exit 1; }
printf '%s\n' "$suffix"
} }
build_ap_ssid() { build_ap_ssid() {
@ -113,11 +166,10 @@ build_ap_ssid() {
} }
generate_factory_ap_password() { generate_factory_ap_password() {
local serial="$1" local host="$1"
local digest password local password
digest="$(printf '%s' "iomatex_the_best${serial}" | sha256sum | awk '{print $1}' | tr '[:upper:]' '[:lower:]' | tr -cd 'a-z0-9')" password="iomatex$(get_ap_password_suffix "$host")"
password="${digest:0:8}" [[ "$password" =~ ^[a-z0-9]{8,}$ ]] || { echo "ERROR: failed to generate valid factory AP password" >&2; exit 1; }
[[ "$password" =~ ^[a-z0-9]{8}$ ]] || { echo "ERROR: failed to generate valid factory AP password" >&2; exit 1; }
printf '%s\n' "$password" printf '%s\n' "$password"
} }
@ -174,19 +226,15 @@ stop_disable_reset_unit "${LEGACY_SERVICE_NAME}"
echo "[3/8] Prepare directories and preserve previous install" echo "[3/8] Prepare directories and preserve previous install"
mkdir -p /etc/iomatex mkdir -p /etc/iomatex
if [ -d "$APP_DIR" ]; then
rm -rf "$PREV_DIR"
mv "$APP_DIR" "$PREV_DIR"
fi
if [ -d "$LEGACY_APP_DIR" ]; then if [ -d "$LEGACY_APP_DIR" ]; then
rm -rf "$LEGACY_PREV_DIR" rm -rf "$LEGACY_PREV_DIR"
mv "$LEGACY_APP_DIR" "$LEGACY_PREV_DIR" mv "$LEGACY_APP_DIR" "$LEGACY_PREV_DIR"
fi fi
mkdir -p "$APP_DIR" "$PUBLIC_DIR" "$BACKEND_DIR" "$PROVIDERS_DIR" /etc/hostapd /etc/dnsmasq.d /usr/local/sbin rm -rf "$STAGE_DIR"
mkdir -p "$STAGE_DIR" "$STAGE_PUBLIC_DIR" "$STAGE_BACKEND_DIR" "$STAGE_PROVIDERS_DIR" "$STAGE_FRONTEND_DIR" /etc/hostapd /etc/dnsmasq.d /usr/local/sbin
HOSTNAME_SHORT="$(get_system_hostname)" HOSTNAME_SHORT="$(get_system_hostname)"
DEVICE_SERIAL="$(get_device_serial)" FACTORY_AP_PASSWORD="$(generate_factory_ap_password "$HOSTNAME_SHORT")"
FACTORY_AP_PASSWORD="$(generate_factory_ap_password "$DEVICE_SERIAL")"
PASSWORD_MODE="$(normalize_password_mode "$(load_env_value /etc/iomatex/ap.env PASSWORD_MODE)")" PASSWORD_MODE="$(normalize_password_mode "$(load_env_value /etc/iomatex/ap.env PASSWORD_MODE)")"
CUSTOM_PASSWORD="$(load_env_value /etc/iomatex/ap.env CUSTOM_PASSWORD)" CUSTOM_PASSWORD="$(load_env_value /etc/iomatex/ap.env CUSTOM_PASSWORD)"
if [[ "$PASSWORD_MODE" == "custom" && -z "$CUSTOM_PASSWORD" ]]; then if [[ "$PASSWORD_MODE" == "custom" && -z "$CUSTOM_PASSWORD" ]]; then
@ -246,16 +294,23 @@ server=1.1.1.1
dhcp-range=${DHCP_START},${DHCP_END},${DHCP_LEASE} dhcp-range=${DHCP_START},${DHCP_END},${DHCP_LEASE}
dhcp-option=3,${AP_IP} dhcp-option=3,${AP_IP}
dhcp-option=6,${AP_IP} dhcp-option=6,${AP_IP}
dhcp-option=114,http://${AP_IP}/captive-portal
address=/#/${AP_IP} address=/#/${AP_IP}
EOF EOF
echo "[4/8] Install console core files" echo "[4/8] Install console core files"
copy_tree "$SRC_ROOT/backend" "$BACKEND_DIR" copy_tree "$SRC_ROOT/backend" "$STAGE_BACKEND_DIR"
install -m 0644 "$SRC_ROOT/frontend/index.html" "$PUBLIC_DIR/index.html" copy_tree "$SRC_ROOT/frontend" "$STAGE_FRONTEND_DIR"
install -m 0644 "$SRC_ROOT/frontend/console.js" "$PUBLIC_DIR/console.js" install -m 0644 "$SRC_ROOT/frontend/index.html" "$STAGE_PUBLIC_DIR/index.html"
install -m 0644 "$SRC_ROOT/frontend/console.css" "$PUBLIC_DIR/console.css" install -m 0644 "$SRC_ROOT/frontend/console.js" "$STAGE_PUBLIC_DIR/console.js"
copy_tree "$SRC_ROOT/providers" "$PROVIDERS_DIR" install -m 0644 "$SRC_ROOT/frontend/console.css" "$STAGE_PUBLIC_DIR/console.css"
rm -rf "$PROVIDERS_DIR/__pycache__" "$BACKEND_DIR/__pycache__" copy_tree "$SRC_ROOT/providers" "$STAGE_PROVIDERS_DIR"
rm -rf "$STAGE_PROVIDERS_DIR/__pycache__" "$STAGE_BACKEND_DIR/__pycache__"
require_file "$STAGE_BACKEND_DIR/app.py"
require_file "$STAGE_FRONTEND_DIR/index.html"
require_file "$STAGE_FRONTEND_DIR/console.js"
require_file "$STAGE_FRONTEND_DIR/console.css"
require_file "$STAGE_PROVIDERS_DIR/00_core_services.py"
echo "[5/8] Install Wi-Fi helper scripts" echo "[5/8] Install Wi-Fi helper scripts"
cat > /usr/local/sbin/iomatex-ap-sync-config <<'EOF' cat > /usr/local/sbin/iomatex-ap-sync-config <<'EOF'
@ -279,21 +334,21 @@ get_system_hostname() {
printf '%s\n' "$host" printf '%s\n' "$host"
} }
get_device_serial() { get_ap_password_suffix() {
local serial="" local host="$1"
serial="$(grep -m1 '^Serial' /proc/cpuinfo 2>/dev/null | awk '{print $3}' | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]')" local suffix=""
[[ -n "$serial" ]] || { echo "ERROR: failed to read device serial from /proc/cpuinfo" >&2; exit 1; } suffix="$(printf '%s' "$host" | tr '[:upper:]' '[:lower:]' | tr -cd 'a-z0-9' | tail -c 4)"
printf '%s\n' "$serial" [[ ${#suffix} -eq 4 ]] || { echo "ERROR: failed to derive AP password suffix from hostname '$host'" >&2; exit 1; }
printf '%s\n' "$suffix"
} }
build_ap_ssid() { printf 'Iomatex %s\n' "$1"; } build_ap_ssid() { printf 'Iomatex %s\n' "$1"; }
generate_factory_ap_password() { generate_factory_ap_password() {
local serial="$1" local host="$1"
local digest password local password
digest="$(printf '%s' "iomatex_the_best${serial}" | sha256sum | awk '{print $1}' | tr '[:upper:]' '[:lower:]' | tr -cd 'a-z0-9')" password="iomatex$(get_ap_password_suffix "$host")"
password="${digest:0:8}" [[ "$password" =~ ^[a-z0-9]{8,}$ ]] || { echo "ERROR: failed to generate valid factory AP password" >&2; exit 1; }
[[ "$password" =~ ^[a-z0-9]{8}$ ]] || { echo "ERROR: failed to generate valid factory AP password" >&2; exit 1; }
printf '%s\n' "$password" printf '%s\n' "$password"
} }
@ -336,9 +391,8 @@ if [[ "$PASSWORD_MODE" == "custom" && -z "$CUSTOM_PASSWORD" ]]; then
fi fi
HOSTNAME_SHORT="$(get_system_hostname)" HOSTNAME_SHORT="$(get_system_hostname)"
DEVICE_SERIAL="$(get_device_serial)"
SSID="$(build_ap_ssid "$HOSTNAME_SHORT")" SSID="$(build_ap_ssid "$HOSTNAME_SHORT")"
FACTORY_PASSWORD="$(generate_factory_ap_password "$DEVICE_SERIAL")" FACTORY_PASSWORD="$(generate_factory_ap_password "$HOSTNAME_SHORT")"
ACTIVE_PASSWORD="$(get_active_ap_password "$PASSWORD_MODE" "$CUSTOM_PASSWORD" "$FACTORY_PASSWORD")" ACTIVE_PASSWORD="$(get_active_ap_password "$PASSWORD_MODE" "$CUSTOM_PASSWORD" "$FACTORY_PASSWORD")"
tmp_env="$(mktemp)" tmp_env="$(mktemp)"
@ -739,7 +793,7 @@ if [ ! -f "$SRC_LOGO" ]; then
echo "ERROR: logo source image not found: $SRC_LOGO" >&2 echo "ERROR: logo source image not found: $SRC_LOGO" >&2
exit 1 exit 1
fi fi
python3 - "$SRC_LOGO" "$PUBLIC_DIR/logo.png" "$PUBLIC_DIR/favicon.png" <<'PY' python3 - "$SRC_LOGO" "$STAGE_PUBLIC_DIR/logo.png" "$STAGE_PUBLIC_DIR/favicon.png" <<'PY'
import sys import sys
from PIL import Image from PIL import Image
@ -855,13 +909,30 @@ remove_if_exists /usr/local/sbin/iomatex-mdns-alias
remove_if_exists /etc/systemd/system/iomatex-mdns-alias.service remove_if_exists /etc/systemd/system/iomatex-mdns-alias.service
echo "[9/9] Validate and restart" echo "[9/9] Validate and restart"
python3 -m py_compile "$BACKEND_DIR/app.py" "$PROVIDERS_DIR/00_core_services.py" python3 -m py_compile "$STAGE_BACKEND_DIR/app.py" "$STAGE_PROVIDERS_DIR/00_core_services.py"
python3 -m py_compile /usr/local/sbin/iomatex-ap-resetd python3 -m py_compile /usr/local/sbin/iomatex-ap-resetd
require_file "$STAGE_PUBLIC_DIR/index.html"
require_file "$STAGE_PUBLIC_DIR/console.js"
require_file "$STAGE_PUBLIC_DIR/console.css"
if [ -d "$APP_DIR" ]; then
rm -rf "$PREV_DIR"
mv "$APP_DIR" "$PREV_DIR"
fi
mv "$STAGE_DIR" "$APP_DIR"
require_file "$BACKEND_DIR/app.py"
require_file "$FRONTEND_DIR/index.html"
require_file "$FRONTEND_DIR/console.js"
require_file "$FRONTEND_DIR/console.css"
require_file "$PROVIDERS_DIR/00_core_services.py"
systemctl daemon-reload systemctl daemon-reload
systemctl_try disable --now iomatex-mdns-alias.service systemctl_try disable --now iomatex-mdns-alias.service
systemctl enable iomatex-ap-watch.timer >/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 systemctl enable iomatex-ap-resetd.service >/dev/null 2>&1 || true
systemctl enable --now "${SERVICE_NAME}" if ! systemctl enable --now "${SERVICE_NAME}"; then
echo "ERROR: failed to start ${SERVICE_NAME}; rolling back deploy" >&2
rollback_deploy
exit 1
fi
if systemctl is-active --quiet iomatex-ap-watch.timer; then if systemctl is-active --quiet iomatex-ap-watch.timer; then
systemctl_try restart iomatex-ap-watch.timer systemctl_try restart iomatex-ap-watch.timer
else else
@ -873,6 +944,17 @@ else
systemctl_try start iomatex-ap-resetd.service systemctl_try start iomatex-ap-resetd.service
fi fi
/usr/local/sbin/iomatex-ap-watch >/dev/null 2>&1 || true /usr/local/sbin/iomatex-ap-watch >/dev/null 2>&1 || true
if ! systemctl is-active --quiet "${SERVICE_NAME}"; then
echo "ERROR: ${SERVICE_NAME} is not active after restart; rolling back deploy" >&2
rollback_deploy
exit 1
fi
if ! wait_for_local_http; then
echo "ERROR: local HTTP smoke-check failed; service did not become ready on port 80 in time; rolling back deploy" >&2
systemctl status "${SERVICE_NAME}" --no-pager -n 40 || true
rollback_deploy
exit 1
fi
echo "[10/10] Summary" echo "[10/10] Summary"
echo "Web UI: http://<EDGE-IP>" echo "Web UI: http://<EDGE-IP>"
@ -882,6 +964,7 @@ echo "Network API: curl -s http://127.0.0.1/api/network/summary | cat"
echo "Display API: curl -s http://127.0.0.1/api/display | cat" echo "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 "Providers dir: ${PROVIDERS_DIR}" echo "Providers dir: ${PROVIDERS_DIR}"
echo "Public dir: ${PUBLIC_DIR}" echo "Public dir: ${PUBLIC_DIR}"
echo "Config: ${CFG_PATH}" echo "Config: ${CFG_PATH}"

View File

@ -13,7 +13,7 @@ set -euo pipefail
# #
# Defaults: # Defaults:
# - AP SSID = Iomatex <hostname> # - AP SSID = Iomatex <hostname>
# - AP PASS = factory/custom mode (factory derived from device serial) # - AP PASS = factory/custom mode (factory derived from hostname suffix)
# - AP IP = 10.10.10.1/24 # - AP IP = 10.10.10.1/24
# - UI port = 18080 # - UI port = 18080
# ====================================== # ======================================
@ -111,14 +111,15 @@ get_system_hostname() {
printf '%s\n' "$host" printf '%s\n' "$host"
} }
get_device_serial() { get_ap_password_suffix() {
local serial="" local host="$1"
serial="$(cat /proc/cpuinfo | grep Serial | awk '{print $3}' | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]' | head -n1)" local suffix=""
if [[ -z "$serial" ]]; then suffix="$(printf '%s' "$host" | tr '[:upper:]' '[:lower:]' | tr -cd 'a-z0-9' | tail -c 4)"
log "ERROR: failed to read device serial from /proc/cpuinfo" if [[ ${#suffix} -ne 4 ]]; then
log "ERROR: failed to derive AP password suffix from hostname '${host}'"
exit 1 exit 1
fi fi
printf '%s\n' "$serial" printf '%s\n' "$suffix"
} }
build_ap_ssid() { build_ap_ssid() {
@ -127,24 +128,13 @@ build_ap_ssid() {
} }
generate_factory_ap_password() { generate_factory_ap_password() {
local serial="$1" local host="$1"
local secret="iomatex_the_best" local suffix=""
local digest=""
local password="" local password=""
suffix="$(get_ap_password_suffix "$host")"
if [[ -z "$serial" ]]; then password="iomatex${suffix}"
log "ERROR: device serial is empty; cannot generate factory AP password" if [[ ! "$password" =~ ^[a-z0-9]{8,}$ ]]; then
exit 1 log "ERROR: failed to generate valid factory AP password from hostname suffix"
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 exit 1
fi fi
printf '%s\n' "$password" printf '%s\n' "$password"
@ -254,8 +244,7 @@ apt_install_missing() {
} }
HOSTNAME_SHORT="$(get_system_hostname)" HOSTNAME_SHORT="$(get_system_hostname)"
DEVICE_SERIAL="$(get_device_serial)" FACTORY_AP_PASSWORD="$(generate_factory_ap_password "$HOSTNAME_SHORT")"
FACTORY_AP_PASSWORD="$(generate_factory_ap_password "$DEVICE_SERIAL")"
load_existing_ap_state load_existing_ap_state
PASSWORD_MODE="$(normalize_password_mode "$EXISTING_PASSWORD_MODE")" PASSWORD_MODE="$(normalize_password_mode "$EXISTING_PASSWORD_MODE")"
CUSTOM_PASSWORD="$EXISTING_CUSTOM_PASSWORD" CUSTOM_PASSWORD="$EXISTING_CUSTOM_PASSWORD"
@ -265,8 +254,8 @@ fi
SSID="$(build_ap_ssid "$HOSTNAME_SHORT")" SSID="$(build_ap_ssid "$HOSTNAME_SHORT")"
PASS="$(get_active_ap_password "$PASSWORD_MODE" "$CUSTOM_PASSWORD" "$FACTORY_AP_PASSWORD")" PASS="$(get_active_ap_password "$PASSWORD_MODE" "$CUSTOM_PASSWORD" "$FACTORY_AP_PASSWORD")"
log "Resolved hostname for AP SSID: ${HOSTNAME_SHORT}" log "Resolved hostname for AP SSID: ${HOSTNAME_SHORT}"
log "Resolved device serial from system" log "Resolved hostname for AP password suffix"
log "Factory AP password computed from device serial" log "Factory AP password computed from hostname suffix"
log "AP password mode resolved: ${PASSWORD_MODE}" log "AP password mode resolved: ${PASSWORD_MODE}"
log "Selected AP SSID: ${SSID}" log "Selected AP SSID: ${SSID}"
@ -393,6 +382,7 @@ server=1.1.1.1
dhcp-range=$DHCP_START,$DHCP_END,$DHCP_LEASE dhcp-range=$DHCP_START,$DHCP_END,$DHCP_LEASE
dhcp-option=3,$AP_IP dhcp-option=3,$AP_IP
dhcp-option=6,$AP_IP dhcp-option=6,$AP_IP
dhcp-option=114,http://$AP_IP/captive-portal
# DNS hijack (captive-like): all domains -> AP # DNS hijack (captive-like): all domains -> AP
address=/#/$AP_IP address=/#/$AP_IP
@ -613,11 +603,12 @@ get_system_hostname() {
printf '%s\n' "$host" printf '%s\n' "$host"
} }
get_device_serial() { get_ap_password_suffix() {
local serial="" local host="$1"
serial="$(cat /proc/cpuinfo | grep Serial | awk '{print $3}' | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]' | head -n1)" local suffix=""
[[ -n "$serial" ]] || { echo "ERROR: failed to read device serial from /proc/cpuinfo" >&2; exit 1; } suffix="$(printf '%s' "$host" | tr '[:upper:]' '[:lower:]' | tr -cd 'a-z0-9' | tail -c 4)"
printf '%s\n' "$serial" [[ ${#suffix} -eq 4 ]] || { echo "ERROR: failed to derive AP password suffix from hostname '$host'" >&2; exit 1; }
printf '%s\n' "$suffix"
} }
build_ap_ssid() { build_ap_ssid() {
@ -625,11 +616,10 @@ build_ap_ssid() {
} }
generate_factory_ap_password() { generate_factory_ap_password() {
local serial="$1" local host="$1"
local digest="" local password=""
digest="$(printf '%s' "iomatex_the_best${serial}" | sha256sum | awk '{print $1}' | tr '[:upper:]' '[:lower:]' | tr -cd 'a-z0-9')" password="iomatex$(get_ap_password_suffix "$host")"
local password="${digest:0:8}" [[ "$password" =~ ^[a-z0-9]{8,}$ ]] || { echo "ERROR: failed to generate valid factory AP password" >&2; exit 1; }
[[ "$password" =~ ^[a-z0-9]{8}$ ]] || { echo "ERROR: failed to generate valid factory AP password" >&2; exit 1; }
printf '%s\n' "$password" printf '%s\n' "$password"
} }
@ -674,9 +664,8 @@ if [[ "$PASSWORD_MODE" == "custom" && -z "$CUSTOM_PASSWORD" ]]; then
fi fi
HOSTNAME_SHORT="$(get_system_hostname)" HOSTNAME_SHORT="$(get_system_hostname)"
DEVICE_SERIAL="$(get_device_serial)"
SSID="$(build_ap_ssid "$HOSTNAME_SHORT")" SSID="$(build_ap_ssid "$HOSTNAME_SHORT")"
FACTORY_PASSWORD="$(generate_factory_ap_password "$DEVICE_SERIAL")" FACTORY_PASSWORD="$(generate_factory_ap_password "$HOSTNAME_SHORT")"
ACTIVE_PASSWORD="$(get_active_ap_password "$PASSWORD_MODE" "$CUSTOM_PASSWORD" "$FACTORY_PASSWORD")" ACTIVE_PASSWORD="$(get_active_ap_password "$PASSWORD_MODE" "$CUSTOM_PASSWORD" "$FACTORY_PASSWORD")"
tmp_env="$(mktemp)" tmp_env="$(mktemp)"