Compare commits

..

2 Commits

117 changed files with 1927 additions and 3066 deletions

View File

@ -635,26 +635,3 @@ journalctl -u iomatex-rt-webui.service -n 80 --no-pager
- надо переустановить только одну часть Edge; - надо переустановить только одну часть Edge;
- надо решить, можно ли ставить стадию поверх уже рабочего устройства; - надо решить, можно ли ставить стадию поверх уже рабочего устройства;
- надо подробно разобраться с `stage_reverse_tunnels`. - надо подробно разобраться с `stage_reverse_tunnels`.
## Обновление Console 3.1.42 и stage_itscreen 1.0.41
### Исправления доставки обновлений
- Distinguish Cloudflare HTTP 403 / 1010 client-signature rejection from Git credential failures; do not expose HTTP response bodies or secrets.
- Publish `stage_itscreen` 1.0.41: the Debian updater reads `latest-iomatex.json`, whose binary URL matches its strict `git.iomatex.com` allowlist. Legacy `latest.json` remains available for old-domain clients.
- Preserve checksum/size/embedded-version checks, redirect refusal, installer lock and rollback. No client binary is replaced in the public repository.
Validation: offline delivery/stage-version tests, Debian updater tests, Console stage-update API/UI contracts, and the active UAE Edge diagnostic recorded separately.
Переходный снимок оставлен в пределах 1000 Git tree entries, чтобы его мог загрузить старый bootstrap без пагинации. Новый bootstrap загружает все страницы дерева одного commit и проверяет их полноту, отсутствие повторов и неизменность commit. Не добавляйте новые файлы в этот переходный снимок без проверки доступа старого загрузчика. Старую Console, которая показывает Cloudflare 1010, сначала перезапустите: это активирует уже обновлённый HTTP User-Agent; пароль Git менять не требуется, если аутентифицированный запрос возвращает HTTP 200.
### Проверено на UAE g-box-5e8135fd — 2026-11-19
- Исходно: Console 3.1.25, stage_itscreen 1.0.27, клиент `it-screen 5.1.23`.
- Старый процесс Console был запущен 2026-10-19; новые `git_delivery.py`/`stage_versions.py` появились на диске 2026-11-19 после частичного обновления. Запросы с `Python-urllib/3.9` блокировались Cloudflare: HTTP 403, `error code: 1010`. С `IomatexOS-Updater/1.0` и теми же сохранёнными Git credentials API ветки/каталога вернул HTTP 200. Перезапуск Console активировал новый HTTP-код; проверка версий стала успешной без смены пароля.
- Первоначальная установка остановилась в `stage_itscreen` на `ValueError: Untrusted download URL`: новый allowlist домена несовместим с legacy `latest.json`. Канонический `latest-iomatex.json` доступен updater без авторизации и содержит URL того же разрешённого домена.
- Переходный commit с 1001 tree entries выявил прежнее ограничение загрузчика. Новый `repository_tree` проверен на реальном двухстраничном ответе Git: все 1001 записи уникальны. Миграционный снимок `cb8b4d0ecc0599b4b3a440ad71e7a1447ede818d` содержит 1000 записей (`truncated=false`), поэтому обновление смог получить и старый загрузчик.
- Через штатные `/api/stages/check` и `/api/stages/install` последовательно установлены Console 3.1.42 и stage_itscreen 1.0.41. Обе detached jobs завершились `success` с соответствующими receipts.
- Установлен существующий опубликованный Debian client 5.1.62 / build 5010062. SHA-256 бинарника совпал с каноническим манифестом: `5b81e7fa9359c7690630a9d3d98b4e0c6b5db7db3882e8246acb3f4de413a3a8`. Один процесс плеера; itscreen-x11, iomatex-console и iomatex-client-updater активны, NRestarts плеера = 0. Новый бинарный релиз не публиковался.
- Автотесты: offline delivery/stage versions — 67 (один platform-specific skip), Debian updater — 21, Console stage-update API — 4, assets — 3; JavaScript stage-update UI contract passed. Визуальная проверка физического экрана и управление аппаратными выходами в эту диагностику не входили.

View File

@ -0,0 +1,15 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.iomatex.console" android:versionCode="7" android:versionName="0.5.0-dev">
<uses-sdk android:minSdkVersion="26" android:targetSdkVersion="28"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application android:label="EVAx10 Console" android:icon="@drawable/icon" android:allowBackup="false" android:debuggable="true">
<activity android:name=".SetupActivity" android:exported="true"><intent-filter><action android:name="android.intent.action.MAIN"/><category android:name="android.intent.category.LAUNCHER"/></intent-filter></activity>
<service android:name=".ConsoleService" android:exported="false"/>
<receiver android:name=".BootReceiver" android:exported="true"><intent-filter><action android:name="android.intent.action.BOOT_COMPLETED"/><action android:name="android.intent.action.MY_PACKAGE_REPLACED"/></intent-filter></receiver>
</application>
</manifest>

221
android_console/README.md Normal file
View File

@ -0,0 +1,221 @@
# EVAx10 Android Console — development 0.4.1
Separate APK (`com.iomatex.console`) for the rooted RK3566 Android 13 lab device.
It preserves the EVAx10 client package and registration. The package identifier
is retained from the prototype; product UI, launcher, icon and theme are EVAx10.
## Access
- Default username/password: `iomatex` / `iomatex`, as requested. Existing stored
passwords survive upgrades. The original lab password was explicitly reset.
- Local: ADB forward `tcp:18080 tcp:18080`, browser http://127.0.0.1:18080/ on the
ADB workstation. The Android HTTP listener binds loopback only.
- Remote: device-owned outbound SSH, using the existing platform enrollment and
Web Gateway. Open **Edge Console** in the registered device's SSH/access tab.
The platform authorizes the link; Console additionally requires its own login.
ADB is not part of this remote transport.
- Sessions expire after 15 minutes; HttpOnly/SameSite cookies, login throttling,
bounded request bodies/worker queue, asset allowlist. Unsupported actions fail.
## Shared owners
`stage_ui/console_core/frontend` owns rendering, authentication UI, themes,
responsive layout and service cards. Build-time packaging reuses those exact
assets and excludes unsupported tabs. The explicit `evax10` brand modifier uses
It-screenClient SettingsTheme colors and the canonical EVAx10 launcher PNG.
Debian's existing branding remains the default. No duplicate frontend source.
`RemoteAccess` owns connection lifecycle. The root-only lab registration adapter
reads the client's canonical `no_backup/registration.ini` (RegistrationStore v1).
It never uses cached configs.json credentials or obsolete Qt settings. A change
of server/device/password closes the old connection before enrolling the new one.
Cleared registration closes the tunnel. Read errors also disconnect fail-closed.
Polling interval is 15 seconds; registration files are read-only.
Enrollment: HTTPS `/v2/device/reverse-tunnel` with the device's own credentials.
The receiver assigns the SSH host/user/port and webui port. Ed25519 keys are
created on-device, private to the agent. Only webui is forwarded to local 18080;
Cockpit/Z2M remain unavailable. No ADB or arbitrary local-port exposure.
Host keys require an administrator-provisioned `files/known_hosts`, obtained
through an already authenticated management channel. Strict verification is
mandatory; there is no ssh-keyscan auto-trust or disabled host verification.
A new environment without a trusted key reports `host_key_required`. On this
bench the eva host key was read through the existing verified dev SSH session
(the environments share the host), then installed into private agent storage.
Health separates SSH connectivity, receiver health, remote HTTP availability,
and Web Gateway health through `/v2/device/reverse-tunnel-status`. It never
marks browser access ready merely because the local service runs. Stale
healthy snapshots expire, and a disconnected SSH session immediately degrades.
The foreground service uses START_STICKY, BOOT_COMPLETED and MY_PACKAGE_REPLACED.
Stopping/force-stopping the package from Android settings suppresses normal
background behavior until it is opened again. This is not a Device Owner agent.
## Build / install
Read the client `docs/client-local-development.md`. Use the existing
`iomatex-android-dev` toolchain and lab signing certificate:
```
bash android_console/build.sh
```
Output: `~/.local/share/iomatex-dev/android-console/console-dev.apk`.
Build verifies pinned dependencies, registration parser tests and APK signature.
Use configured ADB `install -r`; never uninstall/clear EVAx10. For first install,
open **EVAx10 Console** once. Updates restart the foreground service automatically.
Provision trusted SSH public keys to `files/known_hosts` with mode 0600 through
an authenticated local/admin channel. Private device keys stay on Android.
`python3 android_console/test_bench.py` checks the installed API through Windows
SDK ADB forwarding. Override ADB and ANDROID_SERIAL for another development bench.
Credentials read via run-as are never printed. The code remains debuggable and
lab-signed: no production publication or updater manifests have been changed.
Dependency provenance and licenses: [THIRD_PARTY.md](THIRD_PARTY.md).
## Verified 2026-10-29
RK3566 / Android13, 192.168.0.186:5555, client 5.1.42 unchanged.
Registration: Android-bfa7e4de55c90543 on https://Rest.eva.iomatex.com.
Native SSH: eva.iomatex.com:2200, allocated remote webui 41998.
- Login/logout, unauthorized denial, status/health/services, rejected unsupported
mutation and asset allowlist passed on the device.
- Authenticated server -> reverse tunnel -> Android Console request succeeded
while ADB forward 18080 was removed; local forward was restored afterward.
- Android automatically restarted a killed agent process and restored its tunnel.
- APK replacement automatically restarted the agent and remote access.
- Gateway/receiver/remote web endpoint confirmed healthy; unused services false.
- Chromium login and service cards passed at 360/768/1024/1440 without horizontal
overflow or JavaScript errors. Dark EVAx10 theme and original icon inspected.
- Canonical registration/reset/legacy isolation/escaping tests pass. Shared
Console stale-session response regression passes.
Full OS reboot and live re-registration onto a different environment have not
been tested. Browser link issuance through a human platform account has not been
exercised; the existing gateway diagnostic and actual remote HTTP path were.
System terminal, live screen streaming/touch control, client start/stop and updates
are outside this iteration. Display diagnostics and registration status/transfer
reuse the g-box contracts as described below. Non-root Android needs a supported registration handoff from EVAx10;
this lab implementation must not be described as working on ordinary phones.
## Shared g-box contracts — 0.3.0-dev
AndroidPlatform adapts Android OS / DisplayManager into existing health and
Display cards. AndroidClient adapts the existing DeviceSettingsMessenger MQTT
contract, with background status snapshots and one serialized transfer action.
The shared frontend owns tabs, display layout, registration form, server selector,
confirmation, dirty/same-server disabling, error messages and responsive layout.
Capability fields are additive and preserve the Debian default behavior.
No Android frontend copy or independent registration endpoint exists.
Initial enrollment and reset remain local because that is the current Android
client policy. Register can transfer an already confirmed Android registration;
it calls the client's `register` action without first changing its settings.
Console does not write RegistrationStore, Qt settings or cached configs. The
reverse owner watches the resulting canonical registration and reconnects.
Device credentials never appear in diagnostic responses or logs.
Run `python3 android_console/tests/test_shared_contract.py` and the existing
`test_bench.py` / `tests/browser_bench.cjs`. The browser test checks both Health
and registration at 360/768/1024/1440 and excludes Linux-only controls.
### 0.3.0 bench evidence — 2026-10-29
- Android DisplayManager: built-in display 1280x800, approximately 56 Hz,
rotation 0 degrees, power On. APK/client identity and registration preserved.
- Existing MQTT settings channel confirmed registered/logged EVA identity and
client 5.1.42. Broker control prefix is `it-screen` under contract v1.
- Invalid registration target rejected before any command. Initial/reset actions
remain blocked. Form same-server/changed-server/restored-server states passed
without issuing a registration change.
- Health and registration screens passed four responsive widths without JS
errors; Linux display/audio/storage controls absent. Reverse Tunnels uses the
shared g-box card and reports browser path readiness, not just SSH state.
- Authenticated remote Console request passed with the ADB forward removed;
forward restored. Gateway, receiver and Console endpoint reported available.
- MQTT packaging regressions (resource bundles and ServiceLoader descriptor)
now have an APK-level test invoked by build.sh.
Remote server transfer is implemented through the existing client action but
has not been executed on this registered bench. Full reboot, live screen stream,
remote touch and first-time remote enrollment are not claimed as validated.
## 0.4.0 settings bench — 2026-10-29
Shared tabs now expose Health, Security & Region, Network and Registration.
Region reads Europe/Warsaw; network reports wlan0, addresses, routes and DNS.
The bench was granted ACCESS_FINE_LOCATION for Wi-Fi diagnostics; Android may
still throttle scans or require system Location to be enabled. No Wi-Fi switch,
password replacement or different timezone was performed during validation.
Browser tests cover four tabs at four widths, password validation/dirty state,
and registration unchanged/changed/restored behavior. API tests reject incorrect
current passwords, invalid zones and invalid Wi-Fi inputs.
Version checks use the same canonical Android feed as MaintainService and show
installed/public 5.1.42 as latest. The shared version controls are visible again.
APK installation through Console is not implemented: native EVAx10 owns its
updater, and this separate Console development APK has no published update feed.
Those limits are displayed on the cards, not hidden behind missing controls.
Local recovery instructions are Android-specific; the Console password is
separate from the Android lock screen and EVAx10 registration. Password change
revokes other web sessions while preserving the submitting session.
## 0.4.1 thermal adapter
Health now reads `/sys/class/thermal/thermal_zone*/{type,temp}` using the existing
Console `name`, `value_c`, `label` contract. This is the same OS source as the
client NativeSystemMetrics, with sensor names retained rather than relabeling
SoC as CPU. No frontend copy or extra root permission is needed. Vendor test and
battery zones are excluded. Read failures are unavailable, never a zero reading.
JVM fixtures validate units, names, unavailable/invalid/range values and zero.
Bench validation: authenticated health API returned soc-thermal 64.4 C and
GPU 60.6 C during the 0.4.1 check. Those are observations, not fixed values.
### Deployment boundary
Verified client compatibility: EVAx10 Android client 5.1.42 on the rooted
Android 13 RK3566 bench. A minimum compatible client release has not been
established by testing older versions. Agent manifest minimum is Android 8.0
(API 26), which is not a claim of validation on every Android 8+ firmware.
The separate com.iomatex.console APK is not bundled in the client update feed.
Updating/re-registering only the client therefore does not provision Console or
its SSH host trust on a fresh device. EVA's existing receiver/gateway can serve
the device after the agent is installed, started and provisioned with trusted
server host keys. Non-root registration handoff remains outside this prototype.
## 0.4.2-dev: CPU and reboot
The Android adapter now handles the shared `/api/actions/reboot` endpoint and
projects CPU utilization plus 1/5/15-minute load averages into health summary.
Both use the existing rooted-device command adapter. Samples refresh every five
seconds; unavailable data remains unknown. Reboot returns request acceptance,
not completion; the device and reverse tunnel must return after boot.
Verified on the Android 13 bench: full reboot through Console, changed kernel
boot ID, automatic agent start, CPU/load readings and authenticated server-to-
Console reverse access after reboot. DHCP assigned 192.168.0.100 after reboot.
This supersedes the earlier full-reboot limitation above. The client-bundled
agent installation remains separate unfinished work; 0.4.2 is a local agent build.
## Embedded client library (0.5.0-dev)
`export-client-library.sh` builds the shared adapter/frontend and exports
`evax-console.aar` plus `evax-console.json` to the development output directory.
The client imports these together and verifies the SHA-256 during Gradle build.
Source remains here; the AAR is the client's generated dependency, not a fork.
ConsoleBootstrap starts by default on Android 8+, at boot and APK replacement.
The embedded agent reads registration in its own UID without root; SSH host keys
come from the authenticated HTTPS enrollment's `ssh_host_keys` field. The server
receiver must support that additive field (or already have provisioned trust).
Root remains required for privileged OS operations and standalone lab migration.
Verified on the Android 13 bench: embedded startup, password/key migration,
full reboot, automatic reverse restoration, host trust recovery without a manual
known_hosts, and automatic startup after APK replacement. The old separate lab
package is disabled, with its data preserved. No public client release/feed was
published; this supersedes the earlier note that integration is unfinished.

View File

@ -0,0 +1,29 @@
# Android Console dependencies
Downloaded only by build.sh, pinned with SHA-256, not stored in Git.
- SSH: com.github.mwiede:jsch 2.28.0, BSD-3-Clause.
Source/license: https://github.com/mwiede/jsch/blob/master/LICENSE.txt
Artifact: https://repo.maven.apache.org/maven2/com/github/mwiede/jsch/2.28.0/jsch-2.28.0.jar
SHA-256: 916f950708937fa1e7813f1e0b6879854e456c10770033dee54fa4df1de73974
- Ed25519 support: org.bouncycastle:bcprov-jdk18on 1.83, Bouncy Castle license.
https://www.bouncycastle.org/licence.html
Artifact: https://repo.maven.apache.org/maven2/org/bouncycastle/bcprov-jdk18on/1.83/bcprov-jdk18on-1.83.jar
SHA-256: 82cf3a2af766c3bc874f6d36b9f20a8b99a8f09762dc776e8a227a45d8daaafb
- Build only: com.android.tools:r8 8.3.37, BSD-3-Clause.
https://r8.googlesource.com/r8/+/refs/heads/main/LICENSE
Artifact: https://dl.google.com/dl/android/maven2/com/android/tools/r8/8.3.37/r8-8.3.37.jar
SHA-256: 59753e70a74f918389cc87f1b7d66b5c0862932559167425708ded159e3de439
The build strips multi-release Java variants before D8; Android uses the Java 8
implementation plus BC Ed25519 support. Upstream jar license resources remain
in the dependency jars; APK assets must also include their notices.
## Android client settings transport — 0.3.0-dev
Eclipse Paho Java MQTT client 1.2.5, Eclipse Public License 2.0 / Eclipse
Distribution License 1.0. Source: https://github.com/eclipse-paho/paho.mqtt.java.
Artifact: `org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.5` from Maven Central.
SHA-256: `59914287adac506a28d5e8172eed262a22605f3df4d426b9d92f41dae2448185`.
Used only to adapt the existing DeviceSettingsMessenger settings topics; no
second registration workflow or MQTT protocol implementation is introduced.

82
android_console/build.sh Normal file
View File

@ -0,0 +1,82 @@
#!/bin/bash
set -euo pipefail
root=$(cd "$(dirname "$0")/.." && pwd)
build=${IOMATEX_ANDROID_CONSOLE_BUILD:-$HOME/.local/share/iomatex-dev/android-console}
mkdir -p "$build/assets" "$build/classes" "$build/dex" "$build/res/drawable"
exec 9>"$build/.build.lock"
flock -n 9 || { echo "Android Console build is already running" >&2; exit 1; }
# Recreate generated classes in the isolated container for reproducible rebuilds.
cp "$root"/stage_ui/console_core/frontend/{index.html,console.js,console.css,console.i18n.js} "$build/assets/"
cp "$root/stage_env/desktop/evax10_launcher.png" "$build/assets/logo.png"
cp "$build/assets/logo.png" "$build/assets/favicon.png"
cp "$build/assets/logo.png" "$build/res/drawable/icon.png"
cp "$build/assets/logo.png" "$build/assets/g-box.png"
# The prototype exposes only supported navigation; shared rendering and styles stay unchanged.
python3 - "$build/assets/index.html" <<'PY'
from pathlib import Path
import re,sys
p=Path(sys.argv[1]);s=p.read_text()
s=re.sub(r'<button\b[^>]*data-tab="(?!(?:health|tscreen|security|network)")[^"]+"[^>]*>.*?</button>','',s)
s=s.replace('<html lang="en">','<html lang="en" data-console-brand="evax10" data-theme="dark">').replace('IOMATEX Console','EVAx10 Console').replace('IOMATEX G-Box','EVAx10 Android').replace('Edge Automation Gateway','EVAx10 Console').replace('Digital DNA ready','Android')
p.write_text(s)
PY
if [[ ! -f "$build/paho.jar" ]]; then
curl --fail --location --show-error --max-time 60 https://repo.maven.apache.org/maven2/org/eclipse/paho/org.eclipse.paho.client.mqttv3/1.2.5/org.eclipse.paho.client.mqttv3-1.2.5.jar -o "$build/paho.jar"
fi
printf '%s %s\n' 59914287adac506a28d5e8172eed262a22605f3df4d426b9d92f41dae2448185 "$build/paho.jar" | sha256sum -c -
if [[ ! -f "$build/jsch.jar" ]]; then
curl --fail --location --show-error --max-time 60 https://repo.maven.apache.org/maven2/com/github/mwiede/jsch/2.28.0/jsch-2.28.0.jar -o "$build/jsch.jar"
fi
printf '%s %s\n' 916f950708937fa1e7813f1e0b6879854e456c10770033dee54fa4df1de73974 "$build/jsch.jar" | sha256sum -c -
if [[ ! -f "$build/bcprov.jar" ]]; then
curl --fail --location --show-error --max-time 60 https://repo.maven.apache.org/maven2/org/bouncycastle/bcprov-jdk18on/1.83/bcprov-jdk18on-1.83.jar -o "$build/bcprov.jar"
fi
printf '%s %s\n' 82cf3a2af766c3bc874f6d36b9f20a8b99a8f09762dc776e8a227a45d8daaafb "$build/bcprov.jar" | sha256sum -c -
# D8 targets Java 8 entries; newer JVM variants are not Android implementations.
python3 - "$build" <<'PY2'
import sys,zipfile,pathlib
p=pathlib.Path(sys.argv[1])
(p/'assets'/'licenses').mkdir(exist_ok=True)
for name in ['jsch','bcprov','paho']:
with zipfile.ZipFile(p/(name+'.jar')) as source, zipfile.ZipFile(p/(name+'-android.jar'),'w') as target:
for info in source.infolist():
if name == 'paho' and not info.is_dir() and ((info.filename.startswith('org/') and info.filename.endswith('.properties')) or info.filename.startswith('META-INF/services/')):
source.extract(info, p)
if 'LICENSE' in info.filename.upper() and not info.is_dir():
(p/'assets'/'licenses'/(name+'-'+pathlib.Path(info.filename).name)).write_bytes(source.read(info.filename))
if not info.filename.startswith('META-INF/versions/') and not info.filename.endswith('module-info.class'):
target.writestr(info,source.read(info.filename))
PY2
if [[ ! -f "$build/r8.jar" ]]; then
curl --fail --location --show-error --max-time 60 https://dl.google.com/dl/android/maven2/com/android/tools/r8/8.3.37/r8-8.3.37.jar -o "$build/r8.jar"
fi
printf '%s %s\n' 59753e70a74f918389cc87f1b7d66b5c0862932559167425708ded159e3de439 "$build/r8.jar" | sha256sum -c -
cp -r "$root/android_console/src" "$build/"
cp -r "$root/android_console/tests" "$build/"
cp "$root/android_console/AndroidManifest.xml" "$build/"
docker exec iomatex-android-dev mkdir -p /tmp/iomatex-console-build
docker cp "$build/." iomatex-android-dev:/tmp/iomatex-console-build/
docker exec iomatex-android-dev bash -c '
set -euo pipefail
cd /tmp/iomatex-console-build
rm -rf classes dex
mkdir -p classes dex
sdk=/build/sdk; bt=$sdk/build-tools/29.0.3; api=$sdk/platforms/android-30/android.jar
javac -source 8 -target 8 -classpath "$api:jsch-android.jar:paho-android.jar" -d classes src/com/iomatex/console/*.java
mkdir -p test-classes
javac -classpath classes -d test-classes tests/ClientRegistrationTest.java tests/ThermalSensorsTest.java tests/CpuSampleTest.java
java -cp classes:test-classes com.iomatex.console.ClientRegistrationTest
java -cp classes:test-classes com.iomatex.console.ThermalSensorsTest
java -cp classes:test-classes com.iomatex.console.CpuSampleTest
java -cp r8.jar com.android.tools.r8.D8 --lib "$api" --min-api 26 --output dex jsch-android.jar bcprov-android.jar paho-android.jar classes/com/iomatex/console/*.class
"$bt/aapt" package -f -M AndroidManifest.xml -I "$api" -S res -A assets -F unsigned.apk
cp dex/classes.dex .
"$bt/aapt" add unsigned.apk classes.dex
while IFS= read -r resource; do "$bt/aapt" add unsigned.apk "$resource"; done < <(find org META-INF/services -type f)
"$bt/zipalign" -f 4 unsigned.apk aligned.apk
"$bt/apksigner" sign --ks /root/.android/debug.keystore --ks-pass pass:android --out console-dev.apk aligned.apk
"$bt/apksigner" verify console-dev.apk
'
docker cp iomatex-android-dev:/tmp/iomatex-console-build/console-dev.apk "$build/console-dev.apk"
python3 "$root/android_console/tests/test_apk.py" "$build/console-dev.apk"
printf 'Development APK: %s\n' "$build/console-dev.apk"

View File

@ -0,0 +1,22 @@
#!/bin/bash
# Generate the client library from the sole Console source owner.
set -euo pipefail
root=$(cd "$(dirname "$0")/.." && pwd)
bash "$root/android_console/build.sh"
build=${IOMATEX_ANDROID_CONSOLE_BUILD:-$HOME/.local/share/iomatex-dev/android-console}
docker exec iomatex-android-dev bash -c 'cd /tmp/iomatex-console-build/classes && jar cf ../console-classes.jar .'
docker cp iomatex-android-dev:/tmp/iomatex-console-build/console-classes.jar "$build/console-classes.jar"
python3 - "$build" "$root" <<'PY'
import pathlib,sys,zipfile,hashlib,json,subprocess
b,root=map(pathlib.Path,sys.argv[1:]);target=b/'evax-console.aar'
manifest='''<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.iomatex.console.library"><uses-sdk android:minSdkVersion="23"/><uses-permission android:name="android.permission.INTERNET"/><uses-permission android:name="android.permission.FOREGROUND_SERVICE"/><uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/><uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/><uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/><application><service android:name="com.iomatex.console.ConsoleService" android:process=":console" android:exported="false"/><receiver android:name="com.iomatex.console.BootReceiver" android:process=":console" android:exported="false"><intent-filter><action android:name="android.intent.action.BOOT_COMPLETED"/><action android:name="android.intent.action.MY_PACKAGE_REPLACED"/></intent-filter></receiver></application></manifest>'''
with zipfile.ZipFile(target,'w',zipfile.ZIP_DEFLATED) as out:
out.writestr('AndroidManifest.xml',manifest);out.write(b/'console-classes.jar','classes.jar');out.writestr('R.txt','')
for name in ['jsch','paho','bcprov']:out.write(b/(name+'-android.jar'),'libs/'+name+'.jar')
for path in sorted((b/'assets').rglob('*')):
if path.is_file():out.write(path,'assets/evaxconsole/'+str(path.relative_to(b/'assets')))
source={str(p.relative_to(root)):hashlib.sha256(p.read_bytes()).hexdigest() for folder in ['android_console','stage_ui/console_core/frontend'] for p in sorted((root/folder).rglob('*')) if p.is_file() and '__pycache__' not in str(p)}
metadata={'version':'0.5.0-dev','owner':'Iomatex_OS/android_console','base_commit':subprocess.check_output(['git','-C',str(root),'rev-parse','HEAD'],text=True).strip(),'sha256':hashlib.sha256(target.read_bytes()).hexdigest(),'sources':source}
(b/'evax-console.json').write_text(json.dumps(metadata,indent=2)+'\n')
print(target)
PY

View File

@ -0,0 +1,177 @@
package com.iomatex.console;
import android.content.Context;
import org.json.*;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import java.net.URI;
import java.util.*;
import java.util.concurrent.*;
import static com.iomatex.console.ConsoleService.obj;
/** Transport adapter for g-box's DeviceSettingsMessenger contract, not a registration implementation. */
final class AndroidClient implements AutoCloseable {
static final String PACKAGE = "com.magicby.broadcaster.client";
private final Context context;
private final ScheduledExecutorService sampler = Executors.newSingleThreadScheduledExecutor();
private volatile JSONObject registration = new JSONObject();
private volatile JSONObject lastEvent = new JSONObject();
private volatile long sampledAt;
private ClientRegistration sampledIdentity;
private volatile String problem = "Loading client registration";
private volatile boolean closed;
private final java.util.concurrent.locks.ReentrantLock operation = new java.util.concurrent.locks.ReentrantLock();
private final java.util.concurrent.atomic.AtomicBoolean transferInProgress = new java.util.concurrent.atomic.AtomicBoolean();
AndroidClient(Context context) { this.context = context; }
void start() { sampler.scheduleWithFixedDelay(() -> { if(operation.tryLock())try{sample();}finally{operation.unlock();} },0,15,TimeUnit.SECONDS); }
String version() { try { return context.getPackageManager().getPackageInfo(PACKAGE,0).versionName; } catch(Exception e) { return ""; } }
ClientRegistration stored() throws Exception { return new ClientRegistration(RemoteAccess.readClient(context,"no_backup/registration.ini")); }
private void sample() {
try {
ClientRegistration local = stored();
JSONObject next = obj("server", local.server, "host", local.server, "username", local.user,
"device_id", local.user, "device_name", local.user, "local_registered", local.registered,
"registered", false, "logged", false, "password_state", local.password.isEmpty()?"Not specified":"Password set",
"password_present", !local.password.isEmpty(), "app_version", version(), "last_event", lastEvent,
"status", local.registered?"incomplete":"not_registered", "capabilities", obj("can_register", false,"can_reset",false),
"capability_reason", "Initial Android registration is performed in EVAx10 on the device.");
if(sampledIdentity == null || !same(sampledIdentity,local)) registration = new JSONObject(next.toString());
sampledIdentity = local;
if(local.registered)try(Channel channel = new Channel(local)) {
JSONObject live = channel.request(obj("action","get","category","server"), "", "server", 5);
// Never merge a delayed reply belonging to an old registration.
ClientRegistration current = stored();
if(!same(local,current) || !local.user.equals(live.optString("username")) || !sameServer(local.server,live.optString("host")))
throw new Exception("Registration changed during diagnostics");
boolean verified = live.optBoolean("registered") && live.optBoolean("logged");
next.put("registered",verified).put("logged",live.optBoolean("logged")).put("status",verified?"ready":"incomplete")
.put("organization",live.optString("organization")).put("token",live.optString("token"))
.put("contract",channel.controlPrefix).put("mqtt_prefix",channel.mqttPrefix).put("contract_version",channel.contractVersion)
.put("request_topic",channel.requestTopic).put("response_topic",channel.responseTopic)
.put("device_name",live.optString("device_name",local.user)).put("app_version",live.optString("app_version",version()))
.put("capabilities",obj("can_register",verified,"can_reset",false))
.put("capability_reason","Android supports transfer of an enrolled device. Initial registration and reset are performed in EVAx10 locally.");
registration=next; problem="";
} else problem="";
} catch(Exception e) {
android.util.Log.w("EvaxClient", e.getClass().getSimpleName()+" "+java.util.Arrays.toString(e.getStackTrace()));
problem=connectionProblem(e);
}
sampledAt=System.currentTimeMillis();
}
private static String connectionProblem(Exception error) {
if(error instanceof TimeoutException)
return "EVAx10 Client did not answer on its MQTT settings channel. Its saved registration and active MQTT identity may differ; complete registration in EVAx10 Settings > Connection, then refresh status.";
String message=error.getMessage()==null?"":error.getMessage();
if(message.contains("Cached broker configuration does not match current registration"))
return "EVAx10 Client registration does not match its active MQTT identity. Complete registration in EVAx10 Settings > Connection, then refresh status.";
return "EVAx10 Client settings channel is unavailable. Start the client and refresh status.";
}
JSONObject registration() throws Exception {
JSONObject result = new JSONObject(registration.toString());
if(!problem.isEmpty() || System.currentTimeMillis()-sampledAt>60000) {
result.put("registered",false).put("logged",false).put("status","error")
.put("warning",problem.isEmpty()?"Client diagnostics expired":problem)
.put("capabilities",obj("can_register",false,"can_reset",false))
.put("capability_reason",problem.isEmpty()?"Refresh client diagnostics before registration.":problem);
}
result.put("ok",true); return result;
}
JSONObject service() throws Exception {
boolean installed=!version().isEmpty();
// A live settings response proves the application is running; a package or maintenance service does not.
boolean verified=sampledAt>0 && System.currentTimeMillis()-sampledAt<=60000 && problem.isEmpty() && registration.optBoolean("logged");
return obj("id","itscreen","title","EVAx10","unit",PACKAGE,"installed",installed,
"configured",registration.optBoolean("local_registered"),"active",verified?Boolean.TRUE:JSONObject.NULL,
"state",verified?"active":"unknown","status",verified?"running":"unknown",
"status_text",verified?"Active":"Runtime state not verified","version",version(),
"capabilities",obj("can_start",false,"can_stop",false,"logs",false),"details",new JSONArray());
}
JSONObject status() throws Exception { return obj("ok",true,"service",service(),"registration",registration()); }
JSONObject runtime() throws Exception { return obj("ok",true,"current_time",AndroidPlatform.timestamp(System.currentTimeMillis()),"service_state",service().optString("state")); }
JSONObject transfer(JSONObject input) throws Exception {
if(!transferInProgress.compareAndSet(false,true))throw new IllegalStateException("Registration transfer already in progress");
boolean locked=false;
try {
// A periodic status sample uses the same MQTT channel. Wait for that
// short read to finish instead of reporting a false transfer conflict.
operation.lockInterruptibly();locked=true;
String target=input.optString("host","").trim(); if(!target.contains("://"))target="https://"+target;
URI uri=new URI(target);
if(!"https".equalsIgnoreCase(uri.getScheme()) || uri.getHost()==null || uri.getUserInfo()!=null || uri.getQuery()!=null || uri.getFragment()!=null || !(uri.getPath().isEmpty()||"/".equals(uri.getPath())))
throw new IllegalArgumentException("A valid HTTPS registration server is required");
ClientRegistration local=stored();
if(!local.logged || !local.registered)throw new IllegalStateException("Initial registration must be performed in EVAx10 on the device");
if(sameServer(target,local.server))throw new IllegalArgumentException("Device is already registered on the selected server");
try(Channel channel=new Channel(local)) {
JSONObject live=channel.request(obj("action","get","category","server"),"","server",5);
if(!same(local,stored()) || !local.user.equals(live.optString("username")) || !sameServer(local.server,live.optString("host")) || !live.optBoolean("logged"))
throw new IllegalStateException("Client registration is not ready for transfer");
// No 'set server', file write, or manual re-registration: client owns confirmation and rollback.
JSONObject accepted=channel.request(obj("action","register","host",target,"token",input.optString("token")),"register","",5);
if(!accepted.optBoolean("result"))throw new IllegalStateException("Client rejected registration transfer");
long deadline=System.currentTimeMillis()+45000;
while(!closed && System.currentTimeMillis()<deadline) {
ClientRegistration current=stored();
if(current.logged && current.registered && local.user.equals(current.user) && sameServer(target,current.server)) {
lastEvent=obj("action","registered","operation","confirm","status","200","timestamp",AndroidPlatform.timestamp(System.currentTimeMillis()));
sample();
return obj("ok",true,"message","Cloud registration changed. Reopen Console from the new server.","data",registration());
}
Thread.sleep(500);
}
throw new IllegalStateException("Registration transfer was not confirmed; check the client. The old registration is not overwritten by Console.");
}
} finally { if(locked)operation.unlock();transferInProgress.set(false); }
}
static boolean sameServer(String a,String b) { return a.replaceAll("/+$","").equalsIgnoreCase(b.replaceAll("/+$","")); }
static boolean same(ClientRegistration a,ClientRegistration b) { return a.registered==b.registered && a.user.equals(b.user) && a.server.equals(b.server) && a.password.equals(b.password); }
public void close() { closed=true; sampler.shutdownNow(); }
/** Existing MQTT settings wire contract: login -> get server / register. */
final class Channel implements AutoCloseable {
final MqttClient mqtt;
final BlockingQueue<JSONObject> replies=new ArrayBlockingQueue<>(32);
final String requestTopic, responseTopic, controlPrefix, mqttPrefix;
final int contractVersion;
Channel(ClientRegistration local) throws Exception {
JSONObject config=new JSONObject(RemoteAccess.readClient(context,"files/configs.json"));
// Cached broker config may only be used for the exact current canonical identity.
if(!local.registered || !local.user.equals(config.optString("username")) || !local.password.equals(config.optString("password")))
throw new IllegalStateException("Cached broker configuration does not match current registration");
JSONObject broker=config.getJSONObject("mqtt");
String prefix=broker.getString("prefix").replaceAll("^/+|/+$","");
mqttPrefix=prefix;contractVersion=broker.optInt("contract_version",1);
if(contractVersion<2)prefix=prefix.split("/")[0];
controlPrefix=prefix;
if(prefix.isEmpty() || prefix.contains("#") || prefix.contains("+"))throw new IllegalArgumentException("Invalid MQTT prefix");
String base=prefix+"/$devices/settings/"+local.user;
requestTopic=base+"/sub";responseTopic=base+"/pub";
String host=broker.getString("host_name"); int port=broker.getInt("port");
if(!host.matches("[A-Za-z0-9.-]+") || port<1 || port>65535)throw new IllegalArgumentException("Invalid broker address");
boolean tls=broker.optBoolean("ssl") || broker.optInt("ssl",0)==1;
mqtt=new MqttClient((tls?"ssl":"tcp")+"://"+host+":"+port,"console-"+UUID.randomUUID(),new MemoryPersistence());
try {
MqttConnectOptions options=new MqttConnectOptions();options.setCleanSession(true);options.setConnectionTimeout(5);options.setKeepAliveInterval(15);
options.setUserName(broker.getString("username"));options.setPassword(broker.getString("password").toCharArray());
options.setHttpsHostnameVerificationEnabled(true);
mqtt.setTimeToWait(5000);
mqtt.setCallback(new MqttCallback(){
public void connectionLost(Throwable cause){}
public void deliveryComplete(IMqttDeliveryToken token){}
public void messageArrived(String topic,MqttMessage message){if(!message.isRetained() && message.getPayload().length<131072)try{replies.offer(new JSONObject(new String(message.getPayload(),java.nio.charset.StandardCharsets.UTF_8)));}catch(Exception ignored){}}
});
mqtt.connect(options);mqtt.subscribe(base+"/pub",0);
JSONObject login=request(obj("action","login","password","eXXI0wkHBmNBnVbE"),"login","",5);
if(!login.optBoolean("result"))throw new IllegalStateException("Settings login rejected");
}catch(Exception e){close();throw e;}
}
JSONObject request(JSONObject payload,String action,String category,int seconds)throws Exception {
replies.clear();mqtt.publish(requestTopic,payload.toString().getBytes(java.nio.charset.StandardCharsets.UTF_8),0,false);
long end=System.currentTimeMillis()+seconds*1000;
while(System.currentTimeMillis()<end){JSONObject reply=replies.poll(200,TimeUnit.MILLISECONDS);if(reply!=null && (action.isEmpty()||action.equals(reply.optString("action"))) && (category.isEmpty()||category.equals(reply.optString("category"))))return reply;}
throw new TimeoutException("Client settings response timed out");
}
public void close(){try{if(mqtt.isConnected())mqtt.disconnectForcibly(100,100);}catch(Exception ignored){}try{mqtt.close();}catch(Exception ignored){}}
}
}

View File

@ -0,0 +1,103 @@
package com.iomatex.console;
import android.app.ActivityManager;
import android.content.Context;
import android.hardware.display.DisplayManager;
import android.os.*;
import android.view.Display;
import org.json.*;
import java.util.*;
import static com.iomatex.console.ConsoleService.obj;
/** Android sources projected into the existing Console health/display contracts. */
final class AndroidPlatform {
final Context context;
private final java.util.concurrent.ScheduledExecutorService sampler=java.util.concurrent.Executors.newSingleThreadScheduledExecutor();
private CpuSample previous;
private volatile JSONObject cpu=new JSONObject();
private volatile long sampledAt;
AndroidPlatform(Context context) {
this.context = context;
sampler.scheduleWithFixedDelay(()->{
try {
String[] lines=AndroidSettings.command("su","0","sh","-c","head -1 /proc/stat; cat /proc/loadavg").split("\\n");
CpuSample next=new CpuSample(lines[0]);
String[] loads=lines[1].trim().split("\\s+");JSONArray average=new JSONArray();
for(int i=0;i<3;i++){double value=Double.parseDouble(loads[i]);if(!Double.isFinite(value)||value<0)throw new IllegalArgumentException();average.put(value);}
Double usage=next.usage(previous);previous=next;
cpu=obj("cpu_usage_percent",usage==null?JSONObject.NULL:usage,"load_average",average);
sampledAt=SystemClock.elapsedRealtime();
}catch(Exception e){previous=null;cpu=new JSONObject();sampledAt=0;}
},0,5,java.util.concurrent.TimeUnit.SECONDS);
}
void close(){sampler.shutdownNow();}
static String timestamp(long millis) { return new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX", Locale.ROOT).format(new Date(millis)); }
static JSONObject row(String label, Object value) throws JSONException { return obj("label", label, "value", value); }
JSONObject health(JSONObject identity) throws Exception {
StatFs disk = new StatFs(context.getFilesDir().getPath());
ActivityManager.MemoryInfo memory = new ActivityManager.MemoryInfo();
context.getSystemService(ActivityManager.class).getMemoryInfo(memory);
long uptime = SystemClock.elapsedRealtime();
return obj("ok", true, "identity", identity, "generated_at", timestamp(System.currentTimeMillis()),
"last_boot_at", System.currentTimeMillis()-uptime, "uptime_human", uptime/60000+" min",
"cpu_usage_supported", sampledAt>0, "cpu_count", Runtime.getRuntime().availableProcessors(),
"cpu_usage_percent", SystemClock.elapsedRealtime()-sampledAt<15000?cpu.opt("cpu_usage_percent"):JSONObject.NULL,
"load_average", SystemClock.elapsedRealtime()-sampledAt<15000?cpu.opt("load_average"):JSONObject.NULL,
"disk", obj("used_percent", Math.round(1000.0*(disk.getTotalBytes()-disk.getAvailableBytes())/disk.getTotalBytes())/10.0,
"total_bytes", disk.getTotalBytes(), "available_bytes", disk.getAvailableBytes()),
"memory", obj("total_bytes", memory.totalMem, "available_bytes", memory.availMem, "low_memory", memory.lowMemory),
"storage", obj("supported",false), "temperatures", temperatures());
}
JSONArray temperatures() throws Exception {
JSONArray rows=new JSONArray();
for(ThermalSensors.Reading reading:ThermalSensors.read(new java.io.File("/sys/class/thermal"))) {
rows.put(obj("name",reading.name,"value_c",reading.celsius==null?JSONObject.NULL:reading.celsius,
"label",reading.celsius==null?"Not available":String.format(Locale.ROOT,"%.1f C",reading.celsius)));
}
return rows;
}
JSONObject osCard() throws Exception {
ActivityManager.MemoryInfo memory = new ActivityManager.MemoryInfo();
context.getSystemService(ActivityManager.class).getMemoryInfo(memory);
StatFs disk = new StatFs(context.getFilesDir().getPath());
JSONArray details = new JSONArray()
.put(row("OS", "Android "+Build.VERSION.RELEASE)).put(row("SDK", Build.VERSION.SDK_INT))
.put(row("Security patch", Build.VERSION.SECURITY_PATCH)).put(row("Manufacturer", Build.MANUFACTURER))
.put(row("Model", Build.MODEL)).put(row("Board", Build.BOARD)).put(row("Hardware", Build.HARDWARE))
.put(row("Architecture", String.join(", ", Build.SUPPORTED_ABIS))).put(row("Build", Build.DISPLAY))
.put(row("Build fingerprint", Build.FINGERPRINT)).put(row("Kernel", System.getProperty("os.version")))
.put(row("CPU cores", Runtime.getRuntime().availableProcessors())).put(row("Total memory", mib(memory.totalMem)))
.put(row("Available memory", mib(memory.availMem))).put(row("Data partition size", mib(disk.getTotalBytes())))
.put(row("Data partition available", mib(disk.getAvailableBytes())))
.put(row("Time zone", TimeZone.getDefault().getID())).put(row("Current time (Edge)", timestamp(System.currentTimeMillis())));
return obj("id", "environment", "title", "Android OS", "installed", true, "configured", true,
"active", true, "state", "active", "status_text", "Available", "details", details);
}
static String mib(long value) { return (value/1048576)+" MiB"; }
JSONObject display() throws Exception {
JSONArray connectors = new JSONArray(); JSONArray details = new JSONArray();
Display[] displays = context.getSystemService(DisplayManager.class).getDisplays();
Display primary = null;
for (Display display : displays) {
if(primary == null || display.getDisplayId() == Display.DEFAULT_DISPLAY) primary = display;
Display.Mode mode = display.getMode();
JSONArray modes = new JSONArray();
for(Display.Mode available : display.getSupportedModes()) modes.put(available.getPhysicalWidth()+"x"+available.getPhysicalHeight()+" @ "+available.getRefreshRate()+" Hz");
connectors.put(obj("connector", "Display "+display.getDisplayId(), "interface", "Android DisplayManager",
"connected", true, "status", display.getState()==Display.STATE_ON?"Active":"Connected",
"monitor_name", display.getName(), "current_resolution", mode.getPhysicalWidth()+"x"+mode.getPhysicalHeight(),
"refresh_rate", String.format(Locale.ROOT,"%.2f Hz",mode.getRefreshRate()), "modes", modes));
}
if(primary != null) {
Display.Mode mode = primary.getMode();
details.put(row("Monitor", primary.getName())).put(row("Current resolution", mode.getPhysicalWidth()+"x"+mode.getPhysicalHeight()))
.put(row("Refresh", String.format(Locale.ROOT,"%.2f Hz",mode.getRefreshRate()))).put(row("Rotation", primary.getRotation()*90+"°"))
.put(row("Power state", primary.getState()==Display.STATE_ON?"On":primary.getState()==Display.STATE_OFF?"Off":"Unknown"));
}
return obj("id", "display", "title", "Display", "installed", true, "configured", true, "active", primary!=null,
"state", primary!=null?"active":"unknown", "status_text", primary!=null?"Connected":"No displays detected",
"details", details, "connectors", connectors,
"display_status", obj("connected", primary!=null, "connector", primary==null?"":"Display "+primary.getDisplayId()),
"capabilities", obj("desktop_mode", false, "pulse_audio", false));
}
}

View File

@ -0,0 +1,62 @@
package com.iomatex.console;
import android.content.*;
import android.net.*;
import android.net.wifi.*;
import org.json.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
import static com.iomatex.console.ConsoleService.obj;
/** Native OS adapters for the shared Console region and network endpoints. */
final class AndroidSettings {
final Context context;
AndroidSettings(Context context){this.context=context;}
JSONObject timezone()throws Exception{
String zone=command("getprop","persist.sys.timezone");
if(!Arrays.asList(TimeZone.getAvailableIDs()).contains(zone))zone=TimeZone.getDefault().getID();
java.text.SimpleDateFormat local=new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.ROOT);local.setTimeZone(TimeZone.getTimeZone(zone));
java.text.SimpleDateFormat offset=new java.text.SimpleDateFormat("XXX",Locale.ROOT);offset.setTimeZone(TimeZone.getTimeZone(zone));
return obj("ok",true,"timezone",zone,"available_timezones",new JSONArray(Arrays.asList(TimeZone.getAvailableIDs())),"local_time",local.format(new Date()),"utc_offset",offset.format(new Date()));
}
static String command(String...args)throws Exception{
Process p=new ProcessBuilder(args).redirectErrorStream(true).start();
java.io.ByteArrayOutputStream out=new java.io.ByteArrayOutputStream();
Thread reader=new Thread(()->{try(java.io.InputStream in=p.getInputStream()){byte[] b=new byte[4096];int n;while((n=in.read(b))!=-1){if(out.size()+n>65536){p.destroy();break;}out.write(b,0,n);}}catch(Exception ignored){}});reader.start();
if(!p.waitFor(8,TimeUnit.SECONDS)){p.destroyForcibly();throw new IllegalStateException("Android operation timed out");}reader.join(1000);
if(p.exitValue()!=0)throw new IllegalStateException("Android rejected the operation");return out.toString("UTF-8").trim();
}
JSONObject setTimezone(JSONObject input)throws Exception{
String zone=input.optString("timezone");if(!Arrays.asList(TimeZone.getAvailableIDs()).contains(zone))throw new IllegalArgumentException("Select a valid time zone");
command("su","0","cmd","alarm","set-timezone",zone);
JSONObject result=timezone();if(!zone.equals(result.optString("timezone")))throw new IllegalStateException("Time zone change was not confirmed");
return result.put("message","System time zone changed successfully");
}
JSONObject network()throws Exception{
ConnectivityManager manager=context.getSystemService(ConnectivityManager.class);JSONObject interfaces=new JSONObject();String active="";
for(Network network:manager.getAllNetworks()){
NetworkCapabilities cap=manager.getNetworkCapabilities(network);LinkProperties link=manager.getLinkProperties(network);if(cap==null||link==null)continue;
String kind=cap.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)?"wifi":cap.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)?"ethernet":"";if(kind.isEmpty())continue;
JSONArray v4=new JSONArray(),v6=new JSONArray(),dns=new JSONArray();for(LinkAddress address:link.getLinkAddresses()){String value=address.getAddress().getHostAddress();if(address.getAddress() instanceof java.net.Inet4Address)v4.put(value);else v6.put(value);}
for(java.net.InetAddress address:link.getDnsServers())dns.put(address.getHostAddress());String gateway="";for(RouteInfo route:link.getRoutes())if(route.isDefaultRoute()&&route.getGateway()!=null)gateway=route.getGateway().getHostAddress();
boolean defaultRoute=network.equals(manager.getActiveNetwork());if(defaultRoute)active=link.getInterfaceName();
String ssid="";if(kind.equals("wifi")){ssid=context.getSystemService(WifiManager.class).getConnectionInfo().getSSID();if(ssid.startsWith("\"")&&ssid.endsWith("\""))ssid=ssid.substring(1,ssid.length()-1);}
interfaces.put(kind,obj("kind",kind,"interface",link.getInterfaceName(),"present",true,"connected",true,"state","connected","status_text","Connected","connection",ssid.isEmpty()?link.getInterfaceName():ssid,"ssid",ssid,"addresses",obj("ipv4",v4,"ipv6",v6),"gateway",gateway,"dns",dns,"is_default_route",defaultRoute));
}
for(String kind:new String[]{"wifi","ethernet"})if(!interfaces.has(kind))interfaces.put(kind,obj("kind",kind,"present",false,"connected",false,"state","disconnected","status_text","Disconnected","addresses",obj("ipv4",new JSONArray(),"ipv6",new JSONArray()),"dns",new JSONArray()));
return obj("ok",true,"interfaces",interfaces,"active_uplink",active,"desired_profile",obj("ssid",interfaces.getJSONObject("wifi").optString("ssid")));
}
JSONObject scan()throws Exception{
WifiManager wifi=context.getSystemService(WifiManager.class);boolean accepted=wifi.startScan();JSONArray networks=new JSONArray();for(ScanResult item:wifi.getScanResults())networks.put(obj("ssid",item.SSID,"signal",WifiManager.calculateSignalLevel(item.level,101),"security",item.capabilities,"in_use",false));
return obj("ok",true,"networks",networks,"warning",accepted?"":"Android scan is throttled; showing cached results");
}
JSONObject connect(JSONObject input)throws Exception{
String ssid=input.optString("ssid"),password=input.optString("password");
if(ssid.isEmpty()||ssid.getBytes("UTF-8").length>32||ssid.contains("\n"))throw new IllegalArgumentException("Invalid SSID");
if(!password.isEmpty()&&(password.length()<8||password.length()>63))throw new IllegalArgumentException("Wi-Fi password must contain 8 to 63 characters");
WifiConfiguration config=new WifiConfiguration();config.SSID=JSONObject.quote(ssid);
if(password.isEmpty())config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);else{config.preSharedKey=JSONObject.quote(password);config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);}
WifiManager wifi=context.getSystemService(WifiManager.class);int id=wifi.addNetwork(config);if(id<0)throw new IllegalStateException("Android rejected the Wi-Fi profile");
if(!wifi.enableNetwork(id,true))throw new IllegalStateException("Android could not enable the Wi-Fi profile");
return obj("ok",true,"message","Wi-Fi connection requested. The current remote connection may be interrupted; verify the network status after reconnecting.");
}
}

View File

@ -0,0 +1,25 @@
package com.iomatex.console;
import org.json.*;
import java.net.*;
import java.io.*;
import static com.iomatex.console.ConsoleService.obj;
/** Read-only adapter to the client's canonical public release feed. Installation stays client-owned. */
final class AndroidUpdates {
final boolean embedded;
AndroidUpdates(android.content.Context context){embedded=AndroidClient.PACKAGE.equals(context.getPackageName());}
volatile boolean checking;volatile long checked;volatile String error="";volatile JSONObject manifest=new JSONObject();
synchronized JSONObject check()throws Exception{
if(!checking){checking=true;new Thread(()->{try{
HttpURLConnection c=(HttpURLConnection)new URL("https://git.it-screen.com/An-J/DOWNLOAD_IOMATEX_APP/raw/branch/main/edge-client/android/latest.json").openConnection();c.setConnectTimeout(8000);c.setReadTimeout(8000);c.setInstanceFollowRedirects(false);
try{if(c.getResponseCode()!=200)throw new IOException();try(InputStream in=c.getInputStream();ByteArrayOutputStream out=new ByteArrayOutputStream()){byte[] b=new byte[4096];int n;while((n=in.read(b))!=-1){if(out.size()+n>65536)throw new IOException();out.write(b,0,n);}JSONObject m=new JSONObject(out.toString("UTF-8"));if(!AndroidClient.PACKAGE.equals(m.optString("package_name"))||m.optInt("build_number")<1)throw new IOException();manifest=m;error="";}}
finally{c.disconnect();}
}catch(Exception e){error="Android release feed unavailable ("+e.getClass().getSimpleName()+")";}finally{checked=System.currentTimeMillis()/1000;checking=false;}},"android-release-check").start();}
return obj("ok",true,"checking",true);
}
JSONObject state()throws Exception{return obj("supported",true,"checking",checking,"checked_at",checked,"busy",false,"error",error);}
JSONObject release(String id,String current,long build)throws Exception{
boolean client=id.equals("itscreen");String latest=client?manifest.optString("version"):"";String reason=client?"APK installation is owned by the EVAx10 Android updater. Use Updates in the application.":embedded?"Console is included in EVAx10. Updating the client also updates Console.":"Android Console has no published APK update channel yet. Update this development build through local ADB.";
String status=latest.isEmpty()?"not_checked":build==manifest.optLong("build_number")?"latest":build>manifest.optLong("build_number")?"ahead":"update_available";
return obj("stage",id,"installed",true,"current",current,"latest",latest,"status",status,"can_install",false,"reason",reason);
}
}

View File

@ -0,0 +1,8 @@
package com.iomatex.console;
import android.content.*;
public class BootReceiver extends BroadcastReceiver {
public void onReceive(Context c,Intent i) {
if(android.os.Build.VERSION.SDK_INT<26)return;
if(Intent.ACTION_BOOT_COMPLETED.equals(i.getAction()) || Intent.ACTION_MY_PACKAGE_REPLACED.equals(i.getAction())) ConsoleBootstrap.start(c);
}
}

View File

@ -0,0 +1,40 @@
package com.iomatex.console;
import java.util.HashMap;
import java.util.Map;
/** Read only the canonical private RegistrationStore v1; never resurrect cached credentials. */
final class ClientRegistration {
final String server, user, password;
final boolean registered, logged;
ClientRegistration(String ini) {
Map<String,String> values = new HashMap<>();
boolean section = false;
for(String line : ini.split("\\r?\\n")) {
line = line.trim();
if(line.startsWith("[")) { section = line.equals("[registration]"); continue; }
int separator = line.indexOf('=');
if(section && separator > 0) values.put(line.substring(0, separator), decode(line.substring(separator+1)));
}
server = values.getOrDefault("server", "");
user = values.getOrDefault("device_name", "");
password = values.getOrDefault("password", "");
registered = "true".equals(values.get("is_registered")) && !server.isEmpty() && !user.isEmpty() && !password.isEmpty();
logged = registered && "true".equals(values.get("is_logged"));
}
private static String decode(String value) {
if(value.startsWith("\"") && value.endsWith("\"")) value=value.substring(1,value.length()-1);
StringBuilder out=new StringBuilder();
for(int i=0;i<value.length();i++) {
char c=value.charAt(i);
if(c=='\\' && ++i<value.length()) {
char escaped=value.charAt(i);
if(escaped=='n')out.append('\n');
else if(escaped=='r')out.append('\r');
else if(escaped=='t')out.append('\t');
else if(escaped=='\\' || escaped=='"')out.append(escaped);
else throw new IllegalArgumentException("Unsupported registration escape");
} else out.append(c);
}
return out.toString();
}
}

View File

@ -0,0 +1,42 @@
package com.iomatex.console;
import android.content.*;
import android.content.pm.PackageManager;
import android.os.Build;
import java.io.*;
import java.nio.file.Files;
import java.util.concurrent.TimeUnit;
/** Client lifecycle entrypoint; migration is restricted to our same-signed lab agent. */
public final class ConsoleBootstrap {
public static void start(Context context) {
if(Build.VERSION.SDK_INT<26)return;
Context app=context.getApplicationContext();
new Thread(()->{
try (RandomAccessFile file=new RandomAccessFile(new File(app.getFilesDir(),"console-bootstrap.lock"),"rw"); java.nio.channels.FileLock lock=file.getChannel().lock()) { migrate(app); } catch(Exception e){android.util.Log.w("EvaxConsole","Standalone migration unavailable: "+e.getClass().getSimpleName());}
try { app.startForegroundService(new Intent(app,ConsoleService.class)); }
catch(RuntimeException e){android.util.Log.e("EvaxConsole","Console startup failed",e);}
},"console-bootstrap").start();
}
private static void migrate(Context c)throws Exception {
if(!c.getPackageName().equals("com.magicby.broadcaster.client"))return;
if(c.getPackageManager().checkSignatures(c.getPackageName(),"com.iomatex.console")!=PackageManager.SIGNATURE_MATCH)return;
// Never overwrite established client-owned Console settings on a later launch.
if(!c.getSharedPreferences("console",0).contains("password")){
String xml=readLegacy("shared_prefs/console.xml");
org.xmlpull.v1.XmlPullParser parser=android.util.Xml.newPullParser();parser.setInput(new StringReader(xml));
while(parser.next()!=org.xmlpull.v1.XmlPullParser.END_DOCUMENT){
if(parser.getEventType()==org.xmlpull.v1.XmlPullParser.START_TAG&&"string".equals(parser.getName())&&"password".equals(parser.getAttributeValue(null,"name"))){
if(!c.getSharedPreferences("console",0).edit().putString("password",parser.nextText()).commit())throw new IOException("Cannot save Console settings");
}
}
for(String name:new String[]{"remote_ed25519","remote_ed25519.pub","known_hosts"}){
File target=new File(c.getFilesDir(),name);
if(!target.exists())Files.write(target.toPath(),readLegacy("files/"+name).getBytes(java.nio.charset.StandardCharsets.UTF_8));
}
}
AndroidSettings.command("su","0","pm","disable-user","--user","0","com.iomatex.console");
}
private static String readLegacy(String relative)throws Exception {
return AndroidSettings.command("su","0","cat","/data/user/0/com.iomatex.console/"+relative);
}
}

View File

@ -0,0 +1,139 @@
package com.iomatex.console;
import android.app.*;
import android.content.*;
import android.os.*;
import android.provider.Settings;
import org.json.*;
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.util.*;
import java.util.concurrent.*;
/** Android adapter for the existing Console API. Listener is deliberately loopback-only. */
public class ConsoleService extends Service {
private ServerSocket listener;
private RemoteAccess remote;
private AndroidPlatform platform;
private AndroidClient client;
private AndroidSettings settings;
private AndroidUpdates updates;
private final ExecutorService workers=new ThreadPoolExecutor(2,4,30,TimeUnit.SECONDS,new ArrayBlockingQueue<Runnable>(16));
private final Map<String,Long> sessions=new ConcurrentHashMap<>();
private long retryAfter=0;
private int failures=0;
static String random(){byte[] b=new byte[24];new SecureRandom().nextBytes(b);return android.util.Base64.encodeToString(b,android.util.Base64.NO_WRAP|android.util.Base64.URL_SAFE);}
static String password(Context c){
android.content.SharedPreferences p=c.getSharedPreferences("console",0);
String v=p.getString("password",null);if(v==null){v="iomatex";p.edit().putString("password",v).commit();}return v;
}
public void onCreate(){super.onCreate();password(this);
settings=new AndroidSettings(this);updates=new AndroidUpdates(this);platform=new AndroidPlatform(this);client=new AndroidClient(this);client.start();
remote=new RemoteAccess(this);remote.start();
NotificationManager n=getSystemService(NotificationManager.class);
n.createNotificationChannel(new NotificationChannel("console","EVAx10 Console",NotificationManager.IMPORTANCE_LOW));
startForeground(18080,new Notification.Builder(this,"console").setContentTitle("EVAx10 Console").setContentText("Local diagnostics agent").setSmallIcon(android.R.drawable.stat_notify_sync).build());
new Thread(()->{try{listener=new ServerSocket(18080,8,InetAddress.getByName("127.0.0.1"));while(!listener.isClosed()){Socket s=listener.accept();try{workers.execute(()->serve(s));}catch(RejectedExecutionException e){s.close();}}}catch(IOException e){android.util.Log.e("IomatexConsole","Listener stopped",e);stopSelf();}},"console-listener").start();
}
public int onStartCommand(Intent i,int f,int id){return START_STICKY;}
public IBinder onBind(Intent i){return null;}
public void onDestroy(){if(platform!=null)platform.close();if(client!=null)client.close();if(remote!=null)remote.close();try{if(listener!=null)listener.close();}catch(IOException ignored){}workers.shutdownNow();sessions.clear();super.onDestroy();}
static JSONObject obj(Object... args)throws JSONException{JSONObject o=new JSONObject();for(int i=0;i<args.length;i+=2)o.put((String)args[i],args[i+1]);return o;}
static byte[] bytes(String s){return s.getBytes(StandardCharsets.UTF_8);}
static String line(InputStream in)throws IOException{
ByteArrayOutputStream b=new ByteArrayOutputStream();int c;while((c=in.read())!=-1){if(c==10)break;if(b.size()>=4096)throw new IOException("Line too long");if(c!=13)b.write(c);}return b.toString("UTF-8");
}
void serve(Socket s){try(Socket socket=s){socket.setSoTimeout(5000);InputStream in=socket.getInputStream();String[] request=line(in).split(" ");if(request.length!=3)return;
String method=request[0],path=request[1].split("\\?",2)[0];Map<String,String> headers=new HashMap<>();int total=0;String h;
while(!(h=line(in)).isEmpty()){total+=h.length();if(total>16384)throw new IOException("Headers too large");int colon=h.indexOf(':');if(colon<1)throw new IOException("Invalid header");String key=h.substring(0,colon).toLowerCase(Locale.ROOT);if(headers.containsKey(key))throw new IOException("Duplicate header");headers.put(key,h.substring(colon+1).trim());}
int length=Integer.parseInt(headers.getOrDefault("content-length","0"));if(length<0||length>8192||headers.containsKey("transfer-encoding")){reply(socket,400,"application/json",bytes("{\"ok\":false}"),null);return;}
byte[] body=new byte[length];new DataInputStream(in).readFully(body);
if(!method.equals("GET")&&!method.equals("POST")){reply(socket,405,"application/json",bytes("{}"),null);return;}
String cookie="";for(String c:headers.getOrDefault("cookie","").split(";")){if(c.trim().startsWith("iomatex_session="))cookie=c.trim().substring(16);}
long now=System.currentTimeMillis()/1000;boolean auth=sessions.getOrDefault(cookie,0L)>now;
JSONObject result=null;String setCookie=null;int code=200;
if(path.equals("/api/auth/login")&&method.equals("POST")){
if(!headers.getOrDefault("content-type","").startsWith("application/json")){code=415;result=obj("ok",false);}
else synchronized(this){JSONObject credentials=new JSONObject(new String(body,StandardCharsets.UTF_8));
if(now<retryAfter){code=429;result=obj("ok",false,"error","Try again later");}
else if("iomatex".equals(credentials.optString("username"))&&MessageDigest.isEqual(bytes(password(this)),bytes(credentials.optString("password")))){
failures=0;sessions.entrySet().removeIf(e->e.getValue()<=now);if(sessions.size()>=16)sessions.clear();String token=random();sessions.put(token,now+900);setCookie="iomatex_session="+token+"; HttpOnly; SameSite=Strict; Path=/; Max-Age=900";result=session(true,now+900);
}else{failures++;if(failures>=5)retryAfter=now+30;code=401;result=obj("ok",false,"error","Invalid credentials");}}
}else if(path.equals("/api/auth/session")&&method.equals("GET")){result=session(auth,sessions.getOrDefault(cookie,0L));}
else if(path.startsWith("/api/")){
if(!auth){code=401;result=obj("ok",false,"error","Authorization required");}
else if(path.equals("/api/auth/logout")&&method.equals("POST")){sessions.remove(cookie);setCookie="iomatex_session=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0";result=obj("ok",true);}
else if(method.equals("POST") && Arrays.asList("/api/auth/password/change","/api/system/timezone","/api/network/profile/apply","/api/stages/check").contains(path)){
if(!headers.getOrDefault("content-type","").startsWith("application/json")){code=415;result=obj("ok",false,"error","JSON required");}
else try{
JSONObject input=new JSONObject(new String(body,StandardCharsets.UTF_8));
if(path.equals("/api/auth/password/change")){
String old=input.optString("current_password"),next=input.optString("new_password");
if(!MessageDigest.isEqual(bytes(password(this)),bytes(old)))throw new IllegalArgumentException("Current password is incorrect");
if(next.length()<8||next.length()>128||next.equals(old)||!next.equals(input.optString("confirm_password")))throw new IllegalArgumentException("New password must match confirmation, differ from current and contain 8 to 128 characters");
if(!getSharedPreferences("console",0).edit().putString("password",next).commit())throw new IllegalStateException("Password could not be saved");
sessions.clear();sessions.put(cookie,now+900);result=obj("ok",true,"message","Console password changed successfully");
}else if(path.equals("/api/system/timezone"))result=settings.setTimezone(input);
else if(path.equals("/api/network/profile/apply"))result=settings.connect(input);
else result=updates.check();
}catch(IllegalArgumentException e){code=400;result=obj("ok",false,"error",e.getMessage());}
catch(Exception e){code=503;result=obj("ok",false,"error",e instanceof IllegalStateException?e.getMessage():"Android operation unavailable ("+e.getClass().getSimpleName()+")");}
}
else if(path.equals("/api/itscreen/register")&&method.equals("POST")){
if(!headers.getOrDefault("content-type", "").startsWith("application/json")){code=415;result=obj("ok",false,"error","JSON required");}
else try{result=client.transfer(new JSONObject(new String(body,StandardCharsets.UTF_8)));}
catch(IllegalArgumentException e){code=400;result=obj("ok",false,"error",e.getMessage());}
catch(IllegalStateException e){code=409;result=obj("ok",false,"error",e.getMessage());}
catch(Exception e){code=503;result=obj("ok",false,"error","Client settings channel unavailable");}
}
else if(path.equals("/api/actions/reboot")&&method.equals("POST")){
try{
if(!"0".equals(AndroidSettings.command("su","0","id","-u")))throw new IllegalStateException("Root access is required to reboot Android");
new ProcessBuilder("su","0","sh","-c","sleep 3; /system/bin/reboot").redirectErrorStream(true).redirectOutput(new File(getFilesDir(),"reboot.log")).start();
new Handler(Looper.getMainLooper()).postDelayed(()->remote.close(),1000);
result=obj("ok",true,"message","Reboot requested. Connection may drop shortly.");
}catch(Exception e){code=503;result=obj("ok",false,"error","Android reboot could not be requested: privileged access unavailable");}
}
else if(!method.equals("GET")){code=501;result=obj("ok",false,"error","This operation is not supported by the Android prototype");}
else if(path.equals("/api/status")){result=obj("ok",true,"identity",identity(),"generated_at",new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX",Locale.ROOT).format(new Date()),"platform","android");}
else if(path.equals("/api/health/summary")){result=platform.health(identity());}
else if(path.equals("/api/system/timezone")){result=settings.timezone();}
else if(path.equals("/api/network/summary")){result=settings.network();}
else if(path.equals("/api/network/scan")){result=settings.scan();}
else if(path.equals("/api/display")){result=platform.display();}
else if(path.equals("/api/itscreen/status")){result=client.status();}
else if(path.equals("/api/itscreen/registration")){result=client.registration();}
else if(path.equals("/api/itscreen/runtime")){result=client.runtime();}
else if(path.equals("/api/remote/status")){result=remote.snapshot();}
else if(path.equals("/api/health/services")){result=services(now);}
else{code=501;result=obj("ok",false,"error","Not available on Android prototype");}
}else if(method.equals("GET")){
String asset=path.equals("/")?"index.html":path.substring(1);
if(!Arrays.asList("index.html","console.js","console.css","console.i18n.js","logo.png","favicon.png","g-box.png").contains(asset)){reply(socket,404,"text/plain",bytes("Not found"),null);return;}
try(InputStream a=getAssets().open(getPackageName().equals(AndroidClient.PACKAGE)?"evaxconsole/"+asset:asset)){ByteArrayOutputStream out=new ByteArrayOutputStream();byte[] b=new byte[8192];int n;while((n=a.read(b))!=-1)out.write(b,0,n);String type=asset.endsWith(".js")?"application/javascript":asset.endsWith(".css")?"text/css":asset.endsWith(".png")?"image/png":"text/html";reply(socket,200,type,out.toByteArray(),null);return;}
}else{code=405;result=obj("ok",false);}
reply(socket,code,"application/json",bytes(result.toString()),setCookie);
}catch(Exception e){android.util.Log.w("IomatexConsole","Request rejected: "+e.getClass().getSimpleName());}}
JSONObject session(boolean authenticated,long expiry)throws JSONException{return obj("ok",true,"authenticated",authenticated,"username","iomatex","expires_at",expiry);}
JSONObject identity()throws JSONException{return obj("serial_number",remote.deviceId.isEmpty()?Settings.Secure.getString(getContentResolver(),Settings.Secure.ANDROID_ID):remote.deviceId,"hostname",Build.MODEL,"os","Android "+Build.VERSION.RELEASE,"platform","android","prototype",true);}
JSONObject card(String id,String title,boolean active,String status,JSONArray details)throws JSONException{return obj("id",id,"title",title,"installed",true,"configured",active,"active",active,"state",active?"active":"unknown","status_text",status,"details",details);}
JSONObject services(long now)throws Exception{
JSONArray cards=new JSONArray();
cards.put(card("android_agent","EVAx10 Android Console",true,"Active",new JSONArray().put(obj("label","Version","value","0.5.0-dev"))));
JSONObject application=client.service();application.put("release",updates.release("itscreen",client.version(),getPackageManager().getPackageInfo(AndroidClient.PACKAGE,0).versionCode));
cards.getJSONObject(0).put("release",updates.release("android_agent","0.5.0-dev",7));
cards.put(application);cards.put(platform.osCard());cards.put(platform.display());
JSONObject access=remote.snapshot();
JSONObject tunnel=card("reverse_tunnel","Reverse Tunnels",access.optBoolean("available"),access.optString("status","Starting"),new JSONArray().put(obj("label","SSH","value",access.optBoolean("ssh_connected")?"Connected":"Disconnected")).put(obj("label","Diagnostics","value",access.optString("reason","Starting"))));
tunnel.put("configured",remote.clientRegistered).put("state",access.optBoolean("available")?"active":"degraded")
.put("capabilities",obj("can_configure",false,"can_restart",false))
.put("configuration_hint","Remote access follows the current EVAx10 registration automatically.")
.put("tunnels",new JSONArray().put(obj("name","Edge Console","local_port",18080,
"active",access.optBoolean("available"),"state",access.optBoolean("available")?"active":"failed",
"status_text",access.optBoolean("available")?"Available":access.optString("reason","Starting"))));
if(!access.optBoolean("available"))tunnel.put("warnings",new JSONArray().put(access.optString("reason","Starting")));cards.put(tunnel);
return obj("ok",true,"identity",identity(),"generated_at",new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX",Locale.ROOT).format(new Date()),"services",cards,"updates",updates.state());
}
static void reply(Socket s,int code,String type,byte[] body,String cookie)throws IOException{OutputStream out=s.getOutputStream();String h="HTTP/1.1 "+code+" Response\r\nContent-Type: "+type+"; charset=utf-8\r\nContent-Length: "+body.length+"\r\nConnection: close\r\nCache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\nX-Frame-Options: DENY\r\n";if(cookie!=null)h+="Set-Cookie: "+cookie+"\r\n";out.write(bytes(h+"\r\n"));out.write(body);out.flush();}
}

View File

@ -0,0 +1,18 @@
package com.iomatex.console;
/** Linux aggregate ticks: guest counters are already included in user/nice. */
final class CpuSample {
final long total, idle;
CpuSample(String line) {
String[] fields=line.trim().split("\\s+");
if(fields.length<9 || !fields[0].equals("cpu"))throw new IllegalArgumentException("Invalid CPU sample");
long sum=0; for(int i=1;i<=8;i++){long tick=Long.parseLong(fields[i]);if(tick<0)throw new IllegalArgumentException("Negative tick");sum+=tick;}
total=sum;idle=Long.parseLong(fields[4])+Long.parseLong(fields[5]);
}
Double usage(CpuSample previous){
if(previous==null)return null;
long elapsed=total-previous.total, rest=idle-previous.idle;
if(elapsed<=0 || rest<0 || rest>elapsed)return null;
return Math.round(1000.0*(elapsed-rest)/elapsed)/10.0;
}
}

View File

@ -0,0 +1,202 @@
package com.iomatex.console;
import android.content.Context;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.KeyPair;
import com.jcraft.jsch.Session;
import org.json.JSONObject;
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
/** One device-owned connection, enrolled through the existing platform API. */
final class RemoteAccess implements AutoCloseable {
private final Context context;
private volatile boolean stopped;
private volatile Session session;
private Thread worker;
private String registration = "";
volatile boolean clientRegistered;
volatile String deviceId = "";
private volatile JSONObject state = new JSONObject();
RemoteAccess(Context context) { this.context = context; }
void start() {
worker = new Thread(() -> {
while (!stopped) {
try { reconcile(); }
catch (Exception e) {
android.util.Log.w("EvaxRemote", e.getClass().getSimpleName() + " " + java.util.Arrays.toString(e.getStackTrace()));
disconnect();
try { publish("unavailable", failureReason(e), false, null); } catch (Exception ignored) {}
}
try { Thread.sleep(15000); } catch (InterruptedException e) { break; }
}
disconnect();
}, "evax10-remote-access");
worker.start();
}
JSONObject snapshot() {
JSONObject current = state;
if(current.optBoolean("available") && (session == null || !session.isConnected()
|| System.currentTimeMillis()/1000 - current.optLong("checked_at") > 60)) {
try {
return new JSONObject(current.toString()).put("available", false).put("status", "degraded")
.put("reason", "SSH disconnected or diagnostics expired").put("ssh_connected", session != null && session.isConnected());
} catch(Exception ignored) { return new JSONObject(); }
}
return current;
}
private void publish(String status, String reason, boolean available, JSONObject extra) throws Exception {
JSONObject next = new JSONObject();
next.put("status", status).put("reason", reason).put("available", available)
.put("ssh_connected", session != null && session.isConnected())
.put("checked_at", System.currentTimeMillis()/1000);
if (extra != null) next.put("diagnostics", extra);
state = next;
}
static String readClient(Context context, String relative) throws Exception {
// The embedded agent owns the client UID: registration never needs root.
if(!relative.equals("no_backup/registration.ini")&&!relative.equals("files/configs.json"))throw new IOException("Unsupported client store");
if(context.getPackageName().equals(AndroidClient.PACKAGE)) {
File file=new File(context.getApplicationInfo().dataDir,relative);
if(file.length()>2*1024*1024)throw new IOException("Client store too large");
return new String(java.nio.file.Files.readAllBytes(file.toPath()),StandardCharsets.UTF_8);
}
// Standalone diagnostic APK compatibility.
Process process = new ProcessBuilder("su", "0", "cat",
"/data/user/0/com.magicby.broadcaster.client/" + relative)
.redirectErrorStream(true).start();
ByteArrayOutputStream output = new ByteArrayOutputStream();
Thread reader = new Thread(() -> {
try (InputStream in = process.getInputStream()) {
byte[] b = new byte[4096]; int n;
while ((n = in.read(b)) >= 0) {
if (output.size() + n > 2*1024*1024) { process.destroy(); break; }
output.write(b, 0, n);
}
} catch (IOException ignored) {}
});
reader.start();
if (!process.waitFor(4, TimeUnit.SECONDS)) { process.destroyForcibly(); reader.join(1000); throw new IOException("Root adapter timed out"); }
reader.join(1000);
if (process.exitValue() != 0) throw new IOException("Root registration adapter unavailable");
return new String(output.toByteArray(), StandardCharsets.UTF_8);
}
private void reconcile() throws Exception {
ClientRegistration client = new ClientRegistration(readClient(context,"no_backup/registration.ini"));
clientRegistered = client.registered; deviceId = client.user;
String server = client.server, user = client.user, password = client.password;
if (!client.registered) {
disconnect(); registration = "";
publish("waiting_registration", "Client is not registered", false, null); return;
}
if (!server.contains("://")) server = "https://" + server;
URI uri = new URI(server);
if (!"https".equals(uri.getScheme()) || uri.getHost() == null || uri.getUserInfo() != null
|| uri.getQuery() != null || uri.getFragment() != null
|| !(uri.getPath().isEmpty() || "/".equals(uri.getPath()))) {
disconnect(); publish("invalid_registration", "Remote enrollment requires a valid HTTPS server", false, null); return;
}
server = server.replaceAll("/+$", "");
String next = server + "\n" + user + "\n" + password;
if (!next.equals(registration)) { disconnect(); registration = next; }
File key = new File(context.getFilesDir(), "remote_ed25519");
JSch ssh = new JSch();
if (!key.exists() || key.length() == 0) {
KeyPair pair = KeyPair.genKeyPair(ssh, KeyPair.ED25519);
pair.writeOpenSSHv1PrivateKey(key.getAbsolutePath()+".new");
pair.writePublicKey(key.getAbsolutePath()+".pub", "evax10-android");
pair.dispose();
java.nio.file.Files.move(new File(key+".new").toPath(), key.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING);
}
if (session == null || !session.isConnected()) {
publish("connecting", "Enrolling with registration server", false, null);
String publicKey = new String(java.nio.file.Files.readAllBytes(new File(key+".pub").toPath()), StandardCharsets.UTF_8);
JSONObject enrollment = request(server + "/v2/device/reverse-tunnel", user, password,
"public_key=" + URLEncoder.encode(publicKey, "UTF-8")).getJSONObject("reverse_tunnel");
String host = enrollment.getString("ssh_host"), sshUser = enrollment.optString("ssh_user", "iomatex-tunnel");
int port = enrollment.optInt("ssh_port", 22);
int remote = enrollment.getJSONObject("ports").getJSONObject("webui").getInt("remote");
if (!host.matches("[a-zA-Z0-9.-]+") || !sshUser.matches("[a-zA-Z0-9_-]+")
|| port < 1 || port > 65535 || remote < 1024 || remote > 65535) throw new IOException("Invalid tunnel assignment");
// Enrollment is authenticated HTTPS; server public keys are bound to its assignment.
if(enrollment.has("ssh_host_keys")) {
org.json.JSONArray keys=enrollment.getJSONArray("ssh_host_keys");
StringBuilder trusted=new StringBuilder();
for(int i=0;i<keys.length();i++){
String value=keys.getString(i);
if(!value.matches("(ssh-ed25519|ecdsa-sha2-nistp256|ssh-rsa) [A-Za-z0-9+/]+={0,3}"))throw new IOException("Invalid server host key");
trusted.append(port==22?host:"["+host+"]:"+port).append(" ").append(value).append("\n");
}
if(trusted.length()==0)throw new IOException("Server supplied no SSH host keys");
java.nio.file.Files.write(new File(context.getFilesDir(),"known_hosts").toPath(),trusted.toString().getBytes(StandardCharsets.UTF_8));
}
// Older environments may use administrator-provisioned trust.
File known = new File(context.getFilesDir(), "known_hosts");
if (!known.exists()) {
publish("host_key_required", "Trusted SSH host key is missing for " + host + ":" + port, false, null); return;
}
ssh.setKnownHosts(known.getAbsolutePath());
ssh.addIdentity(key.getAbsolutePath());
Session candidate = ssh.getSession(sshUser, host, port);
candidate.setConfig("StrictHostKeyChecking", "yes");
candidate.setConfig("PreferredAuthentications", "publickey");
candidate.setServerAliveInterval(15000); candidate.setServerAliveCountMax(3);
try {
candidate.connect(10000);
candidate.setPortForwardingR("127.0.0.1", remote, "127.0.0.1", 18080);
if (stopped) { candidate.disconnect(); return; }
session = candidate;
} catch (Exception e) { candidate.disconnect(); throw e; }
}
JSONObject diagnostics = request(server + "/v2/device/reverse-tunnel-status", user, password, null).getJSONObject("diagnostics");
boolean gateway = diagnostics.optJSONObject("gateway") != null && diagnostics.getJSONObject("gateway").optBoolean("active");
boolean receiver = diagnostics.optJSONObject("receiver") != null && diagnostics.getJSONObject("receiver").optBoolean("active");
JSONObject ports = diagnostics.optJSONObject("ports");
JSONObject web = ports == null ? null : ports.optJSONObject("webui");
boolean listening = web != null && web.optBoolean("available");
publish(gateway && receiver && listening ? "available" : "degraded",
!gateway ? "Web Gateway unavailable" : !receiver ? "SSH receiver unavailable" : !listening ? "Remote web port is not confirmed" : "Browser gateway and remote port verified",
gateway && receiver && listening, diagnostics);
}
private JSONObject request(String url, String user, String password, String body) throws Exception {
javax.net.ssl.HttpsURLConnection connection = (javax.net.ssl.HttpsURLConnection)new URL(url).openConnection();
connection.setInstanceFollowRedirects(false); connection.setConnectTimeout(8000); connection.setReadTimeout(8000);
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Authorization", "Basic " + android.util.Base64.encodeToString(
(user+":"+password).getBytes(StandardCharsets.UTF_8), android.util.Base64.NO_WRAP));
try {
if (body != null) {
connection.setRequestMethod("POST"); connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
try(OutputStream out = connection.getOutputStream()) { out.write(body.getBytes(StandardCharsets.UTF_8)); }
}
int status = connection.getResponseCode();
if (status != 200) throw new IOException("HTTP " + status + " from registration server");
ByteArrayOutputStream output = new ByteArrayOutputStream();
try(InputStream in = connection.getInputStream()) {
byte[] buffer = new byte[4096]; int n;
while ((n = in.read(buffer)) >= 0) {
if (output.size() + n > 131072) throw new IOException("Response too large");
output.write(buffer, 0, n);
}
}
return new JSONObject(new String(output.toByteArray(), StandardCharsets.UTF_8));
} finally { connection.disconnect(); }
}
private String failureReason(Exception error) {
String message = error.getMessage() == null ? "" : error.getMessage();
String lower = message.toLowerCase(java.util.Locale.ROOT);
if(message.startsWith("HTTP ")) return message;
if(lower.contains("hostkey") || lower.contains("host key")) return "SSH server key is missing, changed or untrusted";
if(lower.contains("remote port forwarding failed")) return "SSH receiver has not released the remote port; reconnecting automatically";
if(lower.contains("auth fail")) return "SSH receiver rejected the device key";
if(error instanceof java.net.UnknownHostException) return "Server DNS resolution failed";
if(lower.contains("timed out") || lower.contains("timeout")) return "Server or registration adapter timed out";
if(lower.contains("root registration")) return "Root access to the client registration store is unavailable";
return "Connection failed: " + error.getClass().getSimpleName();
}
private void disconnect() { Session current = session; session = null; if (current != null) current.disconnect(); }
public void close() { stopped = true; disconnect(); if(worker != null) worker.interrupt(); }
}

View File

@ -0,0 +1,16 @@
package com.iomatex.console;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.widget.TextView;
public class SetupActivity extends Activity {
public void onCreate(Bundle b) {
super.onCreate(b);
String password=ConsoleService.password(this);
startForegroundService(new Intent(this,ConsoleService.class));
TextView text=new TextView(this);
text.setText("EVAx10 Console · Development\n\nLocal endpoint: 127.0.0.1:18080\n\nUser: iomatex\nPassword: "+password+"\n\nAccess through an authenticated tunnel only.\nRemote gateway: see Console diagnostics.");
text.setBackgroundColor(0xff0a101a); text.setTextColor(0xffe6edf7);
text.setTextSize(22); text.setPadding(32,32,32,32); setContentView(text);
}
}

View File

@ -0,0 +1,35 @@
package com.iomatex.console;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.*;
/** Linux thermal-zone ABI, also consumed by the client's NativeSystemMetrics.
* Preserve sensor identity; a SoC zone is not an inferred CPU measurement.
*/
final class ThermalSensors {
static final class Reading {
final String name; final Double celsius;
Reading(String name,Double celsius){this.name=name;this.celsius=celsius;}
}
static List<Reading> read(File root){
List<Reading> result=new ArrayList<>();
File[] zones=root.listFiles(f->f.getName().matches("thermal_zone[0-9]+"));
if(zones==null)return result;
Arrays.sort(zones,Comparator.comparing(File::getName));
for(File zone:zones){
String name=text(new File(zone,"type"));if(name.isEmpty())name=zone.getName();
// Vendor test zones are not hardware telemetry. Battery temperature belongs
// to Android BatteryManager (different units), not this CPU/GPU adapter.
String kind=name.toLowerCase(Locale.ROOT);
if(kind.startsWith("test") || kind.contains("battery"))continue;
Double value=null;
try{double degrees=Double.parseDouble(text(new File(zone,"temp")))/1000.0;
if(Double.isFinite(degrees)&&degrees>=-50&&degrees<=150)value=Math.round(degrees*10.0)/10.0;
}catch(NumberFormatException ignored){}
result.add(new Reading(name,value));
}
return result;
}
private static String text(File file){try{if(file.length()>4096)return "";return new String(Files.readAllBytes(file.toPath()),StandardCharsets.UTF_8).trim();}catch(IOException|SecurityException e){return "";}}
}

View File

@ -0,0 +1,58 @@
"""Read-only HTTP integration checks over an existing Windows ADB forward."""
import json, os, subprocess, time, xml.etree.ElementTree as ET
ADB=os.environ.get('ADB','/mnt/c/Users/Andrei/AppData/Local/Android/Sdk/platform-tools/adb.exe')
SERIAL=os.environ.get('ANDROID_SERIAL','192.168.0.186:5555')
CURL='/mnt/c/Windows/System32/curl.exe'
PACKAGE=os.environ.get('CONSOLE_PACKAGE','com.iomatex.console')
raw=subprocess.check_output([ADB,'-s',SERIAL,'shell','run-as '+PACKAGE+' cat shared_prefs/console.xml'])
password=ET.fromstring(raw).find("string[@name='password']").text
def request(path, body=None, cookie=None):
args=[CURL,'-sS','--max-time','8','-i','http://127.0.0.1:18080'+path]
if body is not None: args += ['-H','Content-Type: application/json','--data-binary','@-']
if cookie: args += ['-H','Cookie: '+cookie]
data=subprocess.check_output(args,input=json.dumps(body).encode() if body is not None else None).decode()
headers,payload=data.replace('\r\n','\n').split('\n\n',1)
return int(headers.split()[1]),headers,payload
assert request('/api/status')[0]==401
assert request('/api/actions/reboot',{})[0]==401
code,headers,body=request('/api/auth/login',{'username':'iomatex','password':password})
assert code==200 and json.loads(body)['authenticated']
cookie=next(l.split(': ',1)[1].split(';')[0] for l in headers.splitlines() if l.startswith('Set-Cookie:'))
for path in ['/api/status','/api/health/summary','/api/health/services','/api/display','/api/system/timezone','/api/network/summary','/api/itscreen/status','/api/itscreen/runtime','/api/itscreen/registration']:
code,_,body=request(path,cookie=cookie)
assert code==200 and json.loads(body).get('ok',path=='/api/display'), (path,code)
if path=='/api/health/summary':
health=json.loads(body)
for attempt in range(15):
if health.get('cpu_usage_percent') is not None: break
time.sleep(1)
health=json.loads(request(path,cookie=cookie)[2])
assert 0 <= health['cpu_usage_percent'] <= 100
assert len(health['load_average']) == 3
readings=health['temperatures']
assert {'soc-thermal','gpu-thermal'} <= {r['name'] for r in readings}
assert all(r['value_c'] is None or -50 <= r['value_c'] <= 150 for r in readings)
assert not any(r['name'].startswith('test') for r in readings)
if path=='/api/display':
display=json.loads(body)
assert display['id']=='display' and display['connectors']
assert display['capabilities']=={'desktop_mode':False,'pulse_audio':False}
if path=='/api/itscreen/registration':
data=json.loads(body)
assert 'password' not in data and data['capabilities']['can_reset'] is False
if path=='/api/health/services':
ids={item['id'] for item in json.loads(body)['services']}
assert {'itscreen','display','environment'} <= ids
assert not ids & {'modbus','cockpit','zigbee2mqtt'}
assert request('/api/system/reboot',{},cookie)[0]==501
assert request('/api/auth/password/change',{'current_password':'invalid','new_password':'temporary123','confirm_password':'temporary123'},cookie)[0]==400
assert request('/api/system/timezone',{'timezone':'Invalid/Zone'},cookie)[0]==400
assert request('/api/network/profile/apply',{'ssid':''},cookie)[0]==400
assert request('/api/stages/check',{},cookie)[0]==200
assert request('/api/itscreen/registration/reset',{},cookie)[0]==501
assert request('/api/itscreen/register',{'host':'https://bad.example/path'},cookie)[0] in (400,409)
assert request('/../AndroidManifest.xml')[0]==404
assert request('/api/auth/logout',{},cookie)[0]==200
assert request('/api/status',cookie=cookie)[0]==401
print('PASS: authorization, login, status, health, services, unsupported mutation, asset allowlist, logout/revocation')

View File

@ -0,0 +1,20 @@
package com.iomatex.console;
public final class ClientRegistrationTest {
public static void main(String[] args) {
ClientRegistration c=new ClientRegistration("[meta]\nversion=1\n[registration]\nserver=https://Rest.eva.iomatex.com\ndevice_name=Android-test\npassword=secret\nis_registered=true\n");
if(!c.registered || !c.server.equals("https://Rest.eva.iomatex.com"))throw new AssertionError("canonical store");
c=new ClientRegistration("[General]\nserver=https://old.example\ndevice_name=old\npassword=old\nis_registered=true");
if(c.registered || !c.password.isEmpty())throw new AssertionError("legacy credentials must not resurrect registration");
c=new ClientRegistration("[registration]\nserver=https://new.example\ndevice_name=device\npassword=secret\nis_registered=false");
if(c.registered)throw new AssertionError("registration reset");
c=new ClientRegistration("[registration]\nserver=https://new.example\ndevice_name=device\npassword=\"quoted\\\\value\"\nis_registered=true");
if(!c.password.equals("quoted\\value"))throw new AssertionError("Qt escaped string");
c=new ClientRegistration("[registration]\nserver=\ndevice_name=device\npassword=secret\nis_registered=true");
if(c.registered)throw new AssertionError("missing server is not a default environment");
c=new ClientRegistration("[registration]\nserver=https://new.example\ndevice_name=device\npassword=secret\nis_registered=true\nis_logged=true");
if(!c.logged)throw new AssertionError("confirmed login");
c=new ClientRegistration("[registration]\nserver=https://new.example\ndevice_name=device\npassword=secret\nis_registered=false\nis_logged=true");
if(c.logged)throw new AssertionError("login cannot survive cleared registration");
System.out.println("PASS canonical registration, legacy isolation, reset, quoting, missing server");
}
}

View File

@ -0,0 +1,11 @@
package com.iomatex.console;
public class CpuSampleTest {
public static void main(String[] args){
CpuSample a=new CpuSample("cpu 100 0 100 800 0 0 0 0 50 0");
CpuSample b=new CpuSample("cpu 150 0 100 850 0 0 0 0 75 0");
if(b.usage(a)!=50.0 || a.usage(null)!=null || a.usage(b)!=null || a.usage(a)!=null)throw new AssertionError();
CpuSample c=new CpuSample("cpu 150 0 100 900 50 0 0 0");
if(c.usage(b)!=0.0)throw new AssertionError("iowait included as idle");
System.out.println("PASS: aggregate CPU delta, guest exclusion, reset, first sample, iowait");
}
}

View File

@ -0,0 +1,21 @@
package com.iomatex.console;
import java.nio.file.*;
import java.util.*;
public final class ThermalSensorsTest {
static void zone(Path root,int index,String name,String raw)throws Exception{
Path path=Files.createDirectory(root.resolve("thermal_zone"+index));Files.write(path.resolve("type"),name.getBytes());if(raw!=null)Files.write(path.resolve("temp"),raw.getBytes());
}
public static void main(String[] args)throws Exception{
Path root=Files.createTempDirectory("thermal-contract");
try{
zone(root,0,"soc-thermal","63888");zone(root,1,"gpu-thermal","60000");zone(root,2,"test_battery","2600");
zone(root,3,"cpu-missing",null);zone(root,4,"bad","NaN");zone(root,5,"overflow","999999");zone(root,6,"zero","0");
List<ThermalSensors.Reading> values=ThermalSensors.read(root.toFile());
if(values.size()!=6||!values.get(0).name.equals("soc-thermal")||values.get(0).celsius!=63.9||values.get(1).celsius!=60.0)throw new AssertionError("identity/scaling/test-zone exclusion");
for(int i=2;i<=4;i++)if(values.get(i).celsius!=null)throw new AssertionError("unavailable/invalid values must not become temperatures");
if(values.get(5).celsius!=0.0)throw new AssertionError("zero is a valid temperature");
if(!ThermalSensors.read(root.resolve("missing").toFile()).isEmpty())throw new AssertionError("missing sysfs");
System.out.println("PASS thermal units, identity, unavailable, invalid, range and zero");
}finally{try(java.util.stream.Stream<Path> paths=Files.walk(root)){paths.sorted(Comparator.reverseOrder()).forEach(p->{try{Files.delete(p);}catch(Exception ignored){}});}}
}
}

View File

@ -0,0 +1,63 @@
const {chromium}=require(process.env.PLAYWRIGHT_MODULE || 'playwright');
const {execFileSync}=require('child_process');
(async()=>{
const browser=await chromium.launch({headless:true,executablePath:process.env.CHROMIUM_EXECUTABLE});const page=await browser.newPage({viewport:{width:1280,height:900}});const errors=[];page.on('pageerror',e=>errors.push(e.message));
let cookie='';
await page.route('http://127.0.0.1:18080/**',async route=>{
const req=route.request();let args=['-sS','-i','--max-time','8',req.url()];if(cookie)args.push('-H','Cookie: '+cookie);if(req.method()==='POST')args.push('-H','Content-Type: application/json','--data-binary','@-');
const raw=execFileSync('/mnt/c/Windows/System32/curl.exe',args,{input:req.postData()||'',maxBuffer:10000000});const pos=raw.indexOf('\r\n\r\n');const h=raw.subarray(0,pos).toString();const headers={};for(const line of h.split('\r\n').slice(1)){let k=line.indexOf(':');if(k>0)headers[line.slice(0,k).toLowerCase()]=line.slice(k+1).trim();}if(headers['set-cookie'])cookie=headers['set-cookie'].split(';')[0];delete headers['content-length'];delete headers['connection'];
await route.fulfill({status:Number(h.split(' ')[1]),headers,body:raw.subarray(pos+4)});
});
await page.goto('http://127.0.0.1:18080/');await page.waitForTimeout(1500);
console.log('Inputs:',await page.locator('input').evaluateAll(xs=>xs.map(x=>({id:x.id,type:x.type}))));
const xml=execFileSync(process.env.ADB || '/mnt/c/Users/Andrei/AppData/Local/Android/Sdk/platform-tools/adb.exe',['-s',process.env.ANDROID_SERIAL || '192.168.0.186:5555','shell','run-as '+(process.env.CONSOLE_PACKAGE || 'com.iomatex.console')+' cat shared_prefs/console.xml'],{encoding:'utf8'});const password=xml.match(/name="password">([^<]+)/)[1];
await page.locator('input[type=password]').fill(password);
await page.locator('input[type=password]').press('Enter');await page.waitForTimeout(2000);
console.log('Errors:',errors);
if(await page.locator('[data-tab=modbus]').count())throw new Error('Modbus must not be exposed');
await page.locator('.displayCard').waitFor();
const healthText=await page.locator('body').innerText();
if(!healthText.includes('soc-thermal') || !healthText.includes('gpu-thermal'))throw new Error('Real thermal sensors missing');
if(await page.locator('.displayModePanel, .audioDeviceGrid').count())throw new Error('Linux display controls exposed');
console.log('Theme:',await page.locator('html').getAttribute('data-theme'));
for(const width of [360,768,1024,1440]) {
await page.setViewportSize({width,height:900});
const overflow=await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth);
if(overflow)throw new Error('Horizontal overflow at '+width);
await page.screenshot({path:'/tmp/android-console-'+width+'.png',fullPage:true});
}
await page.locator('[data-tab=tscreen]').click();await page.waitForTimeout(2000);
await page.locator('#itscreenRegistrationStatus').waitFor();
const host=page.locator('#itscreenCustomHost');
if(await host.count()){
const original=await host.inputValue();
if(await page.locator('#itscreenRegisterBtn').isEnabled())throw new Error('Unchanged registration enabled');
await host.fill('https://example.com');
await page.waitForFunction(()=>{const button=document.getElementById('itscreenRegisterBtn');return button && !button.disabled;},{},{timeout:15000});
await host.fill(original);
if(await page.locator('#itscreenRegisterBtn').isEnabled())throw new Error('Restored registration enabled');
}
if(await page.locator('.itscreenLogsCard').count())throw new Error('Unsupported log controls exposed');
for(const width of [360,768,1024,1440]){
await page.setViewportSize({width,height:900});
if(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth))throw new Error('Registration overflow at '+width);
}
await page.locator('[data-tab=security]').click();await page.waitForTimeout(1500);
await page.locator('.accountSecurityCard').waitFor();
const save=page.locator('[data-account-password-form] button[type=submit]');
if(await save.isEnabled())throw new Error('Unchanged password enabled');
await page.locator('[autocomplete=current-password]').fill('current-test');
await page.locator('[autocomplete=new-password]').nth(0).fill('replacement-test');
await page.locator('[autocomplete=new-password]').nth(1).fill('replacement-test');
if(!await save.isEnabled())throw new Error('Valid password form disabled');
await page.locator('[autocomplete=new-password]').nth(1).fill('');
if(await save.isEnabled())throw new Error('Invalid password form enabled');
if(!await page.locator('#timezoneSearchInput').inputValue())throw new Error('Time zone missing');
for(const tab of ['security','network']){
await page.locator('[data-tab='+tab+']').click();await page.waitForTimeout(1500);
for(const width of [360,768,1024,1440]){await page.setViewportSize({width,height:900});if(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth))throw new Error(tab+' overflow '+width);}
}
await page.locator('#wifiSsid').waitFor();
console.log('PASS Display, registration, region, password dirty state and network UI at four widths');
await browser.close();if(errors.length)process.exit(1);
})();

View File

@ -0,0 +1,13 @@
"""Runtime resources must survive the custom DEX/APK packaging path."""
import sys, zipfile
from pathlib import Path
apk=Path(sys.argv[1]) if len(sys.argv)>1 else Path.home()/'.local/share/iomatex-dev/android-console/console-dev.apk'
with zipfile.ZipFile(apk) as archive:
for name in ('classes.dex','assets/console.js','assets/console.css',
'org/eclipse/paho/client/mqttv3/internal/nls/logcat.properties',
'org/eclipse/paho/client/mqttv3/internal/nls/messages.properties',
'META-INF/services/org.eclipse.paho.client.mqttv3.spi.NetworkModuleFactory'):
assert archive.read(name),name
providers=archive.read('META-INF/services/org.eclipse.paho.client.mqttv3.spi.NetworkModuleFactory')
assert b'TCPNetworkModuleFactory' in providers and b'SSLNetworkModuleFactory' in providers
print('PASS APK frontend, MQTT resource bundles and network ServiceLoader providers')

View File

@ -0,0 +1,44 @@
"""Packaging/lifecycle boundaries; live transport is validated on the Android bench."""
from pathlib import Path
import unittest
ROOT=Path(__file__).resolve().parents[2]
SRC=ROOT/'android_console/src/com/iomatex/console'
class EmbeddedContract(unittest.TestCase):
def test_registration_owned_by_client_uid(self):
source=(SRC/'RemoteAccess.java').read_text()
self.assertIn('context.getPackageName().equals(AndroidClient.PACKAGE)',source)
self.assertIn('context.getApplicationInfo().dataDir,relative',source)
self.assertIn('readClient(context,"no_backup/registration.ini")',source)
self.assertIn('if (!next.equals(registration)) { disconnect(); registration = next; }',source)
def test_server_trust_from_authenticated_enrollment(self):
source=(SRC/'RemoteAccess.java').read_text()
self.assertIn('enrollment.getJSONArray("ssh_host_keys")',source)
self.assertIn('candidate.setConfig("StrictHostKeyChecking", "yes")',source)
self.assertIn('connection.setInstanceFollowRedirects(false)',source)
self.assertNotIn('accept-new',source)
def test_boot_and_update_use_one_bootstrap(self):
source=(SRC/'BootReceiver.java').read_text()
self.assertIn('Intent.ACTION_MY_PACKAGE_REPLACED',source)
self.assertIn('Intent.ACTION_BOOT_COMPLETED',source)
self.assertIn('ConsoleBootstrap.start(c)',source)
bootstrap=(SRC/'ConsoleBootstrap.java').read_text()
self.assertIn('PackageManager.SIGNATURE_MATCH',bootstrap)
self.assertIn('contains("password")',bootstrap)
self.assertIn('file.getChannel().lock()',bootstrap)
def test_embedded_resources_are_namespaced(self):
source=(ROOT/'android_console/export-client-library.sh').read_text()
self.assertIn('android:process=":console"',source)
self.assertIn('assets/evaxconsole/',source)
self.assertIn('sha256',source)
def test_registration_waits_for_diagnostics_but_rejects_a_second_transfer(self):
source=(SRC/'AndroidClient.java').read_text()
self.assertIn('transferInProgress.compareAndSet(false,true)',source)
self.assertIn('operation.lockInterruptibly()',source)
self.assertIn('if(locked)operation.unlock();transferInProgress.set(false)',source)
self.assertNotIn('if(!operation.tryLock())throw new IllegalStateException("Client operation already in progress")',source)
def test_mqtt_timeout_reports_identity_recovery_without_enabling_register(self):
source=(SRC/'AndroidClient.java').read_text()
self.assertIn('error instanceof TimeoutException',source)
self.assertIn('saved registration and active MQTT identity may differ',source)
self.assertIn('.put("capability_reason",problem.isEmpty()',source)
if __name__=='__main__':unittest.main()

View File

@ -0,0 +1,34 @@
"""Ensure Android stays on the same renderer/paths and cannot enable Linux controls."""
from pathlib import Path
import unittest
ROOT = Path(__file__).resolve().parents[2]
class SharedConsoleContract(unittest.TestCase):
def test_shared_frontend_packaging(self):
build=(ROOT/'android_console/build.sh').read_text()
self.assertIn('stage_ui/console_core/frontend/{index.html,console.js,console.css,console.i18n.js}',build)
self.assertIn('(?:health|tscreen|security|network)',build)
self.assertFalse((ROOT/'android_console/frontend').exists())
def test_common_paths_and_owners(self):
server=(ROOT/'android_console/src/com/iomatex/console/ConsoleService.java').read_text()
debian=(ROOT/'stage_ui/console_core/backend/app.py').read_text()
for endpoint in ('/api/display','/api/itscreen/status','/api/itscreen/runtime','/api/itscreen/registration','/api/itscreen/register','/api/health/summary','/api/health/services'):
self.assertIn('"'+endpoint+'"',server)
self.assertIn('"'+endpoint+'"',debian)
ui=(ROOT/'stage_ui/console_core/frontend/console.js').read_text()
self.assertIn('card.capabilities.desktop_mode !== false',ui)
self.assertIn('card.capabilities.pulse_audio !== false',ui)
self.assertIn('registration.capabilities.can_register === false',ui)
self.assertIn('registration.status === "error"',ui)
self.assertIn('if (!itscreenCanRegister(registration))',ui)
self.assertIn('current.capability_reason || state.itscreen.error',ui)
self.assertIn('capabilities.logs === false ? "" : renderItscreenLogsCard()',ui)
def test_registration_stays_client_owned(self):
adapter=(ROOT/'android_console/src/com/iomatex/console/AndroidClient.java').read_text()
self.assertIn('"/$devices/settings/"',adapter)
self.assertIn('"action","register","host",target',adapter)
self.assertNotIn('FileOutputStream',adapter)
self.assertNotIn('"action","set"',adapter)
self.assertNotIn('"action","clear"',adapter)
self.assertIn('!local.password.equals(config.optString("password"))',adapter)
self.assertIn('options.setHttpsHostnameVerificationEnabled(true)',adapter)
if __name__=='__main__':unittest.main()

View File

@ -1,12 +0,0 @@
# Optional dashboard bridge offline editing snapshot — 2026-11-15
Backlog #1 remains WIP. An explicit OFFLINE_HMI_CONFIG enables the isolated SQLite
settings/outbox/sync module on a loopback-only bridge. Current default behavior is
retained without that setting. Hardware actions are not queued as offline edits.
Native MQTT prefix/identity are read from the registered configuration.
Verified: 15 Python store/runtime tests, including durable restart/retry, transaction
interruption, clock trust, grant scope, local-origin/operator guards and rejection of
hardware actions. See AITS docs/architecture/offline-irrigation-hmi.md for remaining
acceptance gates. This is source synchronization only: no stage version/feed update
or OS/bridge installation on physical devices.

View File

@ -0,0 +1,13 @@
# EVAx10 Android Console 0.2.0-dev
- Separate foreground Android agent with native Ed25519 reverse SSH connection,
existing platform enrollment and gateway diagnostics, independent of ADB.
- Canonical private client registration, disconnect on change/reset/read failure,
strict administrator-provisioned SSH host keys, on-device private keys.
- EVAx10 Android branding, shared Console components and original app icon.
- Default local Console password `iomatex`; user passwords survive updates.
- Lab verified: API authentication, server HTTP path without ADB forwarding,
automatic process recovery and tunnel reconnection, APK update restart,
responsive UI at four widths and registration parser tests.
- Development APK only for the rooted RK3566 bench; no production publication.
Full reboot, live server-switch and human platform-link issuance remain untested.

View File

@ -0,0 +1,36 @@
# EVAx10 Android Console 0.3.0-dev
Development APK, rooted RK3566 bench only. No public updater publication.
- Reuses the g-box Console frontend, Health, Display and It-Screen registration
renderers with the same `/api/health/*`, `/api/display` and `/api/itscreen/*`
contracts. Visible Android tab is EVAx10; no duplicated frontend.
- Capability flags suppress Debian desktop/kiosk, PulseAudio and eMMC-specific
information. Modbus, Cockpit, Z2M and g-box manuals are not Android navigation.
- DisplayManager supplies actual display identity, physical resolution, refresh
rate, rotation, power state and supported modes. This is display diagnostics,
not a live screen stream or remote touch-control implementation.
- Android health includes build/security patch, board, hardware, ABI, kernel,
memory, data partition capacity/free space, uptime, boot time and time zone.
Unavailable metrics remain unavailable rather than inferred healthy.
- Client status uses the existing authenticated DeviceSettingsMessenger MQTT
settings contract. A running package/maintenance service alone is not Active.
Local health handlers read a background snapshot without external DNS/network.
- Registration reads canonical RegistrationStore and confirms client state live.
Cached broker credentials can only be used when their username/password match
the current canonical registration; no legacy registration fallback.
- Register delegates to the client's existing Android transfer flow. The client
preserves its old registration until target confirmation; Console never writes
client registration files. First enrollment and reset remain local, matching
the existing Android client policy. An environment change can interrupt the
old Console URL; reopen through the new platform. New SSH hosts require trust.
- APK packages Paho Java resources and ServiceLoader providers alongside DEX;
dependency hash, signature and shared source contract checks cover packaging.
## Validation scope
Shared session, version-response-ordering and reverse-tunnel frontend regressions
pass. Android contract tests enforce shared owners and block parallel registration
writes. Device/API and browser validation is recorded in android_console/README.md.
Live migration to another registration server and a full OS reboot are not part
of this validation; the existing EVA registration is preserved.

View File

@ -0,0 +1,21 @@
# EVAx10 Android Console 0.4.0-dev
- Restore shared Security & Region and Network navigation; name the Android
client tab Registration so the entry point is explicit.
- Console password change verifies the current password, validates confirmation,
persists only the Console account and revokes other Console sessions. Does not
alter Android lock-screen or EVAx10 device registration credentials.
- Region uses the shared timezone API/UI with Android zone IDs and privileged
AlarmManager shell adapter, verifying the resulting OS property.
- Network uses ConnectivityManager / WifiManager, including addresses, gateway,
DNS, cached scan results and explicit Wi-Fi connection requests. Connecting can
interrupt remote access; acceptance is not reported as verified connectivity.
- Restore shared version controls with canonical Android release-feed checks.
APK installation remains owned by the native EVAx10 updater; Console APK has
no public update channel. Disabled actions explain those boundaries.
- Password and unchanged network/timezone submissions are disabled/guarded.
Linux-only password recovery instructions are excluded from Android.
Development only. No public artifacts or feeds are modified. Live Wi-Fi switching,
password replacement and a different time zone are not performed on the remote
bench during verification; negative validation and UI contracts are tested.

View File

@ -0,0 +1,15 @@
# EVAx10 Android Console 0.4.1-dev
- Populate the existing `/api/health/summary` temperatures array from readable
Linux thermal zones, the same OS source consumed by EVAx10 NativeSystemMetrics.
- Preserve sensor type names: soc-thermal is SoC, not an inferred CPU value;
gpu-thermal is the GPU sensor. Use the existing name/value_c/label UI contract.
- Convert millidegrees to Celsius, retaining valid zero; reject malformed,
non-finite and implausible readings. Unreadable values remain unavailable.
- Exclude vendor test and battery zones from this adapter. No fabricated zero,
root escalation or change to client/platform temperature telemetry.
- JVM fixtures cover identity, unit conversion, missing input, NaN, range, zero
and test-zone exclusion. Frontend markup/styles remain unchanged.
- Follow-up: name the shared client tab EVAx10 in static HTML and runtime
translation, consistently for Android and g-box.

View File

@ -0,0 +1,22 @@
# EVAx10 Android Console 0.4.2-dev
- Implement the shared authenticated POST /api/actions/reboot endpoint on the
rooted Android bench. Check privileged access before requesting reboot, delay
the command by three seconds to allow the HTTP response to reach the browser,
and retain command output in the private reboot.log. Success means requested;
unavailable privilege returns a visible error, not success.
- Sample aggregate CPU ticks and load averages every five seconds off HTTP
workers. Reuse cpu_usage_percent and load_average in the shared Console UI.
Do not double-count guest ticks; include idle/iowait as idle. First samples,
counter resets and failed/stale readings never become fabricated zero usage.
- Add CPU arithmetic fixtures and bench health assertions. CPU and reboot use
the existing root adapter; this does not grant these capabilities on stock,
unprivileged Android devices.
- Close the reverse SSH connection before the scheduled reboot to release its
server port. Explain remote forwarding conflicts while automatic retries run.
- Bench validation: Android 13 RK3566 accepted authenticated reboot, changed
kernel boot ID, completed boot and automatically started Console. DHCP changed
192.168.0.186 to 192.168.0.100. CPU/load summary passed after boot, and the
server reached authenticated Console through the restored native reverse.

View File

@ -0,0 +1,27 @@
# EVAx10 Android Console 0.5.0-dev
- Export the existing Android adapter and shared Console frontend as one AAR
library for the EVAx10 APK. Namespace frontend assets under evaxconsole;
preserve all shared HTTP and MQTT contracts. No second UI source tree.
- Start the embedded agent in the client UID, separate :console process on
Android 8/API 26 and newer. Reuse the bootstrap from client maintenance startup,
BOOT_COMPLETED and MY_PACKAGE_REPLACED. Android 6/7 client support is retained,
but this agent is not started on those versions.
- Read canonical registration/configuration in the owning UID, without root.
Root-only OS operations remain capability-dependent. Changes to registration
still disconnect the old SSH session before enrollment on the new server.
- Consume ssh_host_keys from authenticated HTTPS enrollment; keep strict SSH
verification. Missing trust fails closed on older servers. No TOFU or keyscan.
- Migrate the same-signed standalone diagnostic agent on rooted benches: retain
password/device key, disable the obsolete package, and serialize migration.
Established client-owned settings are never replaced on subsequent updates.
- Generate an AAR plus SHA-256/source-file manifest; the client build requires
and verifies that library. Agent updates now follow the client APK updater.
- This is a development integration, not a published Android client release.
Bench validation: embedded client APK installed, standalone agent migrated and
stopped, native reverse verified from the server, full reboot and automatic
restart verified, missing known_hosts automatically recreated from HTTPS,
password/device key retained, repeated APK replacement restarted Console without
manual service launch. Android 13 tested; cross-environment registration transfer
was not performed. Compatible receiver applied on EVA and DEV, not published.

View File

@ -1,6 +0,0 @@
# Console 3.1.29 — update domain migration
- Install shared Git delivery with git.iomatex.com as its canonical HTTPS host.
- Normalize legacy saved hosts in stage checks and package downloads; retain exact-host trust, TLS verification, pinned commits and checksums.
- Bootstrap defaults to git.iomatex.com; legacy installer URLs and virtual APT paths remain accepted.
- Identify bootstrap and package requests as IomatexOS-Updater/1.0; avoid the new proxy rejecting the default Python user agent with Cloudflare 1010.

View File

@ -1,10 +0,0 @@
# Console 3.1.30 — complete Git update domain audit
- All ten Console stages use the shared stage_versions/git_delivery owner for
catalog checks, individual updates, update-all, snapshots and package delivery.
- Bootstrap accepts legacy saved repository URLs but always connects to
git.iomatex.com, including network retries; no fallback to git.it-screen.com.
- Preserve TLS verification, exact-host validation, commit pinning and checksums.
- New snapshots, credentials, stage config and APT sources store the new host.
Legacy virtual APT addresses remain readable and resolve through the new host.
- Client binaries remain 5.1.44; this release updates Console/delivery only.

View File

@ -1,10 +0,0 @@
# Console 3.1.31 — persist migration from old installed bootstrap
- Bench upgrade through the pre-migration Console revealed that the old running
bootstrap writes its old host into snapshot metadata and credentials before
invoking the new activator. Requests already normalize it, but stored values
must also migrate.
- The new activator now persists the canonical host in both source metadata and
credentials as well as the derived APT and stage-update configuration.
- Preserve credentials and their 0600 permissions; never expose them in logs.
- Includes the complete Console 3.1.30 module audit and new-domain-only retries.

View File

@ -1,7 +0,0 @@
# Console 3.1.32 — client update control
- It-Screen shows installed and available native client versions, update availability, progress and errors.
- Check and update delegates to the existing Debian updater socket; no duplicate download/install implementation.
- Opening the tab performs a check-only request; it never installs or changes automatic updates. Status polling updates only the version panel, preserving registration form edits.
- Authenticated API allowlists check-only/update; GET reads local updater state without external network requests.
- Requires stage_itscreen 1.0.40 for the snapshot/check-only protocol extension. Older services report an explicit error.

View File

@ -1,6 +0,0 @@
# Console 3.1.33 — content-versioned browser resources
- The existing static file response owner fingerprints Console JS, translations and CSS in served HTML. Changing a file changes its URL even if the release label was reused.
- Retain no-store headers and existing asset endpoints. No UI controls or installation logic are duplicated.
- This hardens browser refresh after deployment; it does not prove the cause of the reported missing update button in an existing browser session.
- Tests verify stable URLs for unchanged content and invalidation for a same-version JavaScript change.

View File

@ -1,13 +0,0 @@
# Console 3.1.34 — client update in the IT-Screen profile card
- Show the shared Debian client update state and action directly in the
IT-Screen service profile card on Health: installed version, available
version, availability/progress/error status, and Check and update client.
- Use the same update controller and authenticated API as the dedicated
It-Screen tab. Health performs a check-only request and local status polling;
it does not change the automatic-update preference.
- Rename the separate stage 1.0.40 presentation to Client update system module
and explain that it is the technical updater module, not the application
version.
- Keep the generic stage renderer as the single owner; the IT-Screen card only
supplies contextual labels. No parallel installation path is introduced.

View File

@ -1,12 +0,0 @@
# Console 3.1.35 — wide-screen service layout
- Increase the Console shell ceiling from 1180 px to 1600 px so wide screens
use their available horizontal space instead of leaving large empty margins.
- Give the Health service list one explicit responsive owner: three wide
columns on desktop, two columns at 1100 px and below, and one column at
720 px and below.
- Preserve all existing service-card content, actions and status semantics.
Other Console card families keep their current layout contracts.
- Browser verification at 360, 768, 1024, 1440 and 1920 px confirmed 1/2/2/3/3
columns, no horizontal overflow, a 1600 px shell and approximately 511 px
service cards at 1920 px.

View File

@ -1,14 +0,0 @@
# Console 3.1.36 — compact Health service profiles
- Recompose standard Health service cards around one shared compact summary
for ID, state and status, with details, tests, flags, actions and release
controls arranged in responsive information columns.
- Give the IT-Screen profile two desktop grid columns and three internal zones
for registration, client update and system-module information. The existing
update actions and status semantics remain owned by the shared release UI.
- Keep specialized Display, access-point and reverse-tunnel layouts intact.
Standard cards collapse to two and then one internal column as space narrows.
- Browser verification at 360, 768, 1024, 1440 and 1920 px confirmed the
1/2/2/3/3 outer grid, no horizontal overflow and readable responsive
composition. At 1920 px the IT-Screen card height decreased from 921 px to
482 px, a reduction of 439 px (47.7%).

View File

@ -1,16 +0,0 @@
# Console 3.1.37 — faster navigation and wide technical values
- Let service details with long values span the complete card width. USB device
paths and FFmpeg build strings remain readable without narrow word columns.
- Reuse one provider snapshot across Health, Network and G-Box instead of
executing the complete system-service diagnostics separately for every tab.
- Keep the shared snapshot for 15 seconds during normal navigation. Explicit
Refresh bypasses the snapshot, so an operator can still request current data.
- Mark SHA-fingerprinted CSS and JavaScript as immutable browser resources while
keeping the HTML entry point uncached. A changed asset receives a new URL.
- Activate the selected tab immediately before its data request completes, so
navigation always gives visible feedback while live diagnostics are loading.
- The pre-change browser baseline on the local Edge was 1.7 seconds for initial
Health, 6.1 seconds for Network, 1.1 seconds for Modbus and 2.6 seconds for
G-Box. These timings identified repeated provider diagnostics as the main
avoidable delay.

View File

@ -1,11 +0,0 @@
# Console 3.1.38 — parallel service diagnostics
- Execute independent provider modules concurrently with a maximum of four
workers while preserving their canonical card order.
- Execute the independent core service checks for It-Screen, MQTT, Zigbee,
tunnels, FFmpeg, display and managed system services through the same bounded
worker contract.
- Keep the shared snapshot, explicit Refresh bypass and wide technical-value
layout introduced in Console 3.1.37.
- Contract tests verify that provider and core-card checks actually overlap and
that the resulting cards remain in the established product order.

View File

@ -1,6 +0,0 @@
# Console 3.1.39 — camera stream startup diagnostics
- Preserve the sanitized error returned by the IP Camera Streaming service instead of replacing every startup failure with a generic message.
- Keep the existing local control socket and camera-preview API contracts unchanged.
Validation: contract coverage verifies that safe service errors reach the camera gateway response.

View File

@ -1,6 +0,0 @@
# Console 3.1.40 — synchronized camera diagnostics release
- Synchronize the embedded backend version, frontend version, static asset cache keys, stage manifest and release catalog.
- Preserve the sanitized FFmpeg startup error added with Console 3.1.39.
Validation: the complete Console test suite passes and the installed runtime identity reports the same version as the stage updater.

View File

@ -1,6 +0,0 @@
# Console 3.1.41 — camera stream cleanup
- Add the authenticated camera-stream stop operation used by AITS when CDN readiness cannot be confirmed.
- Retain synchronized runtime, frontend, asset and stage version metadata.
Validation: the complete Console suite and camera streaming contract tests pass.

View File

@ -1,34 +0,0 @@
# Debian Console update transport audit — 2026-10-29
Published target: Console 3.1.30, client 5.1.44 unchanged.
| Entry | Shared owner | Network destination |
| --- | --- | --- |
| Console version check `/api/stages/check` | stage_versions.refresh → git_delivery.open_git | HTTPS git.iomatex.com |
| Single stage `/api/stages/install` | stage_versions.install → git_delivery.bootstrap | HTTPS git.iomatex.com |
| Update all `/api/stages/install-all` | same owner, ordered stage queue | HTTPS git.iomatex.com |
| Initial installer, including old `--git-url` input | bootstrap then shared delivery owner | HTTPS git.iomatex.com, including retries |
| APT packages and native runtime dependencies | custom iomatex APT method → download_object → open_git | HTTPS git.iomatex.com |
| Client ELF and Zigbee2MQTT archive | git_delivery fetch → download_object | HTTPS git.iomatex.com |
| Snapshot/credential/stage/source persistence | bootstrap/activate/configure | canonical new host |
Audited stages: environment, Wi-Fi/AP, MQTT, Zigbee2MQTT, Console,
Avahi/mDNS, Cockpit, display/client, IP streaming, reverse tunnels.
They use offline/require-local.sh (Zigbee2MQTT through its shared library).
The optional dashboard bridge installer uses the same delivery owner.
The legacy full-clone functions in local_installer.sh are unreachable: its Git
entry refuses to run and directs the user to the lightweight bootstrap.
Old host literals remain only as accepted migration inputs and virtual APT
identifiers, test fixtures, or historical documentation. They are not network
fallback destinations. Registration servers and local service health URLs are
separate contracts and are unchanged. Build-time Debian dependency collection
in offline/build.sh is not an Edge updater.
Security remains: exact allowlisted hosts, TLS verification, redirect refusal,
commit-pinned contents and package hashes, authenticated Console actions,
explicit installation confirmation and shared installation lock.
Regression coverage: bootstrap retry with either input alias; stage catalog
refresh with legacy/new/missing host; legacy snapshot persistence; package
transport; individual/bulk Console API permission and confirmation tests.

View File

@ -1,9 +0,0 @@
# IP Camera Streaming 1.0.10
Release date: 2026-11-08.
- Retry a failed forwarding FFmpeg process up to two times while its requested TTL remains active.
- Preserve the last sanitized FFmpeg failure in local status and systemd logs for field diagnostics.
- Report retry count without exposing RTSP credentials or SRT publication tokens.
Validation: reproduced the intermittent SRT `Input/output error` on `g-box-c453df5f`; unit coverage verifies bounded restart, expiry and secret redaction.

View File

@ -1,9 +0,0 @@
# IP Camera Streaming 1.0.9
Release date: 2026-11-08.
- Verify that FFmpeg remains alive during the initial stream startup window before reporting success.
- Capture and sanitize early FFmpeg failures so camera credentials and CDN publication tokens never appear in Console responses.
- Close diagnostic handles when a stream stops or is reaped, while retaining the existing forwarding and preview contracts.
Validation: unit coverage verifies early process failure, secret redaction, lifecycle cleanup and the existing H.264 forwarding profiles.

View File

@ -1,7 +0,0 @@
# stage_itscreen 1.0.34 — EVAx10 5.1.44
- Publish Debian ARM64 client from the common release source in release-provenance.json.
- Shared Git delivery normalizes saved git.it-screen.com sources to git.iomatex.com before HTTPS requests.
- Existing virtual APT addresses remain readable; new APT sources use git.iomatex.com.
- Registration, device identity, media and schedules are preserved.
- If the old domain is already blocked, use the new-domain bootstrap once to install this delivery owner.

View File

@ -1,6 +0,0 @@
# stage_itscreen 1.0.35 — EVAx10 5.1.51
- Publish the synchronized Debian ARM64 Edge Client 5.1.51 build.
- Apply live window geometry smoothly and avoid a duplicate redraw after the final coordinate update.
- Keep deterministic layout selection, ONVIF verification and existing device registration data.
- Preserve the current OS, media cache, schedules and connection settings during the stage update.

View File

@ -1,7 +0,0 @@
# stage_itscreen 1.0.36 — EVAx10 5.1.55
- Publish Debian ARM64 Edge Client 5.1.55 through the Console update channel.
- Report the complete previous, current and next-hour generated playback timelines to the server.
- Keep device registration, media cache, schedules, connection settings and the existing operating system during the stage update.
- Source commit: `47147d767678bcbb19dc48b578b51ff65a2f2278`.
- Binary SHA-256: `5e9ab66b072aaa64a1b033992bf6bdc77a1a83c4a35342cbde58f4581753505d`.

View File

@ -1,9 +0,0 @@
# stage_itscreen 1.0.37 — EVAx10 5.1.55 revision 2
- Correct the 1.0.36 publication: its binary actually reported 5.1.54 despite
the 5.1.55 manifest. Replace it with a clean ARM64 build reporting 5.1.55 / 5010055.
- Advance the stage version so devices with 1.0.36 are offered the correction.
- Preserve registration, media and settings; retain the existing stage update contract.
- Exact binary digest and source commit are in stage_itscreen/release-provenance.json.
- Before replacing the installed binary, execute `--version` and require both version
and native build number to match the release provenance; reject mislabeled files.

View File

@ -1,13 +0,0 @@
# stage_itscreen 1.0.38 — Debian client automatic updates
- Install iomatex-client-updater.service; reuse the existing itsupdater Unix
socket and active_update flag sent by the device is_check_update setting.
- Check the public DOWNLOAD_IOMATEX_APP Debian feed on git.iomatex.com every
15 minutes when enabled. Persist the flag; disabled means no automatic installs.
- Manual check/install reuse the same owner. Validate host, platform, ELF ABI,
size, SHA-256 and embedded version before stopping the client.
- Serialize with Console installation, atomically replace the executable, and
restore the previous binary after failed startup or interrupted installation.
- Keep registration, settings and media. Preserve a newer Download client when
installing an older OS stage. System packages remain managed by Console.
- Client binary remains verified 5.1.55 / 5010055 revision 2.

View File

@ -1,13 +0,0 @@
# stage_itscreen 1.0.39 — First installation from Download
- First provisioning resolves the same public Debian Download manifest as the
automatic updater. OS no longer selects stage_itscreen/itscreen for installation.
- Reuse manifest validation, download, ELF/size/SHA-256/embedded-version checks
and atomic replacement from the existing updater owner.
- Initial provisioning installs a client even when automatic updates are off;
preserve that flag, registration, settings and a newer installed client.
- Download failure aborts provisioning without falling back to an old bundled
executable. Archived files remain available only for legacy URL compatibility.
- Use isolated candidate filenames to avoid collisions with a concurrently
downloading updater; share the inherited Console installer lock.
- Dependencies, Console and service startup remain owned by the OS stages.

View File

@ -1,6 +0,0 @@
# It-Screen stage 1.0.40 — Console update adapter
- Extend the existing updater socket with snapshot and check_only commands for Console.
- Check-only never installs, including when automatic updates are enabled; manual update keeps the existing verified download, lock, rollback and startup checks.
- Expose queued/running state and errors without changing client version 5.1.55 or update preferences.
- Validation: 19 updater tests, frontend state tests and local ARM64 Console API checks.

View File

@ -4,7 +4,7 @@ set -Eeuo pipefail
[[ ${EUID:-$(id -u)} -eq 0 ]] || exec sudo -E bash "$0" "$@" [[ ${EUID:-$(id -u)} -eq 0 ]] || exec sudo -E bash "$0" "$@"
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
export DEBIAN_FRONTEND=noninteractive export DEBIAN_FRONTEND=noninteractive
GIT_URL=${IOMATEX_GIT_URL:-https://git.iomatex.com/An-J/Iomatex_OS.git} GIT_URL=${IOMATEX_GIT_URL:-https://git.it-screen.com/An-J/Iomatex_OS.git}
GIT_BRANCH=${IOMATEX_GIT_BRANCH:-ci-cd} GIT_BRANCH=${IOMATEX_GIT_BRANCH:-ci-cd}
CHECKOUT_DIR=${IOMATEX_GIT_DIR:-/userdata/Iomatex_OS} CHECKOUT_DIR=${IOMATEX_GIT_DIR:-/userdata/Iomatex_OS}
STAGES=stage_env,stage_wifi,stage_mqtt,stage_ui,stage_avahi,stage_cockpit,stage_itscreen,stage_reverse_tunnels STAGES=stage_env,stage_wifi,stage_mqtt,stage_ui,stage_avahi,stage_cockpit,stage_itscreen,stage_reverse_tunnels
@ -56,13 +56,11 @@ repo = parsed.path.strip('/').removesuffix('.git')
class NoRedirect(urllib.request.HTTPRedirectHandler): class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, *args, **kwargs): def redirect_request(self, *args, **kwargs):
raise RuntimeError('Git download redirect refused') raise RuntimeError('Git download redirect refused')
headers = {'User-Agent': 'IomatexOS-Updater/1.0', 'Authorization': 'Basic ' + base64.b64encode((os.environ['IOMATEX_GIT_USERNAME'] + ':' + os.environ['IOMATEX_GIT_PASSWORD']).encode()).decode()} headers = {'Authorization': 'Basic ' + base64.b64encode((os.environ['IOMATEX_GIT_USERNAME'] + ':' + os.environ['IOMATEX_GIT_PASSWORD']).encode()).decode()}
opener = urllib.request.build_opener(NoRedirect) opener = urllib.request.build_opener(NoRedirect)
# Accept old saved URLs as input only; never make a request to the blocked host. hosts = [parsed.netloc] + [h for h in ('git.it-screen.com', 'git.iomatex.com') if h != parsed.netloc]
host = 'git.iomatex.com'
attempts = 2
commit = None commit = None
for index in range(attempts): for index, host in enumerate(hosts):
base = 'https://' + host + '/api/v1/repos/' + repo + '/' base = 'https://' + host + '/api/v1/repos/' + repo + '/'
try: try:
if commit is None: if commit is None:
@ -82,9 +80,9 @@ for index in range(attempts):
raise SystemExit('Git TLS verification/connection failed. No domain switch; check certificates and system time.') from None raise SystemExit('Git TLS verification/connection failed. No domain switch; check certificates and system time.') from None
if not isinstance(reason, OSError): if not isinstance(reason, OSError):
raise SystemExit('Git request failed; no domain switch.') from None raise SystemExit('Git request failed; no domain switch.') from None
if index + 1 == attempts: if index + 1 == len(hosts):
raise SystemExit('git.iomatex.com is unreachable. Check DNS and Internet connectivity; installation has not started.') from None raise SystemExit('Both Git domains are unreachable. Check DNS and Internet connectivity; installation has not started.') from None
print('Git network/DNS failure; retrying ' + host, flush=True) print('Git network/DNS failure on ' + host + '; trying ' + hosts[index + 1], flush=True)
PYTHON PYTHON
GIT_URL=$(cat "$work/git_delivery.py.source") GIT_URL=$(cat "$work/git_delivery.py.source")

View File

@ -34,7 +34,7 @@ POST_REBOOT_UNIT_PATH="/etc/systemd/system/${POST_REBOOT_UNIT}"
POST_REBOOT_AUTOSTART="iomatex-local-installer-post-reboot.desktop" POST_REBOOT_AUTOSTART="iomatex-local-installer-post-reboot.desktop"
POST_REBOOT_AUTOSTART_PATH="/etc/xdg/autostart/${POST_REBOOT_AUTOSTART}" POST_REBOOT_AUTOSTART_PATH="/etc/xdg/autostart/${POST_REBOOT_AUTOSTART}"
IOMATEX_GIT_URL="${IOMATEX_GIT_URL:-https://git.iomatex.com/An-J/Iomatex_OS.git}" IOMATEX_GIT_URL="${IOMATEX_GIT_URL:-https://git.it-screen.com/An-J/Iomatex_OS.git}"
IOMATEX_GIT_BRANCH="${IOMATEX_GIT_BRANCH:-ci-cd}" IOMATEX_GIT_BRANCH="${IOMATEX_GIT_BRANCH:-ci-cd}"
IOMATEX_GIT_DIR="${IOMATEX_GIT_DIR:-/opt/iomatex/Iomatex_OS}" IOMATEX_GIT_DIR="${IOMATEX_GIT_DIR:-/opt/iomatex/Iomatex_OS}"
IOMATEX_GIT_TOKEN="${IOMATEX_GIT_TOKEN:-}" IOMATEX_GIT_TOKEN="${IOMATEX_GIT_TOKEN:-}"
@ -206,7 +206,7 @@ Behavior:
- stops on first stage failure - stops on first stage failure
Git defaults: Git defaults:
- IOMATEX_GIT_URL=https://git.iomatex.com/An-J/Iomatex_OS.git - IOMATEX_GIT_URL=https://git.it-screen.com/An-J/Iomatex_OS.git
- IOMATEX_GIT_BRANCH=ci-cd - IOMATEX_GIT_BRANCH=ci-cd
- IOMATEX_GIT_DIR=/opt/iomatex/Iomatex_OS - IOMATEX_GIT_DIR=/opt/iomatex/Iomatex_OS
EOF EOF
@ -1427,7 +1427,7 @@ else
SOURCE_COMMIT="" SOURCE_COMMIT=""
else else
if [[ "$USE_GIT_SOURCE" -eq 1 ]]; then if [[ "$USE_GIT_SOURCE" -eq 1 ]]; then
[[ ( "$GIT_URL" == https://git.iomatex.com/* || "$GIT_URL" == https://git.it-screen.com/* ) && "$GIT_URL" != *'@'* && "$GIT_URL" != *'?'* && "$GIT_URL" != *'#'* ]] || die "Only our Git is allowed" [[ "$GIT_URL" == https://git.it-screen.com/* ]] || die "Only our Git is allowed"
die "Use install_iomatex_edge.sh to update the lightweight snapshot; full Git clones on Edge are disabled" die "Use install_iomatex_edge.sh to update the lightweight snapshot; full Git clones on Edge are disabled"
else else
PROJECT_DIR="$SCRIPT_DIR" PROJECT_DIR="$SCRIPT_DIR"

View File

@ -26,14 +26,13 @@ import urllib.error
import urllib.parse import urllib.parse
import urllib.request import urllib.request
HOST = 'git.iomatex.com' HOST = 'git.it-screen.com'
ALLOWED_HOSTS = (HOST, 'git.it-screen.com') ALLOWED_HOSTS = (HOST, 'git.iomatex.com')
def git_host(value=HOST): def git_host(value=HOST):
if value not in ALLOWED_HOSTS: if value not in ALLOWED_HOSTS:
raise ValueError('Unsupported Git host') raise ValueError('Unsupported Git host')
# Normalize legacy saved credentials/snapshots before any network request. return value
return HOST
STATE = Path('/var/lib/iomatex/packages') STATE = Path('/var/lib/iomatex/packages')
AUTH = Path('/etc/iomatex/git-credentials.json') AUTH = Path('/etc/iomatex/git-credentials.json')
@ -68,7 +67,7 @@ def auth_from_env():
def open_git(repo, endpoint, auth, timeout=120): def open_git(repo, endpoint, auth, timeout=120):
url = 'https://' + git_host(auth.get('host', HOST)) + '/api/v1/repos/' + repo + '/' + endpoint url = 'https://' + git_host(auth.get('host', HOST)) + '/api/v1/repos/' + repo + '/' + endpoint
token = base64.b64encode((auth['username'] + ':' + auth['password']).encode()).decode() token = base64.b64encode((auth['username'] + ':' + auth['password']).encode()).decode()
req = urllib.request.Request(url, headers={'Authorization': 'Basic ' + token, 'User-Agent': 'IomatexOS-Updater/1.0'}) req = urllib.request.Request(url, headers={'Authorization': 'Basic ' + token})
return urllib.request.build_opener(NoRedirect).open(req, timeout=timeout) return urllib.request.build_opener(NoRedirect).open(req, timeout=timeout)
def raw_endpoint(path, commit): def raw_endpoint(path, commit):
@ -283,44 +282,6 @@ def recovery_gate(repo, branch, commit, auth, files, stages, job=None):
raise RecoveryPending('Offline userdata recovery queued; update is pending, not complete') raise RecoveryPending('Offline userdata recovery queued; update is pending, not complete')
def repository_tree(repo, commit, auth):
"""Read every Gitea tree page from one immutable commit before changing files."""
endpoint = 'git/trees/' + commit + '?recursive=true'
with open_git(repo, endpoint, auth) as response:
first = json.load(response)
entries = first.get('tree')
if not isinstance(entries, list):
raise ValueError('Invalid Git repository tree')
if not first.get('truncated'):
return entries
total = first.get('total_count')
if type(total) is not int or not len(entries) or not len(entries) <= total <= 100000:
raise ValueError('Git returned an incomplete repository tree')
entries = list(entries)
seen = {item['path'] for item in entries}
if len(seen) != len(entries):
raise ValueError('Duplicate Git tree members')
page = 1
while len(entries) < total:
page += 1
if page > 1000:
raise ValueError('Git tree pagination limit exceeded')
with open_git(repo, endpoint + '&page=' + str(page), auth) as response:
part = json.load(response)
chunk = part.get('tree')
if (not isinstance(chunk, list) or not chunk or part.get('total_count') != total
or part.get('sha') != first.get('sha') or part.get('page', page) != page):
raise ValueError('Git returned inconsistent repository tree pages')
for item in chunk:
if item['path'] in seen:
raise ValueError('Duplicate Git tree members')
seen.add(item['path'])
entries.extend(chunk)
if len(entries) > total:
raise ValueError('Git tree exceeds declared size')
return entries
def bootstrap(url, branch, checkout, commit=None, recovery_stages=None, recovery_job=None, preserve_local_changes=False): def bootstrap(url, branch, checkout, commit=None, recovery_stages=None, recovery_job=None, preserve_local_changes=False):
platform_check() platform_check()
repo = repo_name(url) repo = repo_name(url)
@ -334,9 +295,12 @@ def bootstrap(url, branch, checkout, commit=None, recovery_stages=None, recovery
commit = json.load(r)['commit']['id'] commit = json.load(r)['commit']['id']
if not re.fullmatch('[a-f0-9]{40}', commit): if not re.fullmatch('[a-f0-9]{40}', commit):
raise ValueError('Invalid pinned commit') raise ValueError('Invalid pinned commit')
tree = repository_tree(repo, commit, auth) with open_git(repo, 'git/trees/' + commit + '?recursive=true', auth) as r:
tree = json.load(r)
if tree.get('truncated'):
raise ValueError('Git returned an incomplete repository tree')
files = [] files = []
for item in tree: for item in tree['tree']:
path = safe_path(item['path']) path = safe_path(item['path'])
if item['type'] == 'tree' or is_payload(path): if item['type'] == 'tree' or is_payload(path):
continue continue
@ -442,14 +406,8 @@ def activate(root):
source = json.loads((root / '.iomatex-source.json').read_text()) source = json.loads((root / '.iomatex-source.json').read_text())
repo_name('https://' + git_host(source.get('host', HOST)) + '/' + source['repo']) repo_name('https://' + git_host(source.get('host', HOST)) + '/' + source['repo'])
raw_endpoint('probe', source['commit']) raw_endpoint('probe', source['commit'])
auth = auth_from_env() # fail before modifying APT if reboot credentials are missing auth_from_env() # fail before modifying APT if reboot credentials are missing
auth['host'] = git_host(auth.get('host', HOST))
text, objects = catalog(root) text, objects = catalog(root)
# An older bootstrap invokes this NEW activator but may have persisted its old host.
# Migrate both durable inputs here, not only the derived APT/stage configuration.
source['host'] = HOST
write_json(root / '.iomatex-source.json', source)
write_json(AUTH, auth, 0o600)
STATE.mkdir(parents=True, exist_ok=True) STATE.mkdir(parents=True, exist_ok=True)
(STATE / 'Packages').write_text(text) (STATE / 'Packages').write_text(text)
(STATE / 'Packages.gz').write_bytes(gzip.compress(text.encode(), mtime=0)) (STATE / 'Packages.gz').write_bytes(gzip.compress(text.encode(), mtime=0))
@ -466,7 +424,7 @@ def activate(root):
CACHE.mkdir(parents=True, exist_ok=True) CACHE.mkdir(parents=True, exist_ok=True)
(CACHE / 'partial').mkdir(exist_ok=True) (CACHE / 'partial').mkdir(exist_ok=True)
apt = Path('/etc/apt') apt = Path('/etc/apt')
(apt / 'iomatex-offline.list').write_text('deb [trusted=yes] iomatex://git.iomatex.com/ ./\n') (apt / 'iomatex-offline.list').write_text('deb [trusted=yes] iomatex://git.it-screen.com/ ./\n')
(apt / 'apt.conf.d/99iomatex-offline').write_text( (apt / 'apt.conf.d/99iomatex-offline').write_text(
'Dir::Etc::sourcelist "/etc/apt/iomatex-offline.list";\n' 'Dir::Etc::sourcelist "/etc/apt/iomatex-offline.list";\n'
'Dir::Etc::sourceparts "-";\n' 'Dir::Etc::sourceparts "-";\n'
@ -517,7 +475,7 @@ def message(code, fields):
def apt_key(uri, objects): def apt_key(uri, objects):
u = urllib.parse.urlparse(uri) u = urllib.parse.urlparse(uri)
if u.scheme != 'iomatex' or u.netloc not in ALLOWED_HOSTS or u.query or u.fragment: if u.scheme != 'iomatex' or u.netloc != HOST or u.query or u.fragment:
raise ValueError('Unsupported APT source') raise ValueError('Unsupported APT source')
# APT's method protocol may already decode the URI displayed by apt-get. # APT's method protocol may already decode the URI displayed by apt-get.
# Preserve literal %3a in Git filenames; never decode it twice into an epoch colon. # Preserve literal %3a in Git filenames; never decode it twice into an epoch colon.

View File

@ -16,7 +16,6 @@ lxterminal openbox wmctrl xdotool libqt5serialbus5-bin qml-module-qtmultimedia
qml-module-qtpositioning qml-module-qtquick-virtualkeyboard qtvirtualkeyboard-plugin qml-module-qtpositioning qml-module-qtquick-virtualkeyboard qtvirtualkeyboard-plugin
qml-module-qtwebview qml-module-qt-labs-settings qml-module-qtquick-xmllistmodel qml-module-qtwebview qml-module-qt-labs-settings qml-module-qtquick-xmllistmodel
qml-module-qtquick-controls2 qml-module-qt-websockets qml-module-qt-labs-platform qml-module-qtquick-controls2 qml-module-qt-websockets qml-module-qt-labs-platform
qml-module-qtquick-window2 qml-module-qtquick-layouts qml-module-qtquick-controls
# Camera streaming and snapshots (CLI, in addition to multimedia libraries). # Camera streaming and snapshots (CLI, in addition to multimedia libraries).
ffmpeg ffmpeg
# Keep installed OpenCV/GStreamer development chains compatible during FFmpeg upgrades. # Keep installed OpenCV/GStreamer development chains compatible during FFmpeg upgrades.

View File

@ -116,14 +116,6 @@ def refresh():
error = 'The stage release catalog has not been published to Git yet.' error = 'The stage release catalog has not been published to Git yet.'
elif exc.code in (401, 403): elif exc.code in (401, 403):
error = 'Git access was denied. Check the Edge Git credentials.' error = 'Git access was denied. Check the Edge Git credentials.'
# Cloudflare 1010 is a rejected HTTP client signature, not failed Git auth.
# Read only a bounded diagnostic marker; never expose the response body.
try:
blocked_client = exc.code == 403 and b'error code: 1010' in (exc.read(4096) or b'').lower()
except (OSError, AttributeError, TypeError):
blocked_client = False
if blocked_client:
error = 'Git network protection blocked this updater (HTTP 403, Cloudflare 1010). Update or restart Edge Console; check server access rules.'
# Do not expose credentials, HTTP bodies or private paths in the API. # Do not expose credentials, HTTP bodies or private paths in the API.
delivery.write_json(STATE / 'available.json', { delivery.write_json(STATE / 'available.json', {
**previous, 'attempt_at': int(time.time()), 'error': error, **previous, 'attempt_at': int(time.time()), 'error': error,

View File

@ -22,26 +22,23 @@ class BootstrapFallbackTest(unittest.TestCase):
opener.open.side_effect = responses opener.open.side_effect = responses
with patch('urllib.request.build_opener', return_value=opener), patch.dict(os.environ, {'IOMATEX_GIT_USERNAME':'user','IOMATEX_GIT_PASSWORD':'secret'}), patch.object(sys, 'argv', ['-', 'https://'+host+'/An-J/Iomatex_OS.git', 'ci-cd', str(destination)]): with patch('urllib.request.build_opener', return_value=opener), patch.dict(os.environ, {'IOMATEX_GIT_USERNAME':'user','IOMATEX_GIT_PASSWORD':'secret'}), patch.object(sys, 'argv', ['-', 'https://'+host+'/An-J/Iomatex_OS.git', 'ci-cd', str(destination)]):
exec(compile(SOURCE, 'bootstrap', 'exec'), {}) exec(compile(SOURCE, 'bootstrap', 'exec'), {})
for call in opener.open.call_args_list:
self.assertTrue(call.args[0].full_url.startswith('https://git.iomatex.com/'))
return destination, opener return destination, opener
def test_dns_retry_stays_on_canonical_host_and_persists_source(self): def test_dns_failure_selects_alternative_and_persists_source(self):
dest, opener = self.run_bootstrap([URLError(socket.gaierror(-3, 'DNS failure')), io.BytesIO(BRANCH), io.BytesIO(b'loader')]) dest, opener = self.run_bootstrap([URLError(socket.gaierror(-3, 'DNS failure')), io.BytesIO(BRANCH), io.BytesIO(b'loader')])
self.assertEqual(b'loader', dest.read_bytes()) self.assertEqual(b'loader', dest.read_bytes())
self.assertEqual('https://git.iomatex.com/An-J/Iomatex_OS.git', Path(str(dest)+'.source').read_text()) self.assertEqual('https://git.iomatex.com/An-J/Iomatex_OS.git', Path(str(dest)+'.source').read_text())
self.assertEqual(3, opener.open.call_count) self.assertEqual(3, opener.open.call_count)
self.assertIn('git.iomatex.com', opener.open.call_args.args[0].full_url) self.assertIn('git.iomatex.com', opener.open.call_args.args[0].full_url)
def test_payload_timeout_keeps_same_commit_and_host(self): def test_payload_timeout_keeps_same_commit_on_alternate(self):
_, opener = self.run_bootstrap([io.BytesIO(BRANCH), socket.timeout(), io.BytesIO(b'loader')]) _, opener = self.run_bootstrap([io.BytesIO(BRANCH), socket.timeout(), io.BytesIO(b'loader')])
self.assertIn('git.iomatex.com', opener.open.call_args.args[0].full_url) self.assertIn('git.iomatex.com', opener.open.call_args.args[0].full_url)
self.assertTrue(opener.open.call_args.args[0].full_url.endswith('a'*40)) self.assertTrue(opener.open.call_args.args[0].full_url.endswith('a'*40))
def test_canonical_host_is_used_directly(self): def test_explicit_alternate_is_tried_first(self):
_, opener = self.run_bootstrap([io.BytesIO(BRANCH), io.BytesIO(b'loader')], 'git.iomatex.com') _, opener = self.run_bootstrap([io.BytesIO(BRANCH), io.BytesIO(b'loader')], 'git.iomatex.com')
self.assertIn('git.iomatex.com', opener.open.call_args_list[0].args[0].full_url) self.assertIn('git.iomatex.com', opener.open.call_args_list[0].args[0].full_url)
self.assertEqual('IomatexOS-Updater/1.0', opener.open.call_args_list[0].args[0].get_header('User-agent'))
def test_auth_and_tls_fail_without_switch(self): def test_auth_and_tls_fail_without_switch(self):
for error in [HTTPError('url', 401, 'Unauthorized', {}, None), URLError(ssl.SSLCertVerificationError('invalid certificate'))]: for error in [HTTPError('url', 401, 'Unauthorized', {}, None), URLError(ssl.SSLCertVerificationError('invalid certificate'))]:
@ -49,12 +46,6 @@ class BootstrapFallbackTest(unittest.TestCase):
with self.assertRaises(SystemExit): with self.assertRaises(SystemExit):
self.run_bootstrap([error, AssertionError('Must not switch')]) self.run_bootstrap([error, AssertionError('Must not switch')])
def test_canonical_host_unreachable_reports_failure(self): def test_both_domains_unreachable_reports_failure(self):
with self.assertRaisesRegex(SystemExit, 'git.iomatex.com is unreachable'): with self.assertRaisesRegex(SystemExit, 'Both Git domains are unreachable'):
self.run_bootstrap([URLError(socket.gaierror()), socket.timeout()]) self.run_bootstrap([URLError(socket.gaierror()), socket.timeout()])
def test_both_input_aliases_only_use_new_host(self):
for host in ('git.it-screen.com', 'git.iomatex.com'):
with self.subTest(host=host):
_, opener = self.run_bootstrap([io.BytesIO(BRANCH), io.BytesIO(b'loader')], host)
self.assertEqual(2, opener.open.call_count)

View File

@ -11,66 +11,25 @@ sys.path.insert(0, str(Path(__file__).parent))
import git_delivery as d import git_delivery as d
class DeliveryTest(unittest.TestCase): class DeliveryTest(unittest.TestCase):
def test_paginated_tree_is_complete_and_pinned_before_bootstrap(self):
commit = 'a' * 40
first = {'sha':commit, 'truncated':True, 'total_count':3, 'page':1,
'tree':[{'path':'a'}, {'path':'b'}]}
second = {**first, 'page':2, 'tree':[{'path':'c'}]}
with patch.object(d, 'open_git', side_effect=[io.StringIO(json.dumps(first)), io.StringIO(json.dumps(second))]) as request:
self.assertEqual(['a','b','c'], [v['path'] for v in d.repository_tree('An-J/Iomatex_OS', commit, {})])
self.assertEqual('git/trees/'+commit+'?recursive=true&page=2', request.call_args.args[1])
for bad in [{**second, 'tree':[]}, {**second, 'sha':'b'*40},
{**second, 'tree':[{'path':'a'}]}, {**second, 'total_count':4},
{**second, 'page':1}]:
with self.subTest(page=bad), patch.object(d, 'open_git', side_effect=[io.StringIO(json.dumps(first)), io.StringIO(json.dumps(bad))]):
with self.assertRaises(ValueError):
d.repository_tree('An-J/Iomatex_OS', commit, {})
def test_only_trusted_git_aliases_receive_credentials(self): def test_only_trusted_git_aliases_receive_credentials(self):
for host in d.ALLOWED_HOSTS: for host in d.ALLOWED_HOSTS:
self.assertEqual('An-J/Iomatex_OS', d.repo_name('https://' + host + '/An-J/Iomatex_OS.git')) self.assertEqual('An-J/Iomatex_OS', d.repo_name('https://' + host + '/An-J/Iomatex_OS.git'))
with patch.object(d.urllib.request, 'build_opener') as opener: with patch.object(d.urllib.request, 'build_opener') as opener:
d.open_git('An-J/Iomatex_OS', 'branches/ci-cd', {'username': 'u', 'password': 'p', 'host': host}) d.open_git('An-J/Iomatex_OS', 'branches/ci-cd', {'username': 'u', 'password': 'p', 'host': host})
request = opener.return_value.open.call_args.args[0] request = opener.return_value.open.call_args.args[0]
self.assertEqual('IomatexOS-Updater/1.0', request.get_header('User-agent')) self.assertEqual('https://' + host + '/api/v1/repos/An-J/Iomatex_OS/branches/ci-cd', request.full_url)
self.assertEqual('https://git.iomatex.com/api/v1/repos/An-J/Iomatex_OS/branches/ci-cd', request.full_url)
for host in ['evil.example', 'git.iomatex.com.evil', 'user@git.iomatex.com', 'git.iomatex.com:443']: for host in ['evil.example', 'git.iomatex.com.evil', 'user@git.iomatex.com', 'git.iomatex.com:443']:
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
d.open_git('An-J/Iomatex_OS', 'branches/ci-cd', {'username': 'u', 'password': 'p', 'host': host}) d.open_git('An-J/Iomatex_OS', 'branches/ci-cd', {'username': 'u', 'password': 'p', 'host': host})
def test_package_download_uses_persisted_host(self): def test_package_download_uses_persisted_host(self):
data = b'package' data = b'package'
config = {'host': 'git.it-screen.com', 'repo': 'An-J/Iomatex_OS', 'commit': 'a'*40, config = {'host': 'git.iomatex.com', 'repo': 'An-J/Iomatex_OS', 'commit': 'a'*40,
'objects': {'debian/a.deb': {'path': 'third_party/a.deb', 'sha256': hashlib.sha256(data).hexdigest()}}} 'objects': {'debian/a.deb': {'path': 'third_party/a.deb', 'sha256': hashlib.sha256(data).hexdigest()}}}
with tempfile.TemporaryDirectory() as folder, patch.object(d, 'open_git', return_value=io.BytesIO(data)) as request: with tempfile.TemporaryDirectory() as folder, patch.object(d, 'open_git', return_value=io.BytesIO(data)) as request:
d.download_object(config, 'debian/a.deb', Path(folder)/'a.deb', {'username': 'u', 'password': 'p'}) d.download_object(config, 'debian/a.deb', Path(folder)/'a.deb', {'username': 'u', 'password': 'p'})
self.assertEqual('git.iomatex.com', request.call_args.args[2]['host']) self.assertEqual('git.iomatex.com', request.call_args.args[2]['host'])
def test_new_activator_migrates_old_bootstrap_persisted_inputs(self):
with tempfile.TemporaryDirectory() as folder:
base = Path(folder)
root = base/'snapshot'
(root/'offline').mkdir(parents=True)
(root/'offline/git_delivery.py').write_text('# delivery owner')
(root/'.iomatex-source.json').write_text(json.dumps({
'host':'git.it-screen.com','repo':'An-J/Iomatex_OS','commit':'a'*40}))
(base/'etc/apt/apt.conf.d').mkdir(parents=True)
(base/'usr/lib/apt/methods').mkdir(parents=True)
auth = base/'auth.json'
def mapped(value):
return base/str(value).lstrip('/') if str(value).startswith(('/etc/apt','/usr/')) else Path(value)
with patch.object(d, 'platform_check'), patch.object(d, 'catalog', return_value=('',{})), \
patch.object(d, 'auth_from_env', return_value={'username':'u','password':'p','host':'git.it-screen.com'}), \
patch.object(d, 'STATE', base/'state'), patch.object(d, 'AUTH', auth), \
patch.object(d, 'CACHE', base/'cache'), patch.object(d, 'Path', side_effect=mapped), \
patch.object(d, 'cleanup'):
d.activate(root)
for path in [auth, root/'.iomatex-source.json', base/'state/source.json']:
self.assertEqual('git.iomatex.com', json.loads(path.read_text())['host'])
self.assertEqual('p', json.loads(auth.read_text())['password'])
self.assertEqual(0o600, auth.stat().st_mode & 0o777)
self.assertIn('iomatex://git.iomatex.com/', (base/'etc/apt/iomatex-offline.list').read_text())
def test_payloads_excluded_from_edge_snapshot(self): def test_payloads_excluded_from_edge_snapshot(self):
for name in ['third_party/debian/bullseye-arm64/repo/a.deb', 'third_party/zigbee2mqtt/z.tar.gz', 'stage_itscreen/itscreen']: for name in ['third_party/debian/bullseye-arm64/repo/a.deb', 'third_party/zigbee2mqtt/z.tar.gz', 'stage_itscreen/itscreen']:
self.assertTrue(d.is_payload(name)) self.assertTrue(d.is_payload(name))
@ -171,8 +130,7 @@ class DeliveryTest(unittest.TestCase):
key='debian/xserver-common_2%3a1.0+deb11_all.deb' key='debian/xserver-common_2%3a1.0+deb11_all.deb'
objects={key:{}} objects={key:{}}
for path in [key, 'debian/xserver-common_2%253a1.0%2bdeb11_all.deb']: for path in [key, 'debian/xserver-common_2%253a1.0%2bdeb11_all.deb']:
for host in d.ALLOWED_HOSTS: self.assertEqual(key,d.apt_key('iomatex://git.it-screen.com/'+path,objects))
self.assertEqual(key,d.apt_key('iomatex://'+host+'/'+path,objects))
def test_unchanged_snapshot_file_is_reused_without_network(self): def test_unchanged_snapshot_file_is_reused_without_network(self):
with tempfile.TemporaryDirectory() as folder: with tempfile.TemporaryDirectory() as folder:

View File

@ -19,7 +19,6 @@ dpkg-query() {
if [[ "$EXISTING" == 1 ]]; then printf 'install ok installed'; else return 1; fi if [[ "$EXISTING" == 1 ]]; then printf 'install ok installed'; else return 1; fi
} }
install_packages_best_effort() { printf '%s\\n' "$*"; } install_packages_best_effort() { printf '%s\\n' "$*"; }
run_long() { printf '%s\\n' "$*"; }
''' '''
return subprocess.check_output(['bash', '-ec', stubs + functions + '\nprepare_qt_gles_stack\ninstall_qt_packages'], return subprocess.check_output(['bash', '-ec', stubs + functions + '\nprepare_qt_gles_stack\ninstall_qt_packages'],
env={**os.environ, 'EXISTING': str(existing)}, text=True) env={**os.environ, 'EXISTING': str(existing)}, text=True)
@ -33,12 +32,4 @@ run_long() { printf '%s\\n' "$*"; }
def test_fresh_image_gets_gles(self): def test_fresh_image_gets_gles(self):
self.assertIn('libqt5gui5-gles libqt5quick5-gles', self.run_selection(0)) self.assertIn('libqt5gui5-gles libqt5quick5-gles', self.run_selection(0))
def test_required_player_qml_modules_use_strict_install(self):
output = self.run_selection(0)
self.assertIn(
'apt-get install -y --no-remove qml-module-qtquick-window2 '
'qml-module-qtquick-layouts qml-module-qtquick-controls',
output,
)
if __name__ == '__main__': unittest.main() if __name__ == '__main__': unittest.main()

View File

@ -34,7 +34,6 @@ class SnapshotUpdateTest(unittest.TestCase):
def test_confirmed_update_preserves_hotfix_and_operator_files(self): def test_confirmed_update_preserves_hotfix_and_operator_files(self):
self.bootstrap() self.bootstrap()
self.assertEqual(b'new release', (self.root/'install.sh').read_bytes()) self.assertEqual(b'new release', (self.root/'install.sh').read_bytes())
self.assertEqual('git.iomatex.com', json.loads((self.root/'.iomatex-source.json').read_text())['host'])
self.assertEqual(b'operator configuration', (self.root/'operator.conf').read_bytes()) self.assertEqual(b'operator configuration', (self.root/'operator.conf').read_bytes())
backup, = self.parent.glob('.installer-local-changes-*') backup, = self.parent.glob('.installer-local-changes-*')
self.assertEqual(0o700, backup.stat().st_mode & 0o777) self.assertEqual(0o700, backup.stat().st_mode & 0o777)

View File

@ -37,25 +37,6 @@ class StageVersionsTest(unittest.TestCase):
versions.configure(root) versions.configure(root)
self.assertEqual('git.iomatex.com', versions.read_json(versions.CONFIG)['host']) self.assertEqual('git.iomatex.com', versions.read_json(versions.CONFIG)['host'])
def test_all_stage_catalogs_use_new_host_for_legacy_and_missing_config(self):
for host in (None, 'git.it-screen.com', 'git.iomatex.com'):
with self.subTest(host=host):
cfg = {'repo': 'An-J/Iomatex_OS', 'branch': 'ci-cd'}
if host is not None:
cfg['host'] = host
versions.delivery.write_json(versions.CONFIG, cfg)
with mock.patch.object(versions.delivery, 'auth_from_env', return_value={'username':'u','password':'p'}), \
mock.patch.object(versions.delivery.urllib.request, 'build_opener') as opener:
opener.return_value.open.side_effect = [
io.BytesIO(json.dumps({'commit': {'id': COMMIT}}).encode()),
io.BytesIO(json.dumps(self.catalog).encode())]
versions.refresh()
result = versions.read_json(versions.STATE / 'available.json')
self.assertEqual('', result['error'])
self.assertEqual(set(versions.STAGES), set(result['stages']))
for call in opener.return_value.open.call_args_list:
self.assertTrue(call.args[0].full_url.startswith('https://git.iomatex.com/'))
def test_published_catalog_is_accepted_by_legacy_console(self): def test_published_catalog_is_accepted_by_legacy_console(self):
raw = json.loads((ROOT / 'stage-releases.json').read_text()) raw = json.loads((ROOT / 'stage-releases.json').read_text())
# This is the exact set checked by Console 3.1.2's validator. # This is the exact set checked by Console 3.1.2's validator.
@ -275,18 +256,6 @@ class StageVersionsTest(unittest.TestCase):
self.assertEqual(expected, versions.read_json(versions.STATE / 'available.json')['error']) self.assertEqual(expected, versions.read_json(versions.STATE / 'available.json')['error'])
self.assertFalse(self.snapshot()['can_install']) self.assertFalse(self.snapshot()['can_install'])
def test_cloudflare_client_block_is_not_reported_as_bad_git_credentials(self):
from urllib.error import HTTPError
failure = HTTPError('https://git.iomatex.com/', 403, 'Forbidden', {},
io.BytesIO(b'error code: 1010'))
with mock.patch.object(versions.delivery, 'open_git', side_effect=failure), \
mock.patch.object(versions.delivery, 'auth_from_env', return_value={}):
versions.refresh()
error = versions.read_json(versions.STATE / 'available.json')['error']
self.assertIn('Cloudflare 1010', error)
self.assertNotIn('credentials', error)
self.assertFalse(self.snapshot()['can_install'])
def test_release_check_refreshes_after_one_minute(self): def test_release_check_refreshes_after_one_minute(self):
for age, expected in [(59, False), (61, True)]: for age, expected in [(59, False), (61, True)]:
with self.subTest(age=age), mock.patch.object(versions, '_checking', False), \ with self.subTest(age=age), mock.patch.object(versions, '_checking', False), \

View File

@ -14,7 +14,7 @@
"version": "1.0.1" "version": "1.0.1"
}, },
"stage_ui": { "stage_ui": {
"version": "3.1.42" "version": "3.1.28"
}, },
"stage_avahi": { "stage_avahi": {
"version": "1.0.0" "version": "1.0.0"
@ -23,7 +23,7 @@
"version": "1.0.0" "version": "1.0.0"
}, },
"stage_itscreen": { "stage_itscreen": {
"version": "1.0.42" "version": "1.0.33"
}, },
"stage_reverse_tunnels": { "stage_reverse_tunnels": {
"version": "1.0.2" "version": "1.0.2"
@ -31,7 +31,7 @@
}, },
"optional_stages": { "optional_stages": {
"stage_ip_stream": { "stage_ip_stream": {
"version": "1.0.10" "version": "1.0.8"
} }
} }
} }

View File

@ -6,8 +6,6 @@ import re
import sys import sys
import threading import threading
import time import time
import uuid
import math
from datetime import datetime, timezone from datetime import datetime, timezone
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
@ -65,11 +63,6 @@ class BridgeState:
self.last_message_at = "" self.last_message_at = ""
self.mqtt_connected = False self.mqtt_connected = False
self.mqtt_last_error = "" self.mqtt_last_error = ""
self.hmi_received = None
self.hmi_emitted = None
self.hmi_registers = {}
self.hmi_components = {}
self.hmi_capabilities = {}
def set_mqtt_connected(self, value): def set_mqtt_connected(self, value):
with self.lock: with self.lock:
@ -96,36 +89,6 @@ class BridgeState:
self.raw_payload = payload self.raw_payload = payload
self.last_message_at = utc_timestamp() self.last_message_at = utc_timestamp()
def observe_hmi(self, payload, registers=False):
now = time.monotonic()
if registers:
emitted = payload.get('observed_at_ms')
if type(emitted) not in (int, float) or not math.isfinite(emitted) or abs(time.time()*1000-emitted)>5000: return False
for item in (payload.get('payload') or payload).get('values', []):
if not isinstance(item, dict) or not isinstance(item.get('id'), int): continue
with self.lock:
previous=self.hmi_registers.get(str(item['id']))
if previous and previous[1]['observed_at_ms'] >= emitted: continue
self.hmi_registers[str(item['id'])] = (now, dict(item,observed_at_ms=emitted))
else:
emitted = payload.get('emitted_at')
if type(emitted) not in (int, float) or not math.isfinite(emitted) or abs(time.time()*1000-emitted)>5000: return False
with self.lock:
if self.hmi_emitted is not None and emitted <= self.hmi_emitted: return False
self.hmi_emitted, self.hmi_received = emitted, now
self.hmi_components = payload.get("components") or {}
self.hmi_capabilities = payload.get("capabilities") or {}
return True
def hmi_observation(self, component_id):
with self.lock:
now = time.monotonic()
fresh = self.mqtt_connected and self.hmi_received is not None and 0 <= now-self.hmi_received <= 5
return {'fresh': bool(fresh), 'component': dict(self.hmi_components.get(str(component_id), {})) if fresh else {},
'observed_at_ms': self.hmi_emitted if fresh else None,
'capabilities': dict(self.hmi_capabilities) if fresh else {},
'registers': {key:value for key,(received,value) in self.hmi_registers.items() if 0 <= now-received <= 5} if fresh else {}}
def get_component(self, component_id): def get_component(self, component_id):
with self.lock: with self.lock:
component = self.components.get(str(component_id)) component = self.components.get(str(component_id))
@ -141,14 +104,12 @@ class BridgeState:
class MqttBridge: class MqttBridge:
def __init__(self, mqtt_url, device_id, state, prefix="it-screen/dev"): def __init__(self, mqtt_url, device_id, state):
self.mqtt_url = mqtt_url self.mqtt_url = mqtt_url
self.device_id = device_id self.device_id = device_id
self.state = state self.state = state
self.host, self.port = parse_mqtt_url(mqtt_url) self.host, self.port = parse_mqtt_url(mqtt_url)
self.topic_prefix = prefix self.state_topic = f"it-screen/dev/client/pub/component/plays/{device_id}"
self.state_topic = f"{prefix}/client/pub/component/plays/{device_id}"
self.register_topic = f"{prefix}/client/pub/interface/values/{device_id}"
self._publish_lock = threading.Lock() self._publish_lock = threading.Lock()
self._ready = threading.Event() self._ready = threading.Event()
self._client = None self._client = None
@ -191,10 +152,10 @@ class MqttBridge:
def is_connected(self): def is_connected(self):
return self._ready.is_set() return self._ready.is_set()
def publish_event(self, component_id, value, title, expires_in_ms=None): def publish_event(self, component_id, value, title):
if self._client is None: if self._client is None:
raise RuntimeError("MQTT client is unavailable") raise RuntimeError("MQTT client is unavailable")
topic = f"{self.topic_prefix}/client/sub/event/push/{component_id}" topic = f"it-screen/dev/client/sub/event/push/{component_id}"
payload = { payload = {
"action": "push", "action": "push",
"value": str(value), "value": str(value),
@ -202,11 +163,7 @@ class MqttBridge:
"time": utc_timestamp(), "time": utc_timestamp(),
"user": "root", "user": "root",
"title": str(title), "title": str(title),
"command_id": uuid.uuid4().hex,
} }
if expires_in_ms is not None:
payload['issued_at_ms'] = round(time.time()*1000)
payload['expires_at_ms'] = payload['issued_at_ms'] + int(expires_in_ms)
serialized = json.dumps(payload, ensure_ascii=True, separators=(",", ":")) serialized = json.dumps(payload, ensure_ascii=True, separators=(",", ":"))
with self._publish_lock: with self._publish_lock:
if not self.is_connected(): if not self.is_connected():
@ -226,7 +183,7 @@ class MqttBridge:
self.state.set_mqtt_error(f"connect failed ({rc})") self.state.set_mqtt_error(f"connect failed ({rc})")
log(f"mqtt connect failed rc={rc}") log(f"mqtt connect failed rc={rc}")
return return
result, _ = client.subscribe([(self.state_topic, 0), (self.register_topic, 0)]) result, _ = client.subscribe(self.state_topic, qos=0)
if result != mqtt_err_success(): if result != mqtt_err_success():
self._ready.clear() self._ready.clear()
self.state.set_mqtt_error("subscribe failed") self.state.set_mqtt_error("subscribe failed")
@ -258,10 +215,6 @@ class MqttBridge:
log(f"ignored invalid mqtt json topic={msg.topic} error={exc}") log(f"ignored invalid mqtt json topic={msg.topic} error={exc}")
return return
try: try:
if msg.topic == self.register_topic:
if not getattr(msg, "retain", False): self.state.observe_hmi(payload, registers=True)
return
if not getattr(msg, 'retain', False): self.state.observe_hmi(payload)
self.state.update_components(payload) self.state.update_components(payload)
except Exception as exc: except Exception as exc:
log(f"ignored invalid mqtt payload topic={msg.topic} error={exc}") log(f"ignored invalid mqtt payload topic={msg.topic} error={exc}")
@ -281,6 +234,7 @@ class Handler(BaseHTTPRequestHandler):
def end_headers(self): def end_headers(self):
self.send_header("Cache-Control", "no-store") self.send_header("Cache-Control", "no-store")
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Access-Control-Allow-Origin", "*") self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Access-Control-Allow-Headers", "Content-Type") self.send_header("Access-Control-Allow-Headers", "Content-Type")
self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS") self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
@ -289,7 +243,6 @@ class Handler(BaseHTTPRequestHandler):
def send_json(self, payload, code=200): def send_json(self, payload, code=200):
body = json.dumps(payload, ensure_ascii=False).encode("utf-8") body = json.dumps(payload, ensure_ascii=False).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-Length", str(len(body))) self.send_header("Content-Length", str(len(body)))
self.end_headers() self.end_headers()
self.wfile.write(body) self.wfile.write(body)
@ -320,7 +273,6 @@ class Handler(BaseHTTPRequestHandler):
self.end_headers() self.end_headers()
def do_GET(self): def do_GET(self):
if self.app.offline_edit and self.app.offline_edit.handle(self): return
parsed = urlparse(self.path) parsed = urlparse(self.path)
if parsed.path == "/api/health": if parsed.path == "/api/health":
snapshot = self.app.state.health_snapshot() snapshot = self.app.state.health_snapshot()
@ -351,11 +303,7 @@ class Handler(BaseHTTPRequestHandler):
self.send_json({"ok": False, "error": "Not found"}, code=404) self.send_json({"ok": False, "error": "Not found"}, code=404)
def do_POST(self): def do_POST(self):
if self.app.offline_edit and self.app.offline_edit.handle(self): return
parsed = urlparse(self.path) parsed = urlparse(self.path)
if self.app.offline_edit and parsed.path == '/api/event':
self.send_json({'error':'Use the scoped HMI control endpoint'},code=403)
return
if parsed.path != "/api/event": if parsed.path != "/api/event":
self.send_json({"ok": False, "error": "Not found"}, code=404) self.send_json({"ok": False, "error": "Not found"}, code=404)
return return
@ -409,31 +357,7 @@ class App:
self.mqtt_url = os.environ.get("DASHBOARD_BRIDGE_MQTT_URL", DEFAULT_MQTT_URL).strip() or DEFAULT_MQTT_URL self.mqtt_url = os.environ.get("DASHBOARD_BRIDGE_MQTT_URL", DEFAULT_MQTT_URL).strip() or DEFAULT_MQTT_URL
self.device_id = os.environ.get("DASHBOARD_BRIDGE_DEVICE_ID", "").strip() or device_id_from_hostname() self.device_id = os.environ.get("DASHBOARD_BRIDGE_DEVICE_ID", "").strip() or device_id_from_hostname()
self.state = BridgeState() self.state = BridgeState()
offline_config = os.environ.get('OFFLINE_HMI_CONFIG', '').strip() self.mqtt_bridge = MqttBridge(self.mqtt_url, self.device_id, self.state)
prefix = 'it-screen/dev' # Compatibility mode; new HMI never guesses this prefix.
if offline_config:
with open(offline_config) as stream: hmi_config = json.load(stream)
with open(hmi_config['native_config_path']) as stream: native_config = json.load(stream)
prefix = str(native_config['mqtt']['prefix']).strip('/')
if not prefix or len(prefix)>200 or not re.fullmatch(r'[A-Za-z0-9_./-]+',prefix): raise RuntimeError('Invalid native MQTT prefix')
self.device_id = str(native_config['username'])
self.mqtt_bridge = MqttBridge(self.mqtt_url, self.device_id, self.state, prefix)
self.offline_edit = None
offline_config = os.environ.get('OFFLINE_HMI_CONFIG', '').strip()
if offline_config:
if self.bind not in ('127.0.0.1', '::1'):
raise RuntimeError('Offline editing requires a loopback-only bridge')
from offline_edit.runtime import Runtime
def invalidate(topic, payload):
if self.mqtt_bridge._client is None or not self.mqtt_bridge.is_connected():
raise RuntimeError('Local MQTT is not connected; settings are durable but not applied')
result = self.mqtt_bridge._client.publish(topic, json.dumps(payload), qos=1, retain=False)
if result.rc != mqtt_err_success(): raise RuntimeError('Local configuration notification failed')
deadline=time.monotonic()+2.0
while not result.is_published() and time.monotonic()<deadline: time.sleep(0.02)
if not result.is_published(): raise RuntimeError('Local broker acknowledgement timed out')
from offline_edit.control import Control
self.offline_edit = Runtime(offline_config, invalidate, control=Control(self.state, self.mqtt_bridge))
self.httpd = ThreadingHTTPServer((self.bind, self.port), Handler) self.httpd = ThreadingHTTPServer((self.bind, self.port), Handler)
self.httpd.app = self self.httpd.app = self
@ -442,11 +366,9 @@ class App:
f"starting http bind={self.bind} port={self.port} device_id={self.device_id} mqtt_url={self.mqtt_url}" f"starting http bind={self.bind} port={self.port} device_id={self.device_id} mqtt_url={self.mqtt_url}"
) )
self.mqtt_bridge.start() self.mqtt_bridge.start()
if self.offline_edit: self.offline_edit.start()
try: try:
self.httpd.serve_forever() self.httpd.serve_forever()
finally: finally:
if self.offline_edit: self.offline_edit.stop()
self.mqtt_bridge.stop() self.mqtt_bridge.stop()

View File

@ -1 +0,0 @@
"""Optional offline settings module; importing the legacy bridge does not enable it."""

View File

@ -1,51 +0,0 @@
"""Delegated immediate control adapter. No scheduler, persistence or replay queue."""
import math
import threading
import time
class Control:
def __init__(self, state, bridge, monotonic=time.monotonic):
self.state, self.bridge, self.monotonic = state, bridge, monotonic
self.lock = threading.Lock()
self.last_command = {}
def observation(self, component):
observed = self.state.hmi_observation(int(component['id']))
outputs = component.get('hardware_outputs') or []
reason = 'unbound_output' if not outputs else None
if not reason and not observed['fresh']: reason = 'observation_unavailable'
if not reason and observed['capabilities'].get('push_expiry_v1') is not True: reason = 'client_update_required'
registers = []
for register in outputs:
item = dict(register)
status = observed['registers'].get(str(register['id']))
item['status'] = status
registers.append(item)
if not reason and (not status or status.get('available') is not True
or status.get('error_code', 0) != 0 or status.get('emulated') is True):
reason = 'output_unavailable'
observed.update(registers=registers, reason=reason,
can_start=not reason and component['groups']['active']['value']['active'] == 1,
can_stop=not reason)
observed.pop('capabilities', None)
return observed
def issue(self, component, action):
if action not in ('start', 'stop'): raise ValueError('Only immediate Start/Stop is allowed')
with self.lock:
# Re-read observations immediately before dispatch; UI readiness is not authority.
state = self.observation(component)
if not state['can_' + action]: raise PermissionError(state['reason'] or 'component_inactive')
key = int(component['id'])
now = self.monotonic()
if now - self.last_command.get(key, -math.inf) < 1:
raise PermissionError('command_pending')
self.last_command = {k:stamp for k,stamp in self.last_command.items() if now-stamp < 60}
self.last_command[key] = now
try:
topic, payload = self.bridge.publish_event(key, action, component['title'], expires_in_ms=5000)
except RuntimeError as error:
raise OSError('Immediate command unavailable; it was not queued') from error
return {'status': 'accepted', 'execution_confirmed': False,
'command_id': payload['command_id'], 'expires_at_ms': payload['expires_at_ms']}

View File

@ -1,201 +0,0 @@
"""Opt-in transport adapter for the existing bridge; no independent scheduler."""
import base64
import gzip
import hmac
import json
import secrets
import threading
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
from .store import Store
LOCAL_HOSTS = {'localhost', '127.0.0.1', '::1'}
NATIVE_PATHS = {'/v2/device': 'native_config', '/v2/device/layout': 'native_frames'}
class Runtime:
def __init__(self, config_path, publish_invalidation, control=None):
self.control = control
self.config = json.loads(Path(config_path).read_text())
credentials = json.loads(Path(self.config['native_config_path']).read_text())
self.authorization = 'Basic ' + base64.b64encode((credentials['username'] + ':' + credentials['password']).encode()).decode()
self.device_id = int(credentials['id'])
self.prefix = str(credentials['mqtt']['prefix']).strip('/')
self.username = str(credentials['username'])
self.publish_invalidation = publish_invalidation
self.store = Store(self.config['database'])
Path(self.config['database']).chmod(0o600)
self.session = secrets.token_urlsafe(32)
self.stop_event = threading.Event()
self.sync_event = threading.Event()
self.online, self.last_error = False, 'not_connected'
self.last_invalidated = None
self.cloud_api = self._origin(self.config['cloud_api_url'])
self.native_base = self._origin(self.config['native_base_url'])
self.assets = Path(self.config['assets']).resolve()
@staticmethod
def _origin(value):
parsed = urllib.parse.urlsplit(value)
if parsed.scheme not in ('http', 'https') or not parsed.hostname or parsed.username or parsed.password or parsed.query or parsed.fragment:
raise ValueError('Configure an explicit credential-free upstream URL')
# Public transports require TLS; HTTP is limited to private deployment addresses.
if parsed.scheme == 'http':
import ipaddress
try:
if not ipaddress.ip_address(parsed.hostname).is_private: raise ValueError('Public upstream requires TLS')
except ValueError:
if parsed.hostname not in LOCAL_HOSTS: raise ValueError('Public upstream requires TLS')
return value.rstrip('/')
def _request(self, base, path, body=None, headers=None):
data = json.dumps(body).encode() if body is not None else None
request = urllib.request.Request(base + path, data=data, headers={'Authorization': self.authorization, 'Content-Type': 'application/json', 'Accept': 'application/json', **(headers or {})})
with urllib.request.urlopen(request, timeout=8) as response:
if response.status != 200: raise OSError('Unexpected API response')
reader=gzip.GzipFile(fileobj=response) if response.headers.get('Content-Encoding','').lower()=='gzip' else response
body=reader.read(4*1024*1024+1)
if len(body)>4*1024*1024: raise ValueError('Platform response exceeds the snapshot limit')
payload = json.loads(body)
return payload.get('data', payload) if isinstance(payload, dict) else payload
def synchronize(self):
try:
# Refresh grants before sending queued operations. Revoked scope never replays.
snapshot = self._request(self.cloud_api, '/offline-edit/snapshot')
self.store.ingest(snapshot)
for operation in self.store.pending():
result = self._request(self.cloud_api, '/offline-edit/operations', operation)
self.store.acknowledge(result)
self.online, self.last_error = True, ''
except (OSError, ValueError, KeyError, urllib.error.HTTPError) as error:
self.online = False
self.last_error = 'authorization_failed' if getattr(error, 'code', None) in (401, 403) else 'cloud_unavailable'
def notify_desired(self):
try: revision=self._cache('desired_revision')
except OSError: return True
if revision==self.last_invalidated: return True
try:
self.publish_invalidation(self.prefix+'/client/sub/action/'+self.username, {'action':'update','model':'config','revision':revision})
self.last_invalidated=revision
return True
except (OSError,RuntimeError):
return False # Durable settings remain visible; a later tick retries invalidation only.
def request_sync(self):
self.sync_event.set()
def start(self):
def loop():
while not self.stop_event.is_set():
self.sync_event.clear()
self.synchronize()
self.notify_desired()
self.sync_event.wait(10 if self.online else 15)
self.thread = threading.Thread(target=loop, name='offline-edit-sync', daemon=True)
self.thread.start()
def stop(self):
self.stop_event.set()
self.sync_event.set()
if hasattr(self, 'thread'): self.thread.join(timeout=9)
def _cache(self, key, value=None):
with self.store.transaction() as db:
if value is not None:
db.execute('INSERT OR REPLACE INTO metadata VALUES(?,?)', (key, json.dumps(value)))
return value
row = db.execute('SELECT value FROM metadata WHERE key=?', (key,)).fetchone()
if row is None: raise OSError('No cached native configuration')
return json.loads(row[0])
def native(self, path, query, headers=None):
if path not in NATIVE_PATHS: raise PermissionError('Native route is outside the configuration scope')
name = NATIVE_PATHS[path]
# The platform's geometry wire contract is version-dependent. Preserve
# native capability headers; never reuse a cache from a different one.
forwarded={key:str(value)[:512] for key,value in (headers or {}).items() if key in ('User-Agent','X-Edge-Client-Version') and value}
if forwarded:
try: previous=self._cache('native_contract')
except OSError: previous=None
if previous!=forwarded:
with self.store.transaction() as db: db.execute("DELETE FROM metadata WHERE key IN ('native_config','native_frames')")
self._cache('native_contract',forwarded)
try:
payload = self._request(self.native_base, path + ('?' + query if query else ''), headers=forwarded)
self._cache(name, payload)
# Native already receives the platform MQTT update channel. Its
# configuration fetch also refreshes HMI clocks without another subscriber.
self.request_sync()
except (OSError, ValueError):
payload = self._cache(name)
return self.store.overlay(payload) if name == 'native_frames' else payload
def _local(self, handler):
host = urllib.parse.urlsplit('http://' + handler.headers.get('Host', '')).hostname
if handler.client_address[0] not in ('127.0.0.1', '::1') or host not in LOCAL_HOSTS:
raise PermissionError('HMI is available only on the local kiosk')
def _write_allowed(self, handler):
self._local(handler)
origin = urllib.parse.urlsplit(handler.headers.get('Origin', ''))
host = urllib.parse.urlsplit('http://' + handler.headers.get('Host', ''))
if origin.scheme != 'http' or origin.netloc != host.netloc or origin.hostname not in LOCAL_HOSTS:
raise PermissionError('Foreign HMI origin')
if not hmac.compare_digest(handler.headers.get('X-HMI-Session', ''), self.session):
raise PermissionError('Local operator session required')
if handler.headers.get('Content-Type', '').split(';')[0] != 'application/json':
raise ValueError('Expected application/json')
def handle(self, handler):
parsed = urllib.parse.urlsplit(handler.path)
if not (parsed.path.startswith('/hmi') or parsed.path.startswith('/native/')): return False
try:
self._local(handler)
if parsed.path.startswith('/native/'):
if handler.command != 'GET' or not hmac.compare_digest(handler.headers.get('Authorization', ''), self.authorization):
handler.send_response(401); handler.send_header('WWW-Authenticate', 'Basic realm="IOMATEX native configuration"'); handler.end_headers(); return True
handler.send_json(self.native(parsed.path[len('/native'):], parsed.query, {key:handler.headers.get(key) for key in ('User-Agent','X-Edge-Client-Version')})); return True
query = urllib.parse.parse_qs(parsed.query)
if handler.command == 'GET' and parsed.path == '/hmi/api/session':
handler.send_json({'session': self.session, 'online': self.online, 'error': self.last_error}); return True
if handler.command == 'GET' and parsed.path == '/hmi/api/component':
handler.send_json(self.store.view(int(query['id'][0]))); return True
if handler.command == 'GET' and parsed.path == '/hmi/api/runtime':
component = self.store.view(int(query['id'][0]))
value = self.control.observation(component) if self.control else {'fresh':False,'component':{},'registers':[],'can_start':False,'can_stop':False,'reason':'control_unavailable'}
handler.send_json(value); return True
if handler.command == 'POST' and parsed.path == '/hmi/api/event':
self._write_allowed(handler)
size=int(handler.headers.get('Content-Length','0'))
if not 0 < size <= 2048: raise ValueError('Invalid command size')
value=json.loads(handler.rfile.read(size))
if set(value)!={'component_id','action'} or type(value['component_id']) is not int: raise ValueError('Invalid immediate command')
component=self.store.view(value['component_id'])
if not self.control: raise PermissionError('Control is not installed')
handler.send_json(self.control.issue(component,value['action'])); return True
if handler.command == 'POST' and parsed.path == '/hmi/api/settings':
self._write_allowed(handler)
size = int(handler.headers.get('Content-Length', '0'))
if not 0 < size <= 65536: raise ValueError('Settings operation is too large or empty')
value = json.loads(handler.rfile.read(size))
operation = self.store.edit(int(value['component_id']), str(value['group']), value['value'])
# Existing local MQTT subscriber + native configuration application own execution.
applied=self.notify_desired()
self.request_sync()
handler.send_json({'operation': operation, 'status': 'saved_locally', 'application_status':'notification_sent' if applied else 'pending'}); return True
if handler.command == 'GET' and parsed.path in ('/hmi', '/hmi/'):
body = (self.assets / 'index.html').read_bytes()
handler.send_response(200); handler.send_header('Content-Type', 'text/html; charset=utf-8'); handler.send_header('Cache-Control', 'no-store'); handler.send_header('Content-Length', str(len(body))); handler.end_headers(); handler.wfile.write(body); return True
handler.send_json({'error': 'not_found'}, code=404)
except PermissionError as error:
handler.send_json({'error': str(error)}, code=403)
except (ValueError, KeyError, TypeError) as error:
handler.send_json({'error': str(error)}, code=422)
except OSError:
handler.send_json({'error': 'local_configuration_unavailable'}, code=503)
return True

View File

@ -1,256 +0,0 @@
"""Durable desired settings and outbox. Never queues physical Start/Stop actions."""
import copy
import json
import math
import sqlite3
import time
import uuid
from contextlib import contextmanager
from pathlib import Path
GROUPS = {
'duration': ('duration',), 'active': ('active',),
'schedule': ('valid_from', 'valid_to', 'valid_hour_from', 'valid_hour_to', 'days_week'),
'conditions': ('triggers', 'start_condition_operator', 'per_hour'),
'availability': ('valid_from', 'valid_to', 'valid_hour_from', 'valid_hour_to', 'days_week', 'activity'),
}
ACTIVITY_KEYS = {'activity_schedules', 'activity_time_ranges', 'activity_date_ranges', 'activity_date_operator'}
def attributes(value):
result = copy.deepcopy(value)
if 'activity' in result:
result.pop('activity')
return result
def apply_value(element, value):
if 'triggers' in value:
current = element.get('triggers') or {}
if isinstance(current, str): current = json.loads(current)
value = copy.deepcopy(value)
value['triggers'] = {**{k:v for k,v in current.items() if k in ACTIVITY_KEYS},
**{k:v for k,v in value['triggers'].items() if k not in ACTIVITY_KEYS}}
element.update(attributes(value))
if 'activity' in value:
triggers = element.get('triggers') or {}
if isinstance(triggers, str): triggers = json.loads(triggers)
element['triggers'] = {k:v for k,v in triggers.items() if k not in ACTIVITY_KEYS}
element['triggers'].update(copy.deepcopy(value['activity']))
def boot_id():
try:
return Path('/proc/sys/kernel/random/boot_id').read_text().strip()
except OSError:
return None # Unknown continuity must not invent a trusted timestamp.
def validate(group, value, generator='sync'):
if group not in GROUPS or not isinstance(value, dict) or set(value) != set(GROUPS[group]):
raise ValueError('Unsupported or incomplete atomic settings group')
if group == 'duration':
number = value['duration']
if isinstance(number, bool) or not isinstance(number, (int, float)) or not math.isfinite(number) or not 3 <= number <= (3600 if generator == 'sync' else 86400):
raise ValueError('Duration exceeds the generator limit')
if group == 'active' and (type(value['active']) is not int or value['active'] not in (0, 1)):
raise ValueError('Activity must be 0 or 1')
if group == 'schedule' and any(v is not None and not isinstance(v, str) for v in value.values()):
raise ValueError('Invalid schedule value')
if group == 'availability':
if (not isinstance(value['activity'], dict) or set(value['activity']) - ACTIVITY_KEYS
or any(v is not None and not isinstance(v, str) for k,v in value.items() if k != 'activity')):
raise ValueError('Invalid availability group')
if group == 'conditions' and (not isinstance(value['triggers'], dict) or value['start_condition_operator'] not in ('AND', 'OR') or type(value['per_hour']) is not int or value['per_hour'] < 0):
raise ValueError('Invalid conditions')
return copy.deepcopy(value)
class Store:
def __init__(self, path, wall=time.time, monotonic=time.monotonic, boot=boot_id):
self.path, self.wall, self.monotonic, self.boot = str(path), wall, monotonic, boot
Path(self.path).parent.mkdir(parents=True, exist_ok=True)
with self.transaction() as db:
db.executescript('''
CREATE TABLE IF NOT EXISTS components(id INTEGER PRIMARY KEY, payload TEXT NOT NULL, anchor_monotonic REAL NOT NULL, anchor_wall REAL NOT NULL, boot_id TEXT);
CREATE TABLE IF NOT EXISTS outbox(id TEXT PRIMARY KEY, component_id INTEGER NOT NULL, group_name TEXT NOT NULL, payload TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending', result TEXT, sequence INTEGER NOT NULL);
CREATE TABLE IF NOT EXISTS metadata(key TEXT PRIMARY KEY, value TEXT NOT NULL);
''')
@contextmanager
def transaction(self):
db = sqlite3.connect(self.path, timeout=10, isolation_level=None)
db.row_factory = sqlite3.Row
try:
db.execute('PRAGMA journal_mode=WAL')
db.execute('PRAGMA synchronous=FULL')
db.execute('BEGIN IMMEDIATE')
yield db
if db.in_transaction:
db.commit()
except BaseException:
if db.in_transaction:
db.rollback()
raise
finally:
db.close()
def ingest(self, snapshot):
if snapshot.get('schema_version') != 1 or not isinstance(snapshot.get('components'), list):
raise ValueError('Unsupported snapshot')
with self.transaction() as db:
device_id = int(snapshot['device_id'])
old = db.execute("SELECT value FROM metadata WHERE key='device_id'").fetchone()
if old and int(old[0]) != device_id:
raise ValueError('Device identity changed; use a separate database')
db.execute("INSERT OR REPLACE INTO metadata VALUES('device_id',?)", (str(device_id),))
ids = []
changed = False
for component in snapshot['components']:
component_id = int(component['id'])
ids.append(component_id)
component=copy.deepcopy(component)
previous=db.execute('SELECT payload FROM components WHERE id=?',(component_id,)).fetchone()
previous=json.loads(previous[0]) if previous else None
if previous:
# An in-flight older snapshot must not undo an acknowledged edit.
for group,canonical in previous['groups'].items():
incoming=component['groups'].get(group)
if incoming and int(incoming['clock']['revision']) < int(canonical['clock']['revision']):
component['groups'][group]=canonical
before={k:v['value'] for k,v in (previous or {}).get('groups',{}).items()}
after={k:v['value'] for k,v in component['groups'].items()}
if before!=after:
changed=True
self._update_native_cache(db,component_id,{k:v for value in after.values() for k,v in value.items()})
db.execute('INSERT OR REPLACE INTO components VALUES(?,?,?,?,?)', (component_id, json.dumps(component), self.monotonic(), self.wall(), self.boot()))
# A complete server grant snapshot is authoritative for deletions and revocations.
allowed = set(ids)
for row in db.execute('SELECT id FROM components').fetchall():
if row['id'] not in allowed:
changed=True
db.execute('DELETE FROM components WHERE id=?', (row['id'],))
db.execute("UPDATE outbox SET status='scope_removed' WHERE component_id=? AND status='pending'", (row['id'],))
if changed:
db.execute("INSERT OR REPLACE INTO metadata VALUES('desired_revision',?)",(json.dumps('server-'+uuid.uuid4().hex),))
@staticmethod
def _update_native_cache(db,component_id,value):
cached=db.execute("SELECT value FROM metadata WHERE key='native_frames'").fetchone()
if not cached:return
document=json.loads(cached[0])
for layout in document.get('layouts',[]):
for frame in layout.get('frames',[]):
for model in frame.get('playlists',[]):
for key in ('elements','diagnostic_elements'):
for element in model.get(key,[]):
if int(element['id'])!=component_id:continue
apply_value(element,value)
if element.get('execution_eligibility',{}).get('eligible') is False:element['active']=0
db.execute("UPDATE metadata SET value=? WHERE key='native_frames'",(json.dumps(document),))
def _component(self, db, component_id):
row = db.execute('SELECT * FROM components WHERE id=?', (component_id,)).fetchone()
if not row:
raise PermissionError('Component is not granted')
data = json.loads(row['payload'])
# Use the advancing server anchor when OS monotonic continuity is intact.
elapsed = self.monotonic() - row['anchor_monotonic']
anchored = data['anchor']['server_time_ms'] / 1000 + elapsed
now = max(self.wall(), anchored) if row['boot_id'] == self.boot() else self.wall()
if now >= int(data['grant_expires_at']):
raise PermissionError('Editing grant expired')
return row, data
def view(self, component_id):
with self.transaction() as db:
_, data = self._component(db, component_id)
pending = db.execute("SELECT * FROM outbox WHERE component_id=? AND status IN ('pending','clock_conflict','revision_conflict') ORDER BY sequence", (component_id,)).fetchall()
data['pending'] = []
for row in pending:
op = json.loads(row['payload'])
data['groups'][row['group_name']]['value'] = op['value']
data['pending'].append({'operation_id': row['id'], 'group': row['group_name'], 'status': row['status']})
return data
def edit(self, component_id, group, value):
with self.transaction() as db:
row, component = self._component(db, component_id)
value = validate(group, value, component.get('generator_type', 'sync'))
elapsed = self.monotonic() - row['anchor_monotonic']
continuity = self.boot() is not None and row['boot_id'] == self.boot() and elapsed >= 0
wall_elapsed = self.wall() - row['anchor_wall']
trusted = continuity and abs(wall_elapsed - elapsed) <= 300
elapsed_ms = max(0, round(elapsed * 1000))
sequence = db.execute('SELECT COALESCE(MAX(sequence),0)+1 FROM outbox').fetchone()[0]
operation = {
'schema_version': 1, 'operation_id': uuid.uuid4().hex,
'device_id': int(db.execute("SELECT value FROM metadata WHERE key='device_id'").fetchone()[0]),
'component_id': component_id, 'grant_id': component['grant_id'],
'group': group, 'value': value,
'base_revision': int(component['groups'][group]['clock']['revision']),
'anchor_id': component['anchor']['id'], 'elapsed_ms': elapsed_ms,
'created_at_ms': int(component['anchor']['server_time_ms']) + elapsed_ms,
'clock_trusted': trusted,
}
# One transaction owns both the desired overlay and the retryable operation.
db.execute('INSERT INTO outbox(id,component_id,group_name,payload,sequence) VALUES(?,?,?,?,?)',
(operation['operation_id'], component_id, group, json.dumps(operation), sequence))
db.execute("INSERT OR REPLACE INTO metadata VALUES('desired_revision',?)", (json.dumps('offline-'+operation['operation_id']),))
return operation
def pending(self, limit=32):
with self.transaction() as db:
return [json.loads(r[0]) for r in db.execute("SELECT payload FROM outbox WHERE status='pending' ORDER BY sequence LIMIT ?", (min(32, max(1, limit)),))]
def acknowledge(self, result):
with self.transaction() as db:
row = db.execute('SELECT * FROM outbox WHERE id=?', (result['operation_id'],)).fetchone()
if not row:
raise ValueError('Unknown operation receipt')
op = json.loads(row['payload'])
if int(result['component_id']) != row['component_id'] or result['group'] != row['group_name']:
raise ValueError('Receipt identity mismatch')
if row['status'] != 'pending':
return # Repeated network acknowledgement is inert.
status = result['status']
if status not in ('accepted', 'superseded', 'clock_conflict', 'revision_conflict'):
raise ValueError('Unknown receipt status')
component_row = db.execute('SELECT payload FROM components WHERE id=?', (row['component_id'],)).fetchone()
if component_row and status in ('accepted', 'superseded'):
data = json.loads(component_row[0]); group = row['group_name']
canonical = result['canonical']
if int(canonical['clock']['revision']) >= int(data['groups'][group]['clock']['revision']):
data['groups'][group] = canonical
db.execute('UPDATE components SET payload=? WHERE id=?', (json.dumps(data), row['component_id']))
# ACK, canonical settings and the native fallback document are one
# durable commit. A power loss must not restore a pre-ACK duration.
self._update_native_cache(db,row['component_id'],canonical['value'])
db.execute('UPDATE outbox SET status=?,result=? WHERE id=?', (status, json.dumps(result), row['id']))
if status in ('accepted','superseded'):
db.execute("INSERT OR REPLACE INTO metadata VALUES('desired_revision',?)", (json.dumps('offline-ack-'+row['id']),))
def overlay(self, canonical):
payload = copy.deepcopy(canonical)
with self.transaction() as db:
ids = [r[0] for r in db.execute('SELECT id FROM components')]
values = {}
for component_id in ids:
try:
component = self.view(component_id)
dirty = {entry['group'] for entry in component['pending']}
values[component_id] = {k: v for name, group in component['groups'].items() if name in dirty for k, v in group['value'].items()}
except PermissionError:
continue
# No new component, runtime, model or hardware binding is invented here.
for layout in payload.get('layouts', []):
for frame in layout.get('frames', []):
for model in frame.get('playlists', []):
for key in ('elements', 'diagnostic_elements'):
for element in model.get(key, []):
if int(element['id']) in values:
apply_value(element, values[int(element['id'])])
if element.get('execution_eligibility', {}).get('eligible') is False:
element['active'] = 0 # Never bypass the platform's unbound-output guard.
return payload

View File

@ -1,25 +0,0 @@
"""Exercise the real HTTP handler, not a browser route interception."""
import sys,threading,unittest,urllib.request
from pathlib import Path
from types import SimpleNamespace
from http.server import ThreadingHTTPServer
sys.path.insert(0,str(Path(__file__).parents[1]/'dashboard_bridge_core/backend'))
from bridge import Handler
class HttpTest(unittest.TestCase):
def test_hmi_html_has_one_html_mime_and_json_stays_json(self):
class Offline:
def handle(self,handler):
if handler.path!='/hmi/':return False
body=b'<!doctype html><title>HMI</title>'
handler.send_response(200);handler.send_header('Content-Type','text/html; charset=utf-8');handler.send_header('Content-Length',str(len(body)));handler.end_headers();handler.wfile.write(body);return True
server=ThreadingHTTPServer(('127.0.0.1',0),Handler)
server.app=SimpleNamespace(offline_edit=Offline())
thread=threading.Thread(target=server.serve_forever,daemon=True);thread.start()
try:
with urllib.request.urlopen('http://127.0.0.1:%s/hmi/'%server.server_port) as response:
self.assertEqual(response.headers.get_all('Content-Type'),['text/html; charset=utf-8'])
self.assertTrue(response.read().startswith(b'<!doctype html>'))
with self.assertRaises(urllib.error.HTTPError) as context:urllib.request.urlopen('http://127.0.0.1:%s/unknown'%server.server_port)
self.assertEqual(context.exception.headers.get_all('Content-Type'),['application/json; charset=utf-8'])
finally:server.shutdown();server.server_close();thread.join()

View File

@ -1,72 +0,0 @@
import copy
import sys
import unittest
from pathlib import Path
from unittest.mock import Mock
sys.path.insert(0,str(Path(__file__).parents[1]/'dashboard_bridge_core/backend'))
from offline_edit.control import Control
from offline_edit.store import apply_value
class ControlTest(unittest.TestCase):
def setUp(self):
self.state=Mock();self.bridge=Mock();self.now=10
self.observed={'fresh':True,'capabilities':{'push_expiry_v1':True},'registers':{'8':{'available':True,'error_code':0,'value':0}},'component':{}}
self.state.hmi_observation.side_effect=lambda _:copy.deepcopy(self.observed)
self.component={'id':22,'title':'Fixture','hardware_outputs':[{'id':8}], 'groups':{'active':{'value':{'active':1}}}}
self.control=Control(self.state,self.bridge,lambda:self.now)
self.bridge.publish_event.return_value=('fixture',{'command_id':'test-command-0001','expires_at_ms':5000})
def test_fail_closed_for_unbound_stale_legacy_and_bad_output(self):
for patch,reason in [({'fresh':False},'observation_unavailable'),({'capabilities':{}},'client_update_required'),({'registers':{}},'output_unavailable'),({'registers':{'8':{'available':True,'emulated':True}}},'output_unavailable')]:
baseline=copy.deepcopy(self.observed);self.observed.update(patch)
self.assertEqual(self.control.observation(self.component)['reason'],reason)
with self.assertRaises(PermissionError):self.control.issue(self.component,'start')
self.observed=baseline
self.component['hardware_outputs']=[]
with self.assertRaises(PermissionError):self.control.issue(self.component,'stop')
self.bridge.publish_event.assert_not_called()
def test_dispatch_once_with_deadline_and_no_optimistic_confirmation(self):
result=self.control.issue(self.component,'start')
self.assertFalse(result['execution_confirmed'])
self.bridge.publish_event.assert_called_once_with(22,'start','Fixture',expires_in_ms=5000)
with self.assertRaises(PermissionError):self.control.issue(self.component,'start')
self.now+=2;self.component['groups']['active']['value']['active']=0
with self.assertRaises(PermissionError):self.control.issue(self.component,'start')
self.control.issue(self.component,'stop')
def test_schedule_and_conditions_preserve_each_other(self):
element={'triggers':{'start':{'type':'push'},'activity_schedules':[{'days_week':[1]}]}}
apply_value(element,{'activity':{'activity_schedules':[{'days_week':[2]}]}})
self.assertEqual(element['triggers']['start'],{'type':'push'})
apply_value(element,{'triggers':{'stop':{'type':'push'}}})
self.assertEqual(element['triggers']['activity_schedules'],[{'days_week':[2]}])
self.assertEqual(element['triggers']['stop'],{'type':'push'})
class ObservationTest(unittest.TestCase):
def test_old_observations_cannot_replace_fresh_hmi_state(self):
import time
from bridge import BridgeState
state=BridgeState();state.set_mqtt_connected(True)
now=int(time.time()*1000)
payload={'emitted_at':now,'components':{'22':{'rest_duration':10}},'capabilities':{'push_expiry_v1':True}}
self.assertTrue(state.observe_hmi(payload))
self.assertFalse(state.observe_hmi(dict(payload,emitted_at=now-1)))
# Compatibility updates are deliberately separate from HMI authority.
state.update_components({'components':{'22':{'rest_duration':999}}})
self.assertEqual(state.hmi_observation(22)['component']['rest_duration'],10)
self.assertFalse(state.observe_hmi(dict(payload,emitted_at=float('nan'))))
self.assertTrue(state.observe_hmi({'observed_at_ms':now,'payload':{'values':[{'id':8,'available':True}]}},registers=True))
state.observe_hmi({'observed_at_ms':now-1,'payload':{'values':[{'id':8,'available':False}]}},registers=True)
self.assertTrue(state.hmi_observation(22)['registers']['8']['available'])
state.set_mqtt_connected(False)
self.assertFalse(state.hmi_observation(22)['fresh'])
self.assertEqual(state.hmi_observation(22)['registers'],{})
def test_retained_packet_does_not_authorize_control(self):
import json,time
from types import SimpleNamespace
from bridge import BridgeState,MqttBridge
state=BridgeState();state.set_mqtt_connected(True)
bridge=MqttBridge.__new__(MqttBridge);bridge.state=state;bridge.register_topic='fixture/registers'
packet={'components':{'22':{'rest_duration':15}},'emitted_at':int(time.time()*1000),'capabilities':{'push_expiry_v1':True}}
bridge._on_message(None,None,SimpleNamespace(topic='fixture/plays',retain=True,payload=json.dumps(packet).encode()))
self.assertFalse(state.hmi_observation(22)['fresh'])
self.assertEqual(state.get_component(22)['rest_duration'],15)

View File

@ -1,131 +0,0 @@
import io
import json
import sys
import tempfile
import time
import unittest
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parents[1] / 'dashboard_bridge_core/backend'))
from offline_edit.runtime import Runtime
class Handler:
def __init__(self, path, method='GET', value=None, headers=None):
self.path, self.command = path, method
body = json.dumps(value).encode() if value is not None else b''
self.rfile = io.BytesIO(body)
self.client_address = ('127.0.0.1', 12345)
self.headers = {'Host':'127.0.0.1:8787', 'Origin':'http://127.0.0.1:8787',
'Content-Type':'application/json', 'Content-Length':str(len(body))}
self.headers.update(headers or {})
self.result, self.code = None, None
def send_json(self, value, code=200): self.result, self.code = value, code
class RuntimeTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory(); root = Path(self.tmp.name)
native = root / 'native.json'; native.write_text(json.dumps({'id':109,'username':'fixture-edge','password':'fixture-only','mqtt':{'prefix':'tenant/fixture'}}))
config = {'native_config_path':str(native),'database':str(root/'edits.sqlite3'),
'cloud_api_url':'http://127.0.0.1:8000/api','native_base_url':'http://127.0.0.1:8000','assets':str(root)}
self.config_path = root/'config.json'; self.config_path.write_text(json.dumps(config))
self.notifications=[]; self.runtime=Runtime(self.config_path,lambda *args,**kwargs:self.notifications.append(args))
now=int(time.time()*1000)
self.runtime.store.ingest({'schema_version':1,'device_id':109,'components':[{'id':22,'title':'Fixture','grant_id':'grant','grant_expires_at':now//1000+3600,'generator_type':'sync',
'anchor':{'id':'anchor','server_time_ms':now},'groups':{'duration':{'value':{'duration':15},'clock':{'revision':1}},'active':{'value':{'active':1},'clock':{'revision':1}}}}]})
def tearDown(self): self.tmp.cleanup()
def test_write_requires_local_host_origin_and_operator_session(self):
for headers in [{'Host':'attacker.example:8787'}, {'Origin':'http://attacker.example'}, {'X-HMI-Session':'wrong'}]:
h=Handler('/hmi/api/settings','POST',{'component_id':22,'group':'duration','value':{'duration':60}},headers)
self.runtime.handle(h); self.assertEqual(h.code,403)
self.assertEqual(self.runtime.store.pending(),[])
def test_native_proxy_preserves_geometry_capability_and_separates_cache(self):
from unittest.mock import Mock
self.runtime._request=Mock(return_value={'layouts':[]})
headers={'User-Agent':'it-screen/5.1.60','X-Edge-Client-Version':'5.1.60','Authorization':'must-not-forward'}
self.runtime.native('/v2/device/layout','',headers)
self.assertEqual(self.runtime._request.call_args.kwargs['headers'],{'User-Agent':'it-screen/5.1.60','X-Edge-Client-Version':'5.1.60'})
self.runtime._request.side_effect=OSError('offline')
self.assertEqual(self.runtime.native('/v2/device/layout','',headers),{'layouts':[]})
with self.assertRaises(OSError):self.runtime.native('/v2/device/layout','',dict(headers,**{'X-Edge-Client-Version':'5.1.61'}))
def test_immediate_route_checks_grant_session_and_never_queues(self):
from unittest.mock import Mock
self.runtime.control=Mock()
self.runtime.control.issue.return_value={'status':'accepted','execution_confirmed':False}
for component_id,headers in [(22,{}),(999,{'X-HMI-Session':self.runtime.session})]:
handler=Handler('/hmi/api/event','POST',{'component_id':component_id,'action':'start'},headers)
self.runtime.handle(handler)
self.assertEqual(handler.code,403)
self.runtime.control.issue.assert_not_called()
handler=Handler('/hmi/api/event','POST',{'component_id':22,'action':'start'},{'X-HMI-Session':self.runtime.session})
self.runtime.handle(handler);self.assertEqual(handler.code,200)
self.assertFalse(handler.result['execution_confirmed'])
self.assertEqual(self.runtime.store.pending(),[])
def test_hardware_actions_are_not_settings_or_retryable(self):
h=Handler('/hmi/api/settings','POST',{'component_id':22,'group':'start','value':{'active':1}}, {'X-HMI-Session':self.runtime.session})
self.runtime.handle(h);self.assertEqual(h.code,422);self.assertEqual(self.notifications,[])
def test_offline_native_document_uses_only_pending_overlay(self):
canonical={'layouts':[{'frames':[{'playlists':[{'elements':[{'id':22,'duration':15,'active':0}]}]}]}]}
self.runtime._cache('native_frames',canonical)
self.runtime._request=lambda *args,**kwargs: (_ for _ in ()).throw(OSError('offline'))
self.runtime.store.edit(22,'duration',{'duration':120})
result=self.runtime.native('/v2/device/layout','')
self.assertEqual(result['layouts'][0]['frames'][0]['playlists'][0]['elements'][0],{'id':22,'duration':120,'active':0})
with self.assertRaises(PermissionError):self.runtime.native('/v2/device/reboot','')
def test_durable_save_survives_broker_outage_and_notifies_on_restart(self):
self.runtime.publish_invalidation=lambda *args,**kwargs: (_ for _ in ()).throw(RuntimeError('broker offline'))
h=Handler('/hmi/api/settings','POST',{'component_id':22,'group':'duration','value':{'duration':120}}, {'X-HMI-Session':self.runtime.session})
self.runtime.handle(h);self.assertEqual(h.code,200);self.assertEqual(h.result['application_status'],'pending');self.assertTrue(self.runtime.sync_event.is_set())
restarted=Runtime(self.config_path,lambda *args,**kwargs:self.notifications.append(args))
self.assertEqual(len(restarted.store.pending()),1)
self.assertTrue(restarted.notify_desired())
self.assertEqual(self.notifications[0][0],'tenant/fixture/client/sub/action/fixture-edge')
self.assertEqual(self.notifications[0][1]['model'],'config')
self.assertTrue(restarted.notify_desired());self.assertEqual(len(self.notifications),1)
def test_ack_and_native_fallback_commit_together(self):
document={'layouts':[{'frames':[{'playlists':[{'elements':[{'id':22,'duration':15,'active':0,'execution_eligibility':{'eligible':False}}]}]}]}]}
self.runtime._cache('native_frames',document)
operation=self.runtime.store.edit(22,'duration',{'duration':120})
self.runtime.store.acknowledge({'operation_id':operation['operation_id'],'component_id':22,'group':'duration','status':'accepted',
'canonical':{'value':{'duration':120},'clock':{'revision':2}}})
restarted=Runtime(self.config_path,lambda *args,**kwargs:None)
restarted._request=lambda *args,**kwargs: (_ for _ in ()).throw(OSError('offline'))
value=restarted.native('/v2/device/layout','')['layouts'][0]['frames'][0]['playlists'][0]['elements'][0]
self.assertEqual(restarted.store.pending(),[])
self.assertEqual(value['duration'],120)
self.assertEqual(value['active'],0)
def test_remote_duration_refreshes_native_cache_and_notifies_once(self):
import copy
document={'layouts':[{'frames':[{'playlists':[{'elements':[{'id':22,'duration':15,'active':0,'execution_eligibility':{'eligible':False}}]}]}]}]}
self.runtime._cache('native_frames',document)
self.runtime.notify_desired();self.notifications.clear()
component=copy.deepcopy(self.runtime.store.view(22));component.pop('pending')
component['groups']['duration']={'value':{'duration':77},'clock':{'revision':2}}
snapshot={'schema_version':1,'device_id':109,'components':[component]}
self.runtime._request=lambda *args,**kwargs:snapshot
self.runtime.synchronize();self.assertTrue(self.runtime.notify_desired())
self.assertEqual(len(self.notifications),1)
self.runtime.synchronize();self.runtime.notify_desired();self.assertEqual(len(self.notifications),1)
self.runtime._request=lambda *args,**kwargs:(_ for _ in ()).throw(OSError('offline'))
element=self.runtime.native('/v2/device/layout','')['layouts'][0]['frames'][0]['playlists'][0]['elements'][0]
self.assertEqual(element['duration'],77);self.assertEqual(element['active'],0)
older=copy.deepcopy(snapshot);older['components'][0]['groups']['duration']={'value':{'duration':15},'clock':{'revision':1}}
self.runtime.store.ingest(older)
self.assertEqual(self.runtime.store.view(22)['groups']['duration']['value']['duration'],77)
def test_plaintext_public_upstream_is_rejected(self):
for url in ['http://public.example','http://8.8.8.8','https://user:secret@example.test','file:///etc/passwd']:
with self.assertRaises(ValueError):Runtime._origin(url)
if __name__=='__main__':unittest.main()

View File

@ -1,120 +0,0 @@
import copy
import importlib.util
import sqlite3
import tempfile
import unittest
from pathlib import Path
ROOT = Path(__file__).parents[1] / 'dashboard_bridge_core/backend/offline_edit/store.py'
spec = importlib.util.spec_from_file_location('offline_store', ROOT)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
def snapshot():
groups = {'duration': {'duration': 15}, 'active': {'active': 1},
'schedule': {key: None for key in module.GROUPS['schedule']},
'conditions': {'triggers': {}, 'start_condition_operator': 'AND', 'per_hour': 0}}
return {'schema_version': 1, 'device_id': 109, 'components': [{
'id': 22, 'title': 'Fixture command, no hardware', 'grant_id': 'grant-fixture',
'grant_expires_at': 200000, 'generator_type': 'sync',
'anchor': {'id': 'anchor-fixture', 'server_time_ms': 100000000},
'groups': {name: {'value': value, 'clock': {'revision': 1}} for name, value in groups.items()}
}]}
class OfflineStoreTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.path = Path(self.tmp.name) / 'edits.sqlite3'
self.wall, self.mono, self.boot = 100000., 500., 'boot-a'
self.store = self.reopen()
self.store.ingest(snapshot())
def tearDown(self):
self.tmp.cleanup()
def reopen(self):
return module.Store(self.path, lambda: self.wall, lambda: self.mono, lambda: self.boot)
def receipt(self, operation, revision=2, status='accepted'):
return {'operation_id': operation['operation_id'], 'component_id': 22, 'group': operation['group'],
'status': status, 'canonical': {'value': operation['value'], 'clock': {'revision': revision}}}
def test_offline_commit_and_process_restart_preserve_outbox(self):
self.mono += 10; self.wall += 10
op = self.store.edit(22, 'duration', {'duration': 120})
self.assertTrue(op['clock_trusted'])
self.assertEqual(op['created_at_ms'], 100010000)
restarted = self.reopen()
self.assertEqual(restarted.pending(), [op])
self.assertEqual(restarted.view(22)['groups']['duration']['value'], {'duration': 120})
restarted.acknowledge(self.receipt(op))
restarted.acknowledge(self.receipt(op))
self.assertEqual(restarted.pending(), [])
self.assertEqual(restarted.view(22)['groups']['duration']['clock']['revision'], 2)
def test_snapshot_does_not_clobber_independent_or_newer_pending_edits(self):
first = self.store.edit(22, 'duration', {'duration': 120})
second = self.store.edit(22, 'duration', {'duration': 240})
incoming = snapshot(); incoming['components'][0]['groups']['active']['value']['active'] = 0
self.store.ingest(incoming)
self.store.acknowledge(self.receipt(first))
view = self.store.view(22)
self.assertEqual(view['groups']['duration']['value']['duration'], 240)
self.assertEqual(view['groups']['active']['value']['active'], 0)
self.assertEqual(self.store.pending(), [second])
self.store.acknowledge(self.receipt(second, 3))
self.assertEqual(self.store.view(22)['groups']['duration']['value']['duration'], 240)
def test_device_change_and_removed_scope_do_not_resurrect_operations(self):
self.store.edit(22, 'active', {'active': 0})
incoming = snapshot(); incoming['device_id'] = 999
with self.assertRaises(ValueError): self.store.ingest(incoming)
incoming = snapshot(); incoming['components'] = []
self.store.ingest(incoming)
self.assertEqual(self.store.pending(), [])
with self.assertRaises(PermissionError): self.store.view(22)
def test_clock_jump_or_reboot_is_explicitly_untrusted(self):
self.wall += 1000
op = self.store.edit(22, 'duration', {'duration': 20})
self.assertFalse(op['clock_trusted'])
self.store.acknowledge(self.receipt(op, status='clock_conflict'))
self.assertEqual(self.store.pending(), [])
self.assertEqual(self.store.view(22)['pending'][0]['status'], 'clock_conflict')
self.boot = 'boot-b'; self.mono = 1
self.assertFalse(self.reopen().edit(22, 'active', {'active': 0})['clock_trusted'])
def test_invalid_edits_cannot_enter_outbox(self):
for group, value in [('duration', {'duration': 3601}), ('active', {'active': True}),
('start', {'value': True}), ('duration', {'duration': 20, 'id': 999})]:
with self.assertRaises(ValueError): self.store.edit(22, group, value)
self.assertEqual(self.store.pending(), [])
def test_overlay_changes_only_existing_target_and_pending_group(self):
self.store.edit(22, 'duration', {'duration': 120})
canonical = {'layouts': [{'frames': [{'playlists': [{'elements': [{'id': 22, 'duration': 15, 'active': 0}, {'id': 99, 'duration': 5}]}]}]}]}
result = self.store.overlay(canonical)
items = result['layouts'][0]['frames'][0]['playlists'][0]['elements']
self.assertEqual(items, [{'id': 22, 'duration': 120, 'active': 0}, {'id': 99, 'duration': 5}])
self.assertEqual(canonical['layouts'][0]['frames'][0]['playlists'][0]['elements'][0]['duration'], 15)
def test_interrupted_sql_write_does_not_apply_half_an_edit(self):
with sqlite3.connect(self.path) as db:
db.execute("CREATE TRIGGER fail_outbox BEFORE INSERT ON outbox BEGIN SELECT RAISE(ABORT,'fixture interruption'); END")
with self.assertRaises(sqlite3.IntegrityError): self.store.edit(22, 'duration', {'duration': 120})
self.assertEqual(self.reopen().view(22)['groups']['duration']['value']['duration'], 15)
def test_local_activity_cannot_bypass_output_eligibility(self):
self.store.edit(22, 'active', {'active': 1})
native = {'layouts': [{'frames': [{'playlists': [{'elements': [{'id': 22, 'active': 0, 'execution_eligibility': {'eligible': False, 'reason': 'command_output_unbound'}}]}]}]}]}
result = self.store.overlay(native)
self.assertEqual(result['layouts'][0]['frames'][0]['playlists'][0]['elements'][0]['active'], 0)
def test_expired_grant_is_not_a_local_permission(self):
self.wall = 200001
with self.assertRaises(PermissionError): self.store.edit(22, 'active', {'active': 0})
if __name__ == '__main__': unittest.main()

View File

@ -7,7 +7,6 @@ import signal
import socket import socket
import subprocess import subprocess
import shutil import shutil
import tempfile
import threading import threading
import time import time
from pathlib import Path from pathlib import Path
@ -23,8 +22,6 @@ SUPPORTED_INPUT_SCHEMES = {"rtsp"}
SUPPORTED_OUTPUT_SCHEMES = {"rtsp", "rtmp", "srt", "udp"} SUPPORTED_OUTPUT_SCHEMES = {"rtsp", "rtmp", "srt", "udp"}
MAX_STREAMS = 8 MAX_STREAMS = 8
PREVIEW_TTL_SEC = 10 * 60 PREVIEW_TTL_SEC = 10 * 60
STARTUP_GUARD_SEC = 0.75
MAX_FORWARD_RESTARTS = 2
FFMPEG_BINARY = "/usr/bin/ffmpeg" FFMPEG_BINARY = "/usr/bin/ffmpeg"
FFPROBE_BINARY = "/usr/bin/ffprobe" FFPROBE_BINARY = "/usr/bin/ffprobe"
@ -91,12 +88,6 @@ def video_arguments(payload):
] ]
def sanitize_process_error(value):
value = re.sub(r"([a-z][a-z0-9+.-]*://)[^/@\s]+@", r"\1[redacted]@", str(value or ""), flags=re.I)
value = re.sub(r"(srt://[^?\s]+)\?[^\s]+", r"\1?[redacted]", value, flags=re.I)
return value.strip()[-2048:]
class StreamManager: class StreamManager:
def __init__(self, device=None, prefix=None): def __init__(self, device=None, prefix=None):
self.device = device or edge_id() self.device = device or edge_id()
@ -109,7 +100,6 @@ class StreamManager:
self.operation_lock = threading.RLock() self.operation_lock = threading.RLock()
self.control_socket = None self.control_socket = None
self.supervisor_stop = threading.Event() self.supervisor_stop = threading.Event()
self.last_failure = None
def publish(self, payload): def publish(self, payload):
subprocess.run([ subprocess.run([
@ -130,19 +120,8 @@ class StreamManager:
code = process.poll() code = process.poll()
if code is None: if code is None:
continue continue
error = self.read_error_log(record) stopped.append({"stream_id": stream_id, "exit_code": code})
stopped.append({"stream_id": stream_id, "exit_code": code, "error": error})
self.remember_failure(stream_id, code, error)
if (record.get("kind") == "forward" and record.get("expires_at", 0) > now
and record.get("restart_count", 0) < MAX_FORWARD_RESTARTS):
self.close_error_log(record)
record["restart_count"] = record.get("restart_count", 0) + 1
record["error_log"] = tempfile.TemporaryFile(mode="w+b")
record["process"] = self.spawn(record["command"], stderr=record["error_log"])
stopped[-1]["restarted"] = True
continue
self.processes.pop(stream_id, None) self.processes.pop(stream_id, None)
self.close_error_log(record)
self.write_status() self.write_status()
return stopped return stopped
@ -163,13 +142,11 @@ class StreamManager:
stream_id: { stream_id: {
"kind": record.get("kind", "forward"), "kind": record.get("kind", "forward"),
"expires_at": int(record.get("expires_at", 0)), "expires_at": int(record.get("expires_at", 0)),
"restart_count": int(record.get("restart_count", 0)),
} }
for stream_id, record in self.processes.items() for stream_id, record in self.processes.items()
}, },
"active_count": len(self.processes), "active_count": len(self.processes),
"max_streams": MAX_STREAMS, "max_streams": MAX_STREAMS,
"last_failure": self.last_failure,
}), encoding="utf-8") }), encoding="utf-8")
os.replace(temporary, STATUS_PATH) os.replace(temporary, STATUS_PATH)
@ -200,76 +177,27 @@ class StreamManager:
"-application", "lowdelay", "-frame_duration", "20", "-application", "lowdelay", "-frame_duration", "20",
*output_arguments(output_url), *output_arguments(output_url),
] ]
error_log = tempfile.TemporaryFile(mode="w+b") self.processes[stream_id] = {
process = self.spawn(command, stderr=error_log) "process": self.spawn(command),
record = {
"process": process,
"error_log": error_log,
"kind": "forward", "kind": "forward",
"expires_at": expires_at, "expires_at": expires_at,
"input_url": input_url, "input_url": input_url,
"output_url": output_url, "output_url": output_url,
"low_latency": low_latency, "low_latency": low_latency,
"profile": profile, "profile": profile,
"command": command,
"restart_count": 0,
} }
self.processes[stream_id] = record
deadline = time.monotonic() + STARTUP_GUARD_SEC
while process.poll() is None and time.monotonic() < deadline:
time.sleep(0.05)
if process.poll() is not None:
self.processes.pop(stream_id, None)
error = self.read_error_log(record)
self.remember_failure(stream_id, process.returncode, error)
self.close_error_log(record)
self.write_status()
message = f"Camera stream process exited during startup (code {process.returncode})"
if error:
message += f": {error}"
raise RuntimeError(message)
self.write_status() self.write_status()
return {"action": "start", "status": "ok", "stream_id": stream_id, "already_running": False} return {"action": "start", "status": "ok", "stream_id": stream_id, "already_running": False}
def spawn(self, command, stderr=subprocess.DEVNULL): def spawn(self, command):
return subprocess.Popen( return subprocess.Popen(
command, command,
stdin=subprocess.DEVNULL, stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
stderr=stderr, stderr=subprocess.DEVNULL,
start_new_session=True, start_new_session=True,
) )
@staticmethod
def read_error_log(record):
error_log = record.get("error_log")
if error_log is None:
return ""
try:
error_log.flush()
error_log.seek(0)
return sanitize_process_error(error_log.read().decode("utf-8", errors="replace"))
except (OSError, ValueError):
return ""
@staticmethod
def close_error_log(record):
error_log = record.pop("error_log", None)
if error_log is not None:
try:
error_log.close()
except OSError:
pass
def remember_failure(self, stream_id, exit_code, error):
self.last_failure = {
"stream_id": stream_id,
"exit_code": exit_code,
"error": error,
"at": int(time.time()),
}
print(json.dumps({"event": "camera_stream_process_failed", **self.last_failure}, separators=(",", ":")), flush=True)
def preview_start(self, payload): def preview_start(self, payload):
stream_id = validate_stream_id(payload.get("stream_id")) stream_id = validate_stream_id(payload.get("stream_id"))
expires_at = time.time() + PREVIEW_TTL_SEC expires_at = time.time() + PREVIEW_TTL_SEC
@ -405,8 +333,6 @@ class StreamManager:
except subprocess.TimeoutExpired: except subprocess.TimeoutExpired:
os.killpg(process.pid, signal.SIGKILL) os.killpg(process.pid, signal.SIGKILL)
process.wait(timeout=2) process.wait(timeout=2)
if record is not None:
self.close_error_log(record)
self.write_status() self.write_status()
return {"action": "stop", "status": "ok", "stream_id": stream_id} return {"action": "stop", "status": "ok", "stream_id": stream_id}

View File

@ -92,7 +92,6 @@ class IpStreamTest(unittest.TestCase):
self.assertEqual(command[command.index("-c:a") + 1], "libopus") self.assertEqual(command[command.index("-c:a") + 1], "libopus")
self.assertEqual(command[command.index("-application") + 1], "lowdelay") self.assertEqual(command[command.index("-application") + 1], "lowdelay")
self.assertNotIn(payload["output_url"], json.dumps(manager.status())) self.assertNotIn(payload["output_url"], json.dumps(manager.status()))
manager.close_error_log(manager.processes["cdn-camera-a1b2"])
def test_forward_low_latency_profile_transcodes_without_b_frames(self): def test_forward_low_latency_profile_transcodes_without_b_frames(self):
manager = stream.StreamManager("g-box-test", "it-screen/dev") manager = stream.StreamManager("g-box-test", "it-screen/dev")
@ -116,40 +115,6 @@ class IpStreamTest(unittest.TestCase):
self.assertEqual(command[command.index("-profile:v") + 1], "baseline") self.assertEqual(command[command.index("-profile:v") + 1], "baseline")
self.assertEqual(command[command.index("-g") + 1], "25") self.assertEqual(command[command.index("-g") + 1], "25")
self.assertEqual(command[command.index("-b:v") + 1], "600k") self.assertEqual(command[command.index("-b:v") + 1], "600k")
manager.close_error_log(manager.processes["cdn-camera-a1b2"])
def test_forward_rejects_an_ffmpeg_process_that_exits_during_startup(self):
manager = stream.StreamManager("g-box-test", "it-screen/dev")
process = MagicMock(returncode=1)
process.poll.return_value = 1
manager.spawn = MagicMock(return_value=process)
manager.write_status = MagicMock()
def write_error(command, stderr=stream.subprocess.DEVNULL):
stderr.write(b"Failed to open rtsp://camera-user:camera-password@camera.local/stream2\n")
stderr.flush()
return process
manager.spawn.side_effect = write_error
with self.assertRaisesRegex(RuntimeError, "Camera stream process exited during startup") as error:
manager.start({
"stream_id": "cdn-camera-a1b2",
"input_url": "rtsp://camera-user:camera-password@camera.local/stream2",
"output_url": "srt://cdn.dev.iomatex.com:8890?streamid=publish:edge/device/camera:user:secret",
"ttl_sec": 600,
})
self.assertNotIn("camera-password", str(error.exception))
self.assertNotIn("user:secret", str(error.exception))
self.assertEqual(manager.processes, {})
def test_console_returns_the_sanitized_stream_service_error(self):
console = MODULE_PATH.parents[1] / "stage_ui" / "console_core" / "backend" / "app.py"
source = console.read_text(encoding="utf-8")
self.assertIn('error = str(result.get("error") or "").strip()', source)
self.assertIn('raise RuntimeError(error or "Unable to start camera media operation")', source)
self.assertIn('if parsed.path == "/api/camera-stream/stop":', source)
self.assertIn('publish_camera_preview({"action": "stop", "stream_id": stream_id})', source)
def test_supervisor_reaps_expired_and_dead_processes_without_status_request(self): def test_supervisor_reaps_expired_and_dead_processes_without_status_request(self):
manager = stream.StreamManager("g-box-test", "it-screen/dev") manager = stream.StreamManager("g-box-test", "it-screen/dev")
@ -160,7 +125,7 @@ class IpStreamTest(unittest.TestCase):
dead.poll.return_value = 7 dead.poll.return_value = 7
manager.processes = { manager.processes = {
"expired": {"process": expired, "kind": "forward", "expires_at": 1}, "expired": {"process": expired, "kind": "forward", "expires_at": 1},
"dead": {"process": dead, "kind": "preview", "expires_at": 0}, "dead": {"process": dead, "kind": "forward", "expires_at": 0},
} }
manager.write_status = MagicMock() manager.write_status = MagicMock()
@ -169,39 +134,8 @@ class IpStreamTest(unittest.TestCase):
self.assertEqual(manager.processes, {}) self.assertEqual(manager.processes, {})
self.assertEqual({item["stream_id"] for item in stopped}, {"expired", "dead"}) self.assertEqual({item["stream_id"] for item in stopped}, {"expired", "dead"})
self.assertEqual(manager.last_failure["stream_id"], "dead")
self.assertEqual(manager.last_failure["exit_code"], 7)
killpg.assert_called_once_with(1001, stream.signal.SIGTERM) killpg.assert_called_once_with(1001, stream.signal.SIGTERM)
def test_supervisor_restarts_a_failed_forward_within_its_ttl(self):
manager = stream.StreamManager("g-box-test", "it-screen/dev")
dead = MagicMock(pid=1002)
dead.poll.return_value = 1
replacement = MagicMock(pid=1003)
replacement.poll.return_value = None
error_log = tempfile.TemporaryFile(mode="w+b")
error_log.write(b"srt://cdn.example:8891?streamid=secret Input/output error")
manager.processes = {
"camera": {
"process": dead,
"error_log": error_log,
"kind": "forward",
"expires_at": stream.time.time() + 60,
"restart_count": 0,
"command": [stream.FFMPEG_BINARY, "-i", "rtsp://camera/stream2"],
},
}
manager.spawn = MagicMock(return_value=replacement)
manager.write_status = MagicMock()
stopped = manager.reap()
self.assertTrue(stopped[0]["restarted"])
self.assertEqual(manager.processes["camera"]["restart_count"], 1)
self.assertIs(manager.processes["camera"]["process"], replacement)
self.assertNotIn("streamid=secret", manager.last_failure["error"])
manager.close_error_log(manager.processes["camera"])
def test_run_starts_periodic_supervisor(self): def test_run_starts_periodic_supervisor(self):
source = MODULE_PATH.read_text(encoding="utf-8") source = MODULE_PATH.read_text(encoding="utf-8")
self.assertIn('target=self.supervise, name="ip-stream-supervisor"', source) self.assertIn('target=self.supervise, name="ip-stream-supervisor"', source)

View File

@ -1,3 +1,3 @@
{ {
"version": "1.0.10" "version": "1.0.8"
} }

Binary file not shown.

View File

@ -1 +1 @@
5e14d2cabd2821620e03467bc5d8bc98d87895d3f6f22c3f82a9cf414c6d13d0 itscreen 52d018fe3580f903d7b46fd94bb22d8c88aa321156107eb66998926a218ffcc1 itscreen

View File

@ -1 +1 @@
5.1.55 5.1.42

View File

@ -1,18 +1,14 @@
{ {
"schema_version": 1, "schema_version": 1,
"client_version": "5.1.55", "client_version": "5.1.42",
"stage_version": "1.0.40", "stage_version": "1.0.33",
"platform": "linux", "platform": "linux",
"architecture": "arm64", "architecture": "arm64",
"source_repository": "https://git.iomatex.com/Development/It-screenClient.git", "source_repository": "https://git.it-screen.com/Development/It-screenClient.git",
"source_branch": "iomatex_dev", "source_branch": "iomatex_dev",
"source_commit": "c4739d5dd87ba43c94578af0c6745b0086829175", "source_commit": "c75170b64ccff88b0a80edf9e21d1382960c9834",
"binary": "itscreen", "binary": "itscreen",
"sha256": "5e14d2cabd2821620e03467bc5d8bc98d87895d3f6f22c3f82a9cf414c6d13d0", "sha256": "52d018fe3580f903d7b46fd94bb22d8c88aa321156107eb66998926a218ffcc1",
"assembly_method": "Clean isolated release build from git archive using iomatex-debian-dev:local; --version and linked libraries verified on Debian 11 ARM64", "assembly_method": "Clean release cross-build from git archive; Debian 11 ARM64 Qt 5.15.2 sysroot; ldd and executable version verified on ARM64 bench",
"native_version_code": 5010055, "native_version_code": 5010042
"release_revision": 2,
"verified_version_output": "5.1.55 5010055",
"artifact_role": "legacy archive only; first installation resolves Download manifest",
"installation_feed": "https://git.iomatex.com/An-J/DOWNLOAD_IOMATEX_APP/raw/branch/main/edge-client/debian/latest.json"
} }

View File

@ -442,11 +442,6 @@ install_qt_packages() {
libqt5texttospeech5 \ libqt5texttospeech5 \
libqt5serialbus5 libqt5serialbus5
# The Player cannot finish loading its QML settings or answer registration
# requests without these modules.
run_long "Install required Player QML modules" 1800 apt-get install -y --no-remove \
qml-module-qtquick-window2 qml-module-qtquick-layouts qml-module-qtquick-controls
install_packages_best_effort "Install Qt extras" 1800 \ install_packages_best_effort "Install Qt extras" 1800 \
lxterminal openbox wmctrl xdotool \ lxterminal openbox wmctrl xdotool \
libqt5serialbus5-bin \ libqt5serialbus5-bin \
@ -518,9 +513,11 @@ cleanup_legacy_x11_hacks() {
install_itscreen_binary() ( install_itscreen_binary() (
set -e set -e
step "Install itscreen binary" step "Install itscreen binary"
# One Download owner for initial provisioning and subsequent automatic updates. local src
# A failed download aborts the stage; never silently install the bundled legacy ELF. src=$(mktemp /userdata/.iomatex-client.XXXXXX)
python3 "$SCRIPT_DIR/updater/client_updater.py" --bootstrap trap 'rm -f "$src"' EXIT
python3 "$IOMATEX_PROJECT_ROOT/offline/git_delivery.py" fetch stage_itscreen/itscreen "$src"
install -m 0755 -o "$ITS_USER" -g "$ITS_GROUP" "$src" "$ITS_BINARY"
) )
install_sudoers() { install_sudoers() {
@ -1569,7 +1566,6 @@ POWER_WAKE
install_x11_session_scripts install_x11_session_scripts
install_recovery_assets install_recovery_assets
install_systemd_unit install_systemd_unit
bash "$SCRIPT_DIR/updater/install.sh"
enable_managed_services enable_managed_services
post_install_self_test post_install_self_test
flush_filesystems flush_filesystems

View File

@ -1,23 +0,0 @@
import json
import tempfile
import unittest
from pathlib import Path
from verify_client_release import verify
class EmbeddedReleaseTest(unittest.TestCase):
def test_matching_and_mislabeled_binaries(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
manifest = root / 'release.json'
manifest.write_text(json.dumps({'client_version': '5.1.55', 'native_version_code': 5010055}))
binary = root / 'client'
for output, accepted in [('5.1.55 5010055', True), ('5.1.54 5010054', False), ('5.1.55 5010054', False), ('', False)]:
with self.subTest(output=output):
binary.write_text('#!/bin/sh\nprintf "%s\\n" "' + output + '"\n')
binary.chmod(0o755)
if accepted:
self.assertEqual(verify(binary, manifest), output)
else:
with self.assertRaises(ValueError):
verify(binary, manifest)

View File

@ -1,51 +0,0 @@
# Debian client updater
One privileged owner implements the existing AppUpdater newline JSON contract
on /tmp/itsupdater. Only root and the itscreen UID can connect. No client
credentials are sent to Download. Endpoint is fixed to the public Debian feed
on git.iomatex.com; redirects and arbitrary download hosts are rejected.
The platform checkbox is_check_update calls Updater.setActiveUpdate(0|1),
which sends set/active_update. The service saves it under
/var/lib/iomatex/client-update/settings.json (default off until configured).
Enabling triggers a check; recurring interval is 900 seconds. Disabling before
installation begins prevents replacement even after a download. Once the client
has been stopped, installation or rollback completes regardless of later changes.
get returns link, period, active_update, installed_version, ready_version,
device_id, state_update and progress_download. download_update checks; update
manually installs even with automatic updates off. quit cannot terminate the
privileged system service. Caller-supplied installed versions are ignored.
Compare native build first, then release_revision for same-version corrections.
If the current binary hash already matches the feed, record provenance without
reinstalling. Candidate must have exact size/hash, ARM64 ELF header and matching
--version output. /userdata stores candidate/rollback files. Replacement uses a
temporary file on the destination filesystem and os.replace. The Console shared
installer lock serializes replacement. A stopped/maintenance client is not started.
Readiness requires the new executable and an X11 client window within 90 seconds.
This is a startup check, not a proof of all media playback. Failed startup restores
the previous binary. An on-disk transaction also restores it after daemon/OS
interruption. The service never reboots the operating system.
Install: bash stage_itscreen/updater/install.sh (also part of stage_itscreen).
Tests: python3 -m unittest discover -s stage_itscreen/updater -p test_client_updater.py
State/diagnostics: status.json, installed.json in /var/lib/iomatex/client-update;
journalctl -u iomatex-client-updater. Existing Console cloud-registration status
continues to query the running client over its existing MQTT contract.
First deployment requires Console stage 1.0.38; subsequent client updates come
from Download. OS/Console updates remain separate. Do not publish an artifact
without a successful native --version check. Stage version is not client version.
## Initial provisioning (OS stage 1.0.39+)
The stage calls this same owner with `--bootstrap` after installing dependencies
and creating the client account/directories. It resolves the public manifest,
downloads/validates the current ELF and atomically installs it, even with automatic
updates off. It records the actual Download provenance in installed.json; a
matching/newer existing client is preserved. The stage retains ownership of
service startup and inherits the shared installer lock into this command.
Failure aborts the stage; no legacy repository binary is substituted. Historical
stage_itscreen/itscreen and provenance are archives only, preserved for old URLs.

View File

@ -1,462 +0,0 @@
#!/usr/bin/env python3
"""Debian Download channel; existing AppUpdater newline-JSON socket contract."""
import fcntl
import grp
import hashlib
import json
import logging
import os
from pathlib import Path
import pwd
import queue
import re
import shutil
import socket
import socketserver
import struct
import sys
import subprocess
import tempfile
import threading
import time
import urllib.parse
import urllib.request
FEED = 'https://git.iomatex.com/An-J/DOWNLOAD_IOMATEX_APP/raw/branch/main/edge-client/debian/latest-iomatex.json'
PREFIX = 'https://git.iomatex.com/An-J/DOWNLOAD_IOMATEX_APP/raw/branch/main/edge-client/debian/releases/'
BINARY = Path('/opt/itscreen/bin/itscreen')
STATE = Path('/var/lib/iomatex/client-update')
CACHE = Path('/userdata/iomatex-client-update')
LOCK = Path('/run/lock/iomatex-installer.lock')
SOCKET = '/tmp/itsupdater'
PERIOD = 900
def sync_directory(path):
fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY)
try:
os.fsync(fd)
finally:
os.close(fd)
def write_json(path, data):
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix('.tmp')
with tmp.open('w') as stream:
json.dump(data, stream)
stream.flush()
os.fsync(stream.fileno())
os.chmod(tmp, 0o600)
os.replace(tmp, path)
sync_directory(path.parent)
def read_json(path):
try:
return json.loads(path.read_text())
except FileNotFoundError:
return {}
def digest(path):
with path.open('rb') as stream:
return hashlib.sha256(stream.read()).hexdigest()
def version_code(version):
if not re.fullmatch(r'[0-9]+\.[0-9]+\.[0-9]+', version):
raise ValueError('Invalid client version')
major, minor, patch = map(int, version.split('.'))
if major < 5 or minor >= 100 or patch >= 10000:
raise ValueError('Unsupported client version')
return major * 1000000 + minor * 10000 + patch
def inspect_binary(path):
result = subprocess.run([str(path), '--version'], check=True, capture_output=True,
text=True, timeout=10)
parts = result.stdout.strip().split()
if len(parts) != 2 or int(parts[1]) != version_code(parts[0]):
raise ValueError('Invalid embedded client version')
return parts[0], int(parts[1])
def validate_manifest(data):
if (data.get('schema_version') != 1 or data.get('platform') != 'debian'
or data.get('architecture') != 'arm64' or data.get('artifact_type') != 'elf'
or type(data.get('build_number')) is not int
or data['build_number'] != version_code(data.get('version', ''))):
raise ValueError('Unsupported release manifest')
url = data.get('download_url', '')
parsed = urllib.parse.urlsplit(url)
if (not url.startswith(PREFIX) or parsed.query or parsed.fragment
or not re.fullmatch(re.escape(data['version']) + r'(?:-[A-Za-z0-9._-]+)?/itscreen', url[len(PREFIX):])):
raise ValueError('Untrusted download URL')
if not re.fullmatch(r'[0-9a-f]{64}', data.get('sha256', '')):
raise ValueError('Invalid checksum')
if type(data.get('size_bytes')) is not int or not 100000 <= data['size_bytes'] <= 128*1024*1024:
raise ValueError('Invalid download size')
revision = data.get('release_revision', 1)
if type(revision) is not int or revision < 1:
raise ValueError('Invalid release revision')
return dict(data, release_revision=revision)
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
raise ValueError('Update redirect refused')
def open_url(url):
req = urllib.request.Request(url, headers={'User-Agent': 'IomatexOS-Updater/1.0'})
return urllib.request.build_opener(NoRedirect()).open(req, timeout=30)
class Updater:
def __init__(self, binary=BINARY, state=STATE, cache=CACHE, bootstrap=False):
self.binary, self.state, self.cache = Path(binary), Path(state), Path(cache)
self.state.mkdir(parents=True, exist_ok=True)
self.cache.mkdir(parents=True, exist_ok=True)
self.mutex = threading.RLock()
self.automatic = read_json(self.state/'settings.json').get('active_update', 0) == 1
self.pending = queue.Queue(maxsize=1)
self.listeners = set()
self.phase, self.progress, self.ready = 'init', 0, 0
self.busy = False
self.error = ''
self.device_id = ''
if read_json(self.state/'transaction.json'):
self.version, self.installed = '', 0
else:
try:
self.version, self.installed = inspect_binary(self.binary)
except (OSError, ValueError, subprocess.SubprocessError):
if not bootstrap:
raise
self.version, self.installed = '', 0
def emit(self, key, value):
for handler in list(self.listeners):
handler.send(key, value)
def status(self, phase, error=''):
self.phase, self.error = phase, error
write_json(self.state/'status.json', {'state_update': phase, 'error': error,
'installed_version': self.installed, 'ready_version': self.ready,
'checked_at': int(time.time())})
self.emit('state_update', phase)
def set_automatic(self, value):
if type(value) is not int or value not in (0, 1):
raise ValueError('active_update must be 0 or 1')
with self.mutex:
self.automatic = bool(value)
write_json(self.state/'settings.json', {'active_update': value})
self.emit('active_update', value)
if value:
self.request(False)
def request(self, manual):
if not self.busy:
try:
self.pending.put_nowait(manual)
except queue.Full:
pass
def values(self):
return {'link': FEED, 'period': PERIOD, 'installed_version': self.installed,
'ready_version': self.ready, 'device_id': self.device_id,
'active_update': int(self.automatic), 'state_update': self.phase,
'progress_download': self.progress, 'error': self.error, 'busy': self.busy or not self.pending.empty()}
def newer(self, data):
if data['build_number'] != self.installed:
return data['build_number'] > self.installed
receipt = read_json(self.state/'installed.json')
installed_hash = digest(self.binary)
revision = receipt.get('release_revision', 0) if (
receipt.get('build_number') == self.installed
and receipt.get('sha256') == installed_hash) else 0
return data['release_revision'] > revision and installed_hash != data['sha256']
def download(self, data):
fd, name = tempfile.mkstemp(prefix='candidate-', dir=self.cache)
os.close(fd)
target = Path(name)
try:
with open_url(data['download_url']) as response, target.open('wb') as output:
count, checksum = 0, hashlib.sha256()
while True:
block = response.read(256*1024)
if not block:
break
count += len(block)
if count > data['size_bytes']:
raise ValueError('Download exceeds expected size')
output.write(block)
checksum.update(block)
self.progress = int(count * 100 / data['size_bytes'])
self.emit('progress_download', self.progress)
output.flush()
os.fsync(output.fileno())
if count != data['size_bytes'] or checksum.hexdigest() != data['sha256']:
raise ValueError('Download checksum/size mismatch')
with target.open('rb') as stream:
elf = stream.read(20)
if elf[:6] != b'\x7fELF\x02\x01' or elf[18:20] != b'\xb7\x00':
raise ValueError('Downloaded file is not ARM64 ELF')
target.chmod(0o755)
if inspect_binary(target) != (data['version'], data['build_number']):
raise ValueError('Embedded version differs from manifest')
return target
except Exception:
target.unlink(missing_ok=True)
raise
def replace(self, source):
# Candidate and destination can be on different filesystems.
fd, name = tempfile.mkstemp(prefix='.client-update-', dir=self.binary.parent)
try:
with os.fdopen(fd, 'wb') as out, source.open('rb') as inp:
shutil.copyfileobj(inp, out)
out.flush()
os.fsync(out.fileno())
original = self.binary.stat() if self.binary.exists() else self.binary.parent.stat()
os.chown(name, original.st_uid, original.st_gid)
os.chmod(name, 0o755)
os.replace(name, self.binary)
sync_directory(self.binary.parent)
finally:
Path(name).unlink(missing_ok=True)
def service(self, action):
subprocess.run(['systemctl', action, 'itscreen-x11.service'], check=True,
capture_output=True, timeout=90)
def healthy(self):
# Cover the normal X11/Qt startup period and verify this executable is running.
expected = digest(self.binary)
for _ in range(45):
time.sleep(2)
for executable in Path('/proc').glob('[0-9]*/exe'):
try:
if executable.resolve() == self.binary and digest(executable) == expected:
# Require a mapped playback window, not just a surviving launcher.
result = subprocess.run(['runuser', '-u', 'itscreen', '--', 'env',
'DISPLAY=:0', 'XAUTHORITY=/var/lib/itscreen/.Xauthority',
'xwininfo', '-root', '-tree'], capture_output=True, text=True, timeout=5)
if re.search(r'"it-screen".*\s[1-9][0-9]{2,}x[1-9][0-9]{2,}', result.stdout):
return True
except (OSError, subprocess.SubprocessError):
continue
return False
def recover(self):
transaction = read_json(self.state/'transaction.json')
if not transaction:
return
backup = self.cache/'previous'
if digest(backup) != transaction['previous_sha256']:
raise ValueError('Rollback backup checksum mismatch')
self.service('stop')
self.replace(backup)
self.service('start')
(self.state/'transaction.json').unlink()
sync_directory(self.state)
self.version, self.installed = inspect_binary(self.binary)
def install(self, candidate, data, manual):
with LOCK.open('a') as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
with self.mutex:
if not manual and not self.automatic:
self.status('not_permitted')
return
self.version, self.installed = inspect_binary(self.binary)
if not self.newer(data):
self.status('not_required')
return
# Do not start a stopped client (e.g. maintenance desktop mode).
if subprocess.run(['systemctl','is-active','--quiet','itscreen-x11']).returncode:
self.status('ready')
return
backup = self.cache/'previous'
shutil.copy2(self.binary, backup)
with backup.open('rb') as stream:
os.fsync(stream.fileno())
sync_directory(backup.parent)
write_json(self.state/'transaction.json', {'previous_sha256': digest(backup)})
self.status('updating')
try:
self.service('stop')
self.replace(candidate)
self.service('start')
if not self.healthy():
raise RuntimeError('Client did not become ready; rolling back')
write_json(self.state/'installed.json', data)
(self.state/'transaction.json').unlink()
sync_directory(self.state)
self.version, self.installed = inspect_binary(self.binary)
self.emit('installed_version', self.installed)
self.status('updated')
except Exception:
self.recover()
raise
def manifest(self):
with open_url(FEED) as response:
raw = response.read(65537)
if len(raw) > 65536:
raise ValueError('Manifest too large')
return validate_manifest(json.loads(raw))
def bootstrap(self):
"""Stage owns the installer lock and service lifecycle, regardless of auto flag."""
if read_json(self.state/'transaction.json'):
raise RuntimeError('Recover interrupted client update before provisioning')
data = self.manifest()
if self.binary.exists() and not self.newer(data):
if digest(self.binary) == data['sha256']:
write_json(self.state/'installed.json', data)
return {'result': 'preserved', 'version': self.version,
'build_number': self.installed, 'feed': FEED}
candidate = self.download(data)
try:
self.replace(candidate)
write_json(self.state/'installed.json', data)
return {'result': 'installed', 'version': data['version'],
'build_number': data['build_number'], 'sha256': data['sha256'],
'download_url': data['download_url'], 'feed': FEED}
finally:
candidate.unlink(missing_ok=True)
def check(self, install=False, check_only=False):
self.busy = True
candidate = None
try:
self.status('check')
data = self.manifest()
self.ready = data['build_number']
self.emit('ready_version', self.ready)
self.version, self.installed = inspect_binary(self.binary)
if not self.newer(data):
if data['build_number'] == self.installed and digest(self.binary) == data['sha256']:
write_json(self.state/'installed.json', data)
self.status('not_required')
return
self.status('ready')
if check_only or not (install or self.automatic):
return
self.status('downloading')
candidate = self.download(data)
self.install(candidate, data, manual=install)
except Exception as exc:
logging.exception('Client update failed')
self.status('error', str(exc))
finally:
if candidate is not None:
candidate.unlink(missing_ok=True)
self.busy = False
def worker(self):
while True:
try:
manual_install = self.pending.get(timeout=PERIOD)
self.check(install=manual_install is True, check_only=manual_install == "check_only")
except queue.Empty:
if self.automatic:
self.check()
class Handler(socketserver.StreamRequestHandler):
def send(self, key, value):
try:
with self.write_lock:
self.wfile.write((json.dumps({key: value})+'\n').encode())
self.wfile.flush()
except OSError:
pass
def handle(self):
_, uid, _ = struct.unpack('3i', self.request.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12))
if uid not in (0, pwd.getpwnam('itscreen').pw_uid):
return
self.write_lock = threading.Lock()
updater = self.server.updater
updater.listeners.add(self)
try:
for key, value in updater.values().items():
self.send(key, value)
while True:
line = self.rfile.readline(65537)
if not line or len(line) > 65536:
break
try:
data = json.loads(line)
action, key = data.get('action'), data.get('key')
if action == 'get' and key == 'snapshot':
self.send('snapshot', updater.values())
elif action == 'check_only':
updater.request('check_only')
elif action == 'get' and key in updater.values():
self.send(key, updater.values()[key])
elif action == 'set' and key == 'active_update':
updater.set_automatic(data.get('value'))
elif action == 'set' and key == 'device_id':
updater.device_id = str(data.get('value', ''))[:128]
self.send(key, updater.device_id)
elif action == 'set' and key == 'installed_version':
# Executable is version authority; never accept caller's version.
self.send(key, updater.installed)
elif action in ('download_update', 'update'):
updater.request(action == 'update')
elif action == 'quit':
self.send('state_update', updater.phase)
except (ValueError, TypeError, AttributeError):
self.send('state_update', 'error_info')
finally:
updater.listeners.discard(self)
class Server(socketserver.ThreadingUnixStreamServer):
daemon_threads = True
def main():
logging.basicConfig(level=logging.INFO)
STATE.mkdir(parents=True, exist_ok=True)
CACHE.mkdir(parents=True, exist_ok=True)
os.chmod(STATE, 0o700)
os.chmod(CACHE, 0o700)
if sys.argv[1:] == ['--bootstrap']:
# Nested stages inherit the existing flock file description. Standalone
# invocations acquire the same lock rather than bypassing Console.
inherited = os.environ.get('IOMATEX_INSTALL_LOCK_FD', '')
if inherited.isdigit() and Path('/proc/self/fd/'+inherited).resolve() == LOCK:
fcntl.flock(int(inherited), fcntl.LOCK_EX | fcntl.LOCK_NB)
print(json.dumps(Updater(bootstrap=True).bootstrap()))
else:
with LOCK.open('a') as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
print(json.dumps(Updater(bootstrap=True).bootstrap()))
return
if len(sys.argv) != 1:
raise ValueError('Usage: client_updater.py [--bootstrap]')
updater = Updater()
with LOCK.open('a') as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
updater.recover()
Path(SOCKET).unlink(missing_ok=True)
with Server(SOCKET, Handler) as server:
server.updater = updater
os.chown(SOCKET, 0, grp.getgrnam('itscreen').gr_gid)
os.chmod(SOCKET, 0o660)
threading.Thread(target=updater.worker, daemon=True).start()
if updater.automatic:
updater.request(False)
server.serve_forever()
if __name__ == '__main__':
main()

View File

@ -1,12 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
updater_source=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
install -d -m 0755 -o root -g root /usr/local/lib/iomatex/client-updater
install -m 0644 -o root -g root "$updater_source/client_updater.py" /usr/local/lib/iomatex/client-updater/
install -m 0644 -o root -g root "$updater_source/iomatex-client-updater.service" /etc/systemd/system/
install -d -m 0700 -o root -g root /var/lib/iomatex/client-update /userdata/iomatex-client-update
systemctl daemon-reload
systemctl enable iomatex-client-updater.service
# Installer holds the shared lock. Starting asynchronously lets the daemon wait
# for that lock without deadlocking the stage installer.
systemctl restart --no-block iomatex-client-updater.service

View File

@ -1,18 +0,0 @@
[Unit]
Description=EVAx10 Debian client updates from Download
After=network-online.target
Wants=network-online.target
RequiresMountsFor=/userdata /opt/itscreen
[Service]
Type=simple
ExecStart=/usr/bin/python3 /usr/local/lib/iomatex/client-updater/client_updater.py
Restart=on-failure
RestartSec=15
UMask=0077
# QLocalSocket's existing relative itsupdater name resolves in shared /tmp.
PrivateTmp=false
TimeoutStopSec=120
[Install]
WantedBy=multi-user.target

View File

@ -1,238 +0,0 @@
import io
import json
from pathlib import Path
import subprocess
import tempfile
import unittest
from unittest.mock import patch
import client_updater as c
def executable(path, version):
path.write_text('#!/bin/sh\necho "'+version+' '+str(c.version_code(version))+'"\n')
path.chmod(0o755)
def manifest():
return {'schema_version':1, 'platform':'debian','architecture':'arm64',
'artifact_type':'elf','version':'5.1.55','build_number':5010055,
'release_revision':2,'size_bytes':100000,'sha256':'a'*64,
'download_url':c.PREFIX+'5.1.55-r2/itscreen'}
class TestUpdater(unittest.TestCase):
def test_manifest_requests_use_updater_user_agent(self):
opener = unittest.mock.Mock()
opener.open.return_value = io.BytesIO(json.dumps(manifest()).encode())
with patch.object(c.urllib.request, 'build_opener', return_value=opener):
data = self.u.manifest()
request = opener.open.call_args.args[0]
self.assertEqual(c.FEED, request.full_url)
self.assertEqual('IomatexOS-Updater/1.0', request.get_header('User-agent'))
self.assertTrue(data['download_url'].startswith(c.PREFIX))
def test_feed_matches_strict_canonical_download_host(self):
# Legacy latest.json intentionally keeps git.it-screen.com URLs.
self.assertEqual(c.PREFIX.rsplit('/releases/', 1)[0] + '/latest-iomatex.json', c.FEED)
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.root = Path(self.tmp.name)
self.binary = self.root/'itscreen'
executable(self.binary, '5.1.54')
self.u = c.Updater(self.binary,self.root/'state',self.root/'cache')
def test_console_check_never_installs_even_with_automatic_enabled(self):
self.u.automatic = True
with patch.object(self.u, 'manifest', return_value=manifest()), patch.object(self.u, 'download') as download:
self.u.check(check_only=True)
download.assert_not_called()
self.assertEqual(self.u.phase, 'ready')
self.assertTrue(self.u.automatic)
self.assertEqual(self.u.values()['ready_version'], 5010055)
def test_console_pending_request_is_busy(self):
self.u.request('check_only')
self.assertTrue(self.u.values()['busy'])
self.assertEqual(self.u.pending.get_nowait(), 'check_only')
self.assertFalse(self.u.values()['busy'])
def test_socket_checkbox_and_fragmented_frames(self):
import os
import socket
import threading
from types import SimpleNamespace
path = str(self.root/'socket')
with patch.object(c.pwd,'getpwnam',return_value=SimpleNamespace(pw_uid=os.getuid())):
with c.Server(path,c.Handler) as server:
server.updater=self.u
thread=threading.Thread(target=server.serve_forever,daemon=True)
thread.start()
try:
with socket.socket(socket.AF_UNIX) as client:
client.settimeout(3);client.connect(path)
stream=client.makefile('rwb',buffering=0)
initial={}
for _ in range(len(self.u.values())):initial.update(json.loads(stream.readline()))
self.assertEqual(initial['active_update'],0)
stream.write(b'{"action":"get","key":"snapshot"}\n')
self.assertEqual(json.loads(stream.readline())['snapshot']['installed_version'],5010054)
stream.write(b'{"action":"set","key":"active_')
stream.write(b'update","value":1}\n')
self.assertEqual(json.loads(stream.readline()),{'active_update':1})
self.assertTrue(c.Updater(self.binary,self.u.state,self.u.cache).automatic)
stream.write(b'{"action":"set","key":"active_update","value":0}\n')
self.assertEqual(json.loads(stream.readline()),{'active_update':0})
self.assertFalse(c.Updater(self.binary,self.u.state,self.u.cache).automatic)
finally:
server.shutdown();thread.join()
def test_first_install_from_download_even_with_automatic_off(self):
self.binary.unlink()
u=c.Updater(self.binary,self.u.state,self.u.cache,bootstrap=True)
candidate=self.root/'new';executable(candidate,'5.1.55')
data=manifest();data['sha256']=c.digest(candidate)
with patch.object(u,'manifest',return_value=data),patch.object(u,'download',return_value=candidate):
self.assertEqual(u.bootstrap()['result'],'installed')
self.assertEqual(c.inspect_binary(self.binary),('5.1.55',5010055))
self.assertFalse(u.automatic)
self.assertEqual(c.read_json(u.state/'installed.json')['sha256'],c.digest(self.binary))
self.assertFalse(candidate.exists())
def test_bootstrap_preserves_newer_and_matching_install(self):
for version in ['5.1.55','5.1.56']:
executable(self.binary,version)
u=c.Updater(self.binary,self.u.state,self.u.cache,bootstrap=True)
data=manifest();data['sha256']=c.digest(self.binary)
with patch.object(u,'manifest',return_value=data),patch.object(u,'download') as download:
self.assertEqual(u.bootstrap()['result'],'preserved')
download.assert_not_called()
self.assertEqual(c.inspect_binary(self.binary)[0],version)
def test_bootstrap_network_failure_preserves_existing_or_absent_binary(self):
before=self.binary.read_bytes()
with patch.object(self.u,'manifest',side_effect=OSError('offline')):
with self.assertRaises(OSError):self.u.bootstrap()
self.assertEqual(self.binary.read_bytes(),before)
self.binary.unlink()
u=c.Updater(self.binary,self.u.state,self.u.cache,bootstrap=True)
with patch.object(u,'manifest',side_effect=OSError('offline')):
with self.assertRaises(OSError):u.bootstrap()
self.assertFalse(self.binary.exists())
def test_bootstrap_rejects_bad_binary_before_replacement(self):
before=self.binary.read_bytes()
with patch.object(self.u,'manifest',return_value=manifest()),patch.object(c,'open_url',return_value=io.BytesIO(b'bad')):
with self.assertRaises(ValueError):self.u.bootstrap()
self.assertEqual(self.binary.read_bytes(),before)
def test_bootstrap_stage_uses_shared_download_owner(self):
stage=Path(__file__).resolve().parents[1]/'stage_itscreen_install.sh'
if not stage.exists():self.skipTest('source contract runs in full checkout')
source=stage.read_text().split('install_itscreen_binary() (',1)[1].split('\n)',1)[0]
self.assertIn('updater/client_updater.py" --bootstrap',source)
self.assertNotIn('git_delivery.py',source)
self.assertNotIn('verify_client_release.py',source)
def test_manifest_rejects_untrusted_or_wrong_platform(self):
self.assertEqual(c.validate_manifest(manifest())['build_number'],5010055)
for key,value in [('download_url',c.PREFIX+'../itscreen'),
('download_url','https://git.it-screen.com/a'),
('download_url',c.PREFIX+'ok/itscreen?redirect=x'),
('architecture','x86_64'),('build_number',5010054),
('size_bytes',True),('sha256','bad'),('release_revision',0)]:
with self.subTest(key=key,value=value):
data=manifest();data[key]=value
with self.assertRaises(ValueError): c.validate_manifest(data)
def test_redirect_refused(self):
with self.assertRaises(ValueError):
c.NoRedirect().redirect_request(None,None,302,'',{},'https://git.it-screen.com')
def test_flag_persists_and_does_not_accept_other_values(self):
self.u.set_automatic(1)
self.assertTrue(c.Updater(self.binary,self.u.state,self.u.cache).automatic)
self.u.set_automatic(0)
self.assertFalse(c.Updater(self.binary,self.u.state,self.u.cache).automatic)
for v in [True,2,'1',None]:
with self.assertRaises(ValueError):self.u.set_automatic(v)
def test_check_only_when_off_and_auto_when_on(self):
with patch.object(c,'open_url',return_value=io.BytesIO(json.dumps(manifest()).encode())), patch.object(self.u,'download') as download:
self.u.check()
download.assert_not_called()
self.assertEqual(self.u.phase,'ready')
self.u.automatic=True
with patch.object(c,'open_url',return_value=io.BytesIO(json.dumps(manifest()).encode())), patch.object(self.u,'download',return_value=self.binary), patch.object(self.u,'install') as install:
self.u.check();install.assert_called_once()
def test_no_downgrade_or_repeat_and_revision_correction(self):
data=manifest();self.u.installed=5010056
self.assertFalse(self.u.newer(data))
self.u.installed=5010055
self.assertTrue(self.u.newer(data))
c.write_json(self.u.state/'installed.json',dict(data,sha256=c.digest(self.binary)))
self.assertFalse(self.u.newer(data))
data['release_revision']=3
self.assertTrue(self.u.newer(data))
data['sha256']=c.digest(self.binary)
self.assertFalse(self.u.newer(data))
def test_bad_download_leaves_installed_binary(self):
before=self.binary.read_bytes()
with patch.object(c,'open_url',return_value=io.BytesIO(b'bad')):
with self.assertRaises(ValueError):self.u.download(manifest())
self.assertEqual(self.binary.read_bytes(),before)
self.assertFalse((self.u.cache/'candidate').exists())
def test_verified_elf_and_embedded_version(self):
data=manifest();content=bytearray(data['size_bytes'])
content[:6]=b'\x7fELF\x02\x01';content[18:20]=b'\xb7\x00'
data['sha256']=c.hashlib.sha256(content).hexdigest()
with patch.object(c,'open_url',return_value=io.BytesIO(content)),patch.object(c,'inspect_binary',return_value=('5.1.55',5010055)):
self.assertEqual(self.u.download(data).read_bytes(),content)
with patch.object(c,'open_url',return_value=io.BytesIO(content)),patch.object(c,'inspect_binary',return_value=('5.1.54',5010054)):
with self.assertRaises(ValueError):self.u.download(data)
def test_disabling_after_download_prevents_install(self):
with patch.object(c,'LOCK',self.root/'lock'),patch.object(self.u,'service') as service:
self.u.install(self.binary,manifest(),False)
service.assert_not_called()
self.assertEqual(self.u.phase,'not_permitted')
def perform_install(self, healthy):
candidate=self.root/'candidate';executable(candidate,'5.1.55')
data=manifest();data['sha256']=c.digest(candidate)
run=subprocess.run
def local_run(args,**kwargs):
if args[0]=='systemctl':return subprocess.CompletedProcess(args,0)
return run(args,**kwargs)
with patch.object(c,'LOCK',self.root/'lock'),patch.object(c.subprocess,'run',side_effect=local_run),patch.object(self.u,'service') as service,patch.object(self.u,'healthy',return_value=healthy):
if healthy:self.u.install(candidate,data,True)
else:
with self.assertRaises(RuntimeError):self.u.install(candidate,data,True)
return service.call_args_list
def test_manual_install_when_off(self):
self.perform_install(True)
self.assertEqual(c.inspect_binary(self.binary),('5.1.55',5010055))
self.assertEqual(self.u.phase,'updated')
self.assertFalse((self.u.state/'transaction.json').exists())
def test_failed_health_rolls_back(self):
before=self.binary.read_bytes();self.perform_install(False)
self.assertEqual(self.binary.read_bytes(),before)
self.assertEqual(c.inspect_binary(self.binary),('5.1.54',5010054))
self.assertFalse((self.u.state/'transaction.json').exists())
def test_recovery_after_interruption(self):
backup=self.u.cache/'previous';executable(backup,'5.1.54')
c.write_json(self.u.state/'transaction.json',{'previous_sha256':c.digest(backup)})
executable(self.binary,'5.1.55')
u=c.Updater(self.binary,self.u.state,self.u.cache)
with patch.object(u,'service'):u.recover()
self.assertEqual(c.inspect_binary(self.binary),('5.1.54',5010054))
if __name__=='__main__':unittest.main()

View File

@ -1,19 +0,0 @@
#!/usr/bin/env python3
"""Embedded-version check for archived release provenance."""
import sys
from pathlib import Path
from updater.client_updater import inspect_binary, read_json
def verify(binary, provenance):
metadata = read_json(Path(provenance))
actual = inspect_binary(Path(binary))
expected = (metadata['client_version'], metadata['native_version_code'])
if actual != expected:
raise ValueError(f'Client release mismatch: expected {expected!r}, got {actual!r}')
return f'{actual[0]} {actual[1]}'
if __name__ == '__main__':
print(verify(sys.argv[1], sys.argv[2]))

View File

@ -1,3 +1,3 @@
{ {
"version": "1.0.42" "version": "1.0.33"
} }

View File

@ -66,13 +66,31 @@ never reports success. The firmware's power-cycle persistence is not asserted.
UI uses existing field/select/actionRow/card classes and the shared body-mounted UI uses existing field/select/actionRow/card classes and the shared body-mounted
confirmation dialog. No new CSS or independent modal/serial transport is added. confirmation dialog. No new CSS or independent modal/serial transport is added.
## Debian client updates (Console 3.1.32) ## Android adapter (development)
The It-Screen panel uses authenticated GET/POST `/api/itscreen/update`. `android_console` packages this frontend verbatim, with the EVAx10 brand and a
`client_update_request` only adapts the existing `/tmp/itsupdater` socket; supported-tab allowlist; it must not carry its own HTML/JS/CSS component copy.
`stage_itscreen/updater/client_updater.py` remains the single owner for feed AndroidPlatform and AndroidClient implement the same health, display and client
validation, version comparison, download, install locking and rollback. registration URLs. DeviceSettingsMessenger remains the owner of client actions;
GET reads a local snapshot; POST allowlists `check_only` and `update`. Console may adapt transport but must not create a second registration store or
Opening the tab checks without installation or changing the automatic flag. write the client's private configuration. RemoteAccess follows canonical
The panel polls local state and replaces only its own markup, preserving form RegistrationStore changes and projects readiness into the shared reverse card.
focus and edits elsewhere. Stage 1.0.40 supplies the extended socket contract.
Additive capability fields are explicit opt-outs; absence preserves g-box:
- Display card `capabilities.desktop_mode` and `pulse_audio` suppress OS-specific
controls/panels, retaining the same display/connector renderer.
- Health `storage.supported=false` suppresses unsupported eMMC wear claims.
- Registration `capabilities.can_register` and `can_reset` constrain existing
controls; `capability_reason` explains the underlying client's policy.
- Client service `capabilities.can_start`, `can_stop`, `logs` constrain controls
and log transport together. Unknown active state is `null`, not false/true.
- Reverse card `capabilities.can_configure` / `can_restart` constrain its actions;
`configuration_hint` describes automatic registration-driven reconciliation.
- `updates.supported=false` excludes Debian stage updater controls on Android.
Android background samplers own remote checks. HTTP status/health handlers only
read local snapshots; expired or failed checks cannot remain green. Registration
response secrets are masked using the existing `password_present` contract.
`android_console/tests/test_shared_contract.py` guards common ownership and URLs;
API/browser bench tests cover supported controls and responsive states.

View File

@ -1,6 +1,5 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import glob import glob
import hashlib
import base64 import base64
import importlib.util import importlib.util
import ipaddress import ipaddress
@ -22,7 +21,6 @@ import time
import wave import wave
import crypt import crypt
import spwd import spwd
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime from datetime import datetime
from http.cookies import SimpleCookie from http.cookies import SimpleCookie
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
@ -62,7 +60,7 @@ APP_DIR = "/opt/iomatex-console"
PUBLIC_DIR = os.path.join(APP_DIR, "public") PUBLIC_DIR = os.path.join(APP_DIR, "public")
PROVIDERS_DIR = os.path.join(APP_DIR, "providers.d") PROVIDERS_DIR = os.path.join(APP_DIR, "providers.d")
CONFIG_PATH = "/etc/iomatex/console.json" CONFIG_PATH = "/etc/iomatex/console.json"
UI_VERSION = "V 3.1.42" UI_VERSION = "V 3.1.28"
STORAGE_HEALTH_COMMAND = "/usr/local/sbin/iomatex-storage-health" STORAGE_HEALTH_COMMAND = "/usr/local/sbin/iomatex-storage-health"
ZONEINFO_ROOT = "/usr/share/zoneinfo" ZONEINFO_ROOT = "/usr/share/zoneinfo"
@ -70,11 +68,13 @@ DEFAULT_CONFIG = {
"bind": "0.0.0.0", "bind": "0.0.0.0",
"port": 80, "port": 80,
"extra_ports": [], "extra_ports": [],
"cache_ttl_sec": 15, "cache_ttl_sec": 3,
} }
_CACHE = {"expires_at": 0.0, "payload": None} _CACHE = {"expires_at": 0.0, "payload": None}
_HEALTH_SERVICES_CACHE = {"expires_at": 0.0, "payload": None}
_CACHE_LOCK = threading.Lock() _CACHE_LOCK = threading.Lock()
_HEALTH_SERVICES_CACHE_LOCK = threading.Lock()
_CPU_SAMPLE = {"total": None, "idle": None} _CPU_SAMPLE = {"total": None, "idle": None}
_NET_SAMPLE = {} _NET_SAMPLE = {}
_WIFI_SCAN_CACHE = {"expires_at": 0.0, "payload": None} _WIFI_SCAN_CACHE = {"expires_at": 0.0, "payload": None}
@ -168,9 +168,6 @@ STATIC_NO_CACHE_HEADERS = {
"Cache-Control": "no-store, no-cache, must-revalidate", "Cache-Control": "no-store, no-cache, must-revalidate",
"Pragma": "no-cache", "Pragma": "no-cache",
} }
STATIC_ASSET_CACHE_HEADERS = {
"Cache-Control": "public, max-age=31536000, immutable",
}
_AUTH_SESSIONS = {} _AUTH_SESSIONS = {}
_AUTH_SESSIONS_LOCK = threading.Lock() _AUTH_SESSIONS_LOCK = threading.Lock()
CAMERA_PREVIEW_PATH_RE = re.compile( CAMERA_PREVIEW_PATH_RE = re.compile(
@ -240,8 +237,7 @@ def publish_camera_preview(payload):
response.extend(chunk) response.extend(chunk)
result = json.loads(response.decode("utf-8")) if response else {} result = json.loads(response.decode("utf-8")) if response else {}
if not isinstance(result, dict) or result.get("status") != "ok": if not isinstance(result, dict) or result.get("status") != "ok":
error = str(result.get("error") or "").strip() if isinstance(result, dict) else "" raise RuntimeError("Unable to start camera media operation")
raise RuntimeError(error or "Unable to start camera media operation")
return result return result
@ -1533,6 +1529,8 @@ def ap_status_card():
def invalidate_cache(): def invalidate_cache():
_CACHE["payload"] = None _CACHE["payload"] = None
_CACHE["expires_at"] = 0.0 _CACHE["expires_at"] = 0.0
_HEALTH_SERVICES_CACHE["payload"] = None
_HEALTH_SERVICES_CACHE["expires_at"] = 0.0
_ITSCREEN_STATUS_CACHE["payload"] = None _ITSCREEN_STATUS_CACHE["payload"] = None
_ITSCREEN_STATUS_CACHE["expires_at"] = 0.0 _ITSCREEN_STATUS_CACHE["expires_at"] = 0.0
@ -2050,7 +2048,7 @@ def summarize_interface(iface, kind="ethernet"):
} }
def get_network_summary(include_service_cards=True, force_provider_refresh=False): def get_network_summary(include_service_cards=True):
iface = get_primary_interface() iface = get_primary_interface()
profile = read_wifi_profile_state() profile = read_wifi_profile_state()
script_status = parse_wifi_status_script() script_status = parse_wifi_status_script()
@ -2077,7 +2075,7 @@ def get_network_summary(include_service_cards=True, force_provider_refresh=False
} }
avahi_card = None avahi_card = None
if include_service_cards: if include_service_cards:
cards = build_status_payload(force=force_provider_refresh).get("services", []) cards, _ = collect_provider_cards(build_provider_context())
avahi_card = next((card for card in cards if card.get("id") == "avahi"), None) avahi_card = next((card for card in cards if card.get("id") == "avahi"), None)
return { return {
"ok": True, "ok": True,
@ -2528,11 +2526,9 @@ def build_provider_context():
def collect_provider_cards(context, entrypoint="get_cards"): def collect_provider_cards(context, entrypoint="get_cards"):
cards = [] cards = []
providers = load_providers(entrypoint) provider_names = []
provider_names = [os.path.basename(path) for path, _provider in providers] for path, provider in load_providers(entrypoint):
provider_names.append(os.path.basename(path))
def collect(item):
path, provider = item
try: try:
result = provider(context) result = provider(context)
except Exception as exc: except Exception as exc:
@ -2549,24 +2545,20 @@ def collect_provider_cards(context, entrypoint="get_cards"):
}] }]
if isinstance(result, dict): if isinstance(result, dict):
result = [result] result = [result]
return [normalize_card(card) for card in result or []] for card in result or []:
cards.append(normalize_card(card))
if providers:
with ThreadPoolExecutor(max_workers=min(4, len(providers)), thread_name_prefix="console-provider") as executor:
for result in executor.map(collect, providers):
cards.extend(result)
return cards, provider_names return cards, provider_names
def build_status_payload(force=False): def build_status_payload():
now = time.time() now = time.time()
cfg = load_config() cfg = load_config()
if not force and _CACHE["payload"] is not None and now < _CACHE["expires_at"]: if _CACHE["payload"] is not None and now < _CACHE["expires_at"]:
return _CACHE["payload"] return _CACHE["payload"]
with _CACHE_LOCK: with _CACHE_LOCK:
now = time.time() now = time.time()
if not force and _CACHE["payload"] is not None and now < _CACHE["expires_at"]: if _CACHE["payload"] is not None and now < _CACHE["expires_at"]:
return _CACHE["payload"] return _CACHE["payload"]
cards, provider_names = collect_provider_cards(build_provider_context()) cards, provider_names = collect_provider_cards(build_provider_context())
@ -2578,7 +2570,7 @@ def build_status_payload(force=False):
"providers": provider_names, "providers": provider_names,
} }
_CACHE["payload"] = payload _CACHE["payload"] = payload
_CACHE["expires_at"] = time.time() + max(1, int(cfg.get("cache_ttl_sec", 15))) _CACHE["expires_at"] = time.time() + max(1, int(cfg.get("cache_ttl_sec", 3)))
return payload return payload
@ -2702,27 +2694,40 @@ def build_runtime_profile_payload():
} }
def build_health_services_payload(force=False): def build_health_services_payload():
allowed_ids = { now = time.time()
"itscreen", cfg = load_config()
"mosquitto", if _HEALTH_SERVICES_CACHE["payload"] is not None and now < _HEALTH_SERVICES_CACHE["expires_at"]:
"mqtt_bridge", return _HEALTH_SERVICES_CACHE["payload"]
"zigbee2mqtt",
"cockpit", with _HEALTH_SERVICES_CACHE_LOCK:
"reverse_tunnel", now = time.time()
"display", if _HEALTH_SERVICES_CACHE["payload"] is not None and now < _HEALTH_SERVICES_CACHE["expires_at"]:
"edge_api", return _HEALTH_SERVICES_CACHE["payload"]
"ip_stream",
"environment", allowed_ids = {
"console", "itscreen",
} "mosquitto",
status = build_status_payload(force=force) "mqtt_bridge",
return { "zigbee2mqtt",
"ok": True, "cockpit",
"generated_at": status.get("generated_at", ""), "reverse_tunnel",
"identity": status.get("identity", {}), "display",
"services": [card for card in status.get("services", []) if card.get("id") in allowed_ids], "edge_api",
} "ip_stream",
"environment",
"console",
}
cards, _ = collect_provider_cards(build_provider_context())
payload = {
"ok": True,
"generated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"identity": get_identity_payload(),
"services": [card for card in cards if card.get("id") in allowed_ids],
}
_HEALTH_SERVICES_CACHE["payload"] = payload
_HEALTH_SERVICES_CACHE["expires_at"] = time.time() + max(1, int(cfg.get("cache_ttl_sec", 3)))
return payload
def find_service_card(service_id): def find_service_card(service_id):
@ -2972,38 +2977,6 @@ def get_itscreen_binary_candidates():
return [path for path in candidates if os.path.exists(path)] return [path for path in candidates if os.path.exists(path)]
def fingerprint_console_assets(html, directory):
"""Invalidate browser assets on content changes, including same-version deploys."""
text = html.decode("utf-8")
for name in ("console.js", "console.i18n.js", "console.css"):
with open(os.path.join(directory, name), "rb") as stream:
fingerprint = hashlib.sha256(stream.read()).hexdigest()[:16]
pattern = r'(["\'])/' + re.escape(name) + r'(?:\?[^"\']*)?(["\'])'
text = re.sub(pattern, lambda match: match[1] + "/" + name + "?sha=" + fingerprint + match[2], text)
return text.encode("utf-8")
def client_update_request(action=None):
"""Console adapter only: the privileged updater owns feeds and installation."""
if action not in (None, "check_only", "update"):
raise ValueError("Invalid client update action")
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as connection:
connection.settimeout(3)
connection.connect("/tmp/itsupdater")
if action:
connection.sendall((json.dumps({"action": action}) + "\n").encode())
connection.sendall(b'{"action":"get","key":"snapshot"}\n')
with connection.makefile("rb") as stream:
for _ in range(32):
line = stream.readline(65537)
if not line or len(line) > 65536:
break
payload = json.loads(line)
if "snapshot" in payload:
return {"ok": True, **payload["snapshot"]}
raise RuntimeError("Client updater is unavailable; update the It-Screen system stage")
def get_itscreen_app_version(): def get_itscreen_app_version():
version_re = re.compile(r"\b(\d+\.\d+\.\d+(?:\.\d+)?)\b") version_re = re.compile(r"\b(\d+\.\d+\.\d+(?:\.\d+)?)\b")
for binary_path in get_itscreen_binary_candidates(): for binary_path in get_itscreen_binary_candidates():
@ -3480,8 +3453,6 @@ class Handler(BaseHTTPRequestHandler):
except FileNotFoundError: except FileNotFoundError:
self.send_error(404) self.send_error(404)
return return
if os.path.basename(path) == "index.html":
data = fingerprint_console_assets(data, os.path.dirname(path))
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)))
@ -3652,7 +3623,7 @@ class Handler(BaseHTTPRequestHandler):
) )
return return
if parsed.path == "/api/status": if parsed.path == "/api/status":
self.send_json(build_status_payload(force=query.get("refresh", ["0"])[0] == "1")) self.send_json(build_status_payload())
return return
if parsed.path == "/api/display": if parsed.path == "/api/display":
payload = find_service_card("display") payload = find_service_card("display")
@ -3663,7 +3634,7 @@ class Handler(BaseHTTPRequestHandler):
return return
if parsed.path == "/api/health/services": if parsed.path == "/api/health/services":
try: try:
payload = build_health_services_payload(force=query.get("refresh", ["0"])[0] == "1") payload = build_health_services_payload()
cards = [dict(card) for card in payload["services"]] cards = [dict(card) for card in payload["services"]]
updates = stage_versions.snapshot(cards) updates = stage_versions.snapshot(cards)
for card in cards: for card in cards:
@ -3712,7 +3683,7 @@ class Handler(BaseHTTPRequestHandler):
if parsed.path == "/api/network/summary": if parsed.path == "/api/network/summary":
try: try:
self.send_json({ self.send_json({
**get_network_summary(force_provider_refresh=query.get("refresh", ["0"])[0] == "1"), **get_network_summary(),
"identity": get_identity_payload(), "identity": get_identity_payload(),
}) })
except Exception as exc: except Exception as exc:
@ -3758,12 +3729,6 @@ class Handler(BaseHTTPRequestHandler):
except Exception as exc: except Exception as exc:
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 == "/api/itscreen/update":
try:
self.send_json(client_update_request())
except Exception as exc:
self.send_json({"ok": False, "error": str(exc)}, code=503)
return
if parsed.path == "/api/itscreen/status": if parsed.path == "/api/itscreen/status":
try: try:
self.send_json(build_itscreen_status_payload()) self.send_json(build_itscreen_status_payload())
@ -3813,13 +3778,13 @@ class Handler(BaseHTTPRequestHandler):
self.send_file(os.path.join(PUBLIC_DIR, "index.html"), "text/html; charset=utf-8", extra_headers=STATIC_NO_CACHE_HEADERS) 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", extra_headers=STATIC_ASSET_CACHE_HEADERS if "sha" in query else STATIC_NO_CACHE_HEADERS) 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", extra_headers=STATIC_ASSET_CACHE_HEADERS if "sha" in query else STATIC_NO_CACHE_HEADERS) 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", extra_headers=STATIC_ASSET_CACHE_HEADERS if "sha" in query else STATIC_NO_CACHE_HEADERS) 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")
@ -3862,16 +3827,6 @@ class Handler(BaseHTTPRequestHandler):
return return
if not self.require_auth(parsed): if not self.require_auth(parsed):
return return
if parsed.path == "/api/itscreen/update":
payload = self.read_json_body()
if not isinstance(payload, dict) or payload.get("action") not in ("check_only", "update"):
self.send_json({"ok": False, "error": "Invalid update action"}, code=400)
return
try:
self.send_json(client_update_request(payload["action"]))
except Exception as exc:
self.send_json({"ok": False, "error": str(exc)}, code=503)
return
if parsed.path == "/api/onvif/probe": if parsed.path == "/api/onvif/probe":
payload = self.read_json_body() payload = self.read_json_body()
if payload is None: if payload is None:
@ -3994,18 +3949,6 @@ class Handler(BaseHTTPRequestHandler):
except Exception as exc: except Exception as exc:
self.send_json({"ok": False, "error": str(exc)}, code=503) self.send_json({"ok": False, "error": str(exc)}, code=503)
return return
if parsed.path == "/api/camera-stream/stop":
payload = self.read_json_body()
stream_id = str((payload or {}).get("stream_id", ""))
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,63}", stream_id):
self.send_json({"ok": False, "error": "Invalid camera stream request"}, code=400)
return
try:
publish_camera_preview({"action": "stop", "stream_id": stream_id})
self.send_json({"ok": True, "stream_id": stream_id})
except Exception as exc:
self.send_json({"ok": False, "error": str(exc)}, code=503)
return
if parsed.path == "/api/camera-preview/snapshot": if parsed.path == "/api/camera-preview/snapshot":
payload = self.read_json_body() payload = self.read_json_body()
stream_id = str((payload or {}).get("stream_id", "")) stream_id = str((payload or {}).get("stream_id", ""))

View File

@ -1,21 +0,0 @@
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const source = fs.readFileSync(__dirname + '/../frontend/console.js', 'utf8');
const ctx = {state: {itscreen: {}}, t: s => s, esc: s => String(s).replaceAll('<', '&lt;')};
vm.createContext(ctx);
vm.runInContext(source.slice(source.indexOf(' function clientVersion('), source.indexOf(' async function loadClientUpdate(')), ctx);
for (const [phase, label] of [['ready', 'A new client version'], ['not_required', 'latest client version'], ['updating', 'Installing client'], ['error', 'Client update failed']]) {
ctx.state.itscreen.update = {state_update: phase, installed_version: 5010055, ready_version: 5010056, error: phase === 'error' ? '<error>' : '', busy: phase === 'updating'};
const html = ctx.renderClientUpdate();
assert.ok(html.includes(label));
assert.ok(html.includes('5.1.55'));
assert.ok(html.includes('5.1.56'));
assert.equal(html.includes(' disabled '), phase === 'updating');
assert.ok(!html.includes('<error>'));
}
assert.ok(source.includes('panel.innerHTML = renderClientUpdate()'), 'Polling updates only the updater panel, preserving form edits');
assert.ok(source.includes('["health", "tscreen"].includes(state.activeTab)'), 'Health profile and It-Screen tab share the update owner');
assert.equal((source.match(/id="itscreenClientUpdate"/g) || []).length, 2, 'Both views expose the shared client update panel');
assert.ok(source.includes('Client update system module'), 'Technical stage is explicitly distinguished from the client version');
console.log('Client update versions, available/current/error/busy states and local panel rendering passed');

View File

@ -1,39 +0,0 @@
import ast
import hashlib
import os
from pathlib import Path
import re
import tempfile
import unittest
source = Path(__file__).with_name('app.py').read_text()
node = next(n for n in ast.parse(source).body if isinstance(n, ast.FunctionDef) and n.name == 'fingerprint_console_assets')
namespace = dict(hashlib=hashlib, os=os, re=re)
exec(compile(ast.Module(body=[node], type_ignores=[]), '<asset-owner>', 'exec'), namespace)
class AssetVersionTest(unittest.TestCase):
def test_same_release_changed_content_gets_new_url(self):
with tempfile.TemporaryDirectory() as directory:
for name in ('console.js', 'console.i18n.js', 'console.css'):
Path(directory, name).write_text('original')
html = b'<script src="/console.js?v=3.1.32&amp;rev=old"></script><link href="/console.css?v=3.1.32">'
render = lambda: namespace['fingerprint_console_assets'](html, directory)
first = render()
self.assertIn(b'?sha=', first)
self.assertNotIn(b'rev=old', first)
self.assertEqual(first, render())
Path(directory, 'console.js').write_text('new same-version bundle')
self.assertNotEqual(first, render())
self.assertEqual(first.split(b'<link')[1], render().split(b'<link')[1])
def test_html_response_uses_shared_asset_owner(self):
handler = source.split(' def send_file(', 1)[1].split(' def send_sse_headers', 1)[0]
self.assertIn('fingerprint_console_assets(data, os.path.dirname(path))', handler)
self.assertLess(handler.index('fingerprint_console_assets'), handler.index('Content-Length'))
def test_fingerprinted_assets_are_immutable(self):
self.assertIn('"Cache-Control": "public, max-age=31536000, immutable"', source)
route = source.split('if parsed.path == "/console.css":', 1)[1].split('if parsed.path == "/logo.png":', 1)[0]
self.assertEqual(3, route.count('STATIC_ASSET_CACHE_HEADERS if "sha" in query else STATIC_NO_CACHE_HEADERS'))
if __name__ == '__main__': unittest.main()

View File

@ -1,8 +1,6 @@
import importlib.util import importlib.util
import pathlib import pathlib
import threading
import unittest import unittest
from unittest import mock
PROVIDER_PATH = pathlib.Path(__file__).resolve().parents[1] / "providers" / "00_core_services.py" PROVIDER_PATH = pathlib.Path(__file__).resolve().parents[1] / "providers" / "00_core_services.py"
@ -12,26 +10,6 @@ SPEC.loader.exec_module(provider)
class ReverseTunnelBootstrapTest(unittest.TestCase): class ReverseTunnelBootstrapTest(unittest.TestCase):
def test_core_cards_run_in_parallel_and_keep_product_order(self):
barrier = threading.Barrier(4)
names = [
"itscreen_card", "mosquitto_card", "mqtt_bridge_card", "zigbee_card",
"reverse_tunnel_card", "ip_stream_card", "display_card", "managed_system_cards",
]
patches = {}
for index, name in enumerate(names):
def build(_context, card_id=name, wait=index < 4):
if wait:
barrier.wait(1)
card = {"id": card_id}
return [card] if card_id == "managed_system_cards" else card
patches[name] = build
with mock.patch.multiple(provider, **patches):
cards = provider.get_cards({})
self.assertEqual(names, [card["id"] for card in cards])
def test_tunnel_is_active_only_when_ssh_child_has_established_connection(self): def test_tunnel_is_active_only_when_ssh_child_has_established_connection(self):
unit = {"active": True, "active_state": "active", "main_pid": 100} unit = {"active": True, "active_state": "active", "main_pid": 100}
responses = { responses = {

View File

@ -1,24 +0,0 @@
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const js = fs.readFileSync(path.join(__dirname, '../frontend/console.js'), 'utf8');
const css = fs.readFileSync(path.join(__dirname, '../frontend/console.css'), 'utf8');
assert.match(js, /class="cards healthServiceGrid"/);
assert.equal((js.match(/serviceCard serviceProfileCard/g) || []).length, 2);
assert.match(js, /function renderServiceSummary\(card\)/);
assert.match(js, /serviceCard serviceProfileCard itscreenServiceCard/);
assert.match(js, /if \(card\.id === "itscreen"\) return content/);
assert.match(js, /serviceDetailsWide/);
assert.match(js, /state\.activeTab = nextTab;\s+renderActiveTab\(\);\s+await loadForActiveTab\(\)/);
assert.match(css, /\.shell\{max-width:1600px/);
assert.match(css, /\.healthServiceGrid\{\s*grid-template-columns:repeat\(3,minmax\(0,1fr\)\)/);
assert.match(css, /@media \(max-width:1100px\)[\s\S]*?\.healthServiceGrid\{grid-template-columns:repeat\(2,minmax\(0,1fr\)\)\}/);
assert.match(css, /@media \(max-width:720px\)[\s\S]*?\.healthServiceGrid\{grid-template-columns:1fr\}/);
assert.match(css, /\.healthServiceGrid \.serviceProfileCard\{[\s\S]*?grid-template-columns:repeat\(2,minmax\(0,1fr\)\)/);
assert.match(css, /\.healthServiceGrid \.itscreenServiceCard\{[\s\S]*?grid-column:span 2;[\s\S]*?grid-template-columns:repeat\(3,minmax\(0,1fr\)\)/);
assert.match(css, /\.serviceDetailsWide \.compactMeta\{grid-template-columns:minmax\(90px,24%\) minmax\(0,1fr\)\}/);
assert.match(css, /@media \(max-width:940px\)[\s\S]*?\.healthServiceGrid \.serviceProfileCard\{grid-template-columns:1fr\}/);
console.log('Health layout owner: 1600px shell and 3/2/1 service columns passed');

View File

@ -16,7 +16,7 @@ SPEC.loader.exec_module(app)
class HealthServicesCacheTest(unittest.TestCase): class HealthServicesCacheTest(unittest.TestCase):
def setUp(self): def setUp(self):
app._CACHE.update({"expires_at": 0.0, "payload": None}) app._HEALTH_SERVICES_CACHE.update({"expires_at": 0.0, "payload": None})
def test_ttl_starts_after_slow_collection_finishes(self): def test_ttl_starts_after_slow_collection_finishes(self):
clock = iter([100.0, 100.0, 110.0, 110.0]) clock = iter([100.0, 100.0, 110.0, 110.0])
@ -26,24 +26,7 @@ class HealthServicesCacheTest(unittest.TestCase):
mock.patch.object(app, "get_identity_payload", return_value={}): mock.patch.object(app, "get_identity_payload", return_value={}):
app.build_health_services_payload() app.build_health_services_payload()
self.assertEqual(113.0, app._CACHE["expires_at"]) self.assertEqual(113.0, app._HEALTH_SERVICES_CACHE["expires_at"])
def test_status_and_health_share_one_provider_collection(self):
calls = []
def collect(_context):
calls.append(True)
return [{"id": "edge_api"}], ["core.py"]
with mock.patch.object(app, "load_config", return_value={"cache_ttl_sec": 15}), \
mock.patch.object(app, "collect_provider_cards", side_effect=collect), \
mock.patch.object(app, "get_identity_payload", return_value={}):
health = app.build_health_services_payload()
status = app.build_status_payload()
self.assertEqual([{"id": "edge_api"}], health["services"])
self.assertEqual([{"id": "edge_api"}], status["services"])
self.assertEqual(1, len(calls))
def test_concurrent_requests_share_one_collection(self): def test_concurrent_requests_share_one_collection(self):
started = threading.Event() started = threading.Event()
@ -70,25 +53,6 @@ class HealthServicesCacheTest(unittest.TestCase):
self.assertEqual(1, len(calls)) self.assertEqual(1, len(calls))
def test_provider_modules_run_in_parallel_and_keep_order(self):
barrier = threading.Barrier(2)
def provider(service_id):
def collect(_context):
barrier.wait(1)
return {"id": service_id}
return collect
providers = [
("/providers/first.py", provider("first")),
("/providers/second.py", provider("second")),
]
with mock.patch.object(app, "load_providers", return_value=providers):
cards, names = app.collect_provider_cards({})
self.assertEqual(["first", "second"], [card["id"] for card in cards])
self.assertEqual(["first.py", "second.py"], names)
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()

View File

@ -15,6 +15,7 @@
--surface-connected:rgba(14,122,83,.08); --surface-connected:rgba(14,122,83,.08);
--surface-idle:#f7f8f7; --surface-idle:#f7f8f7;
--button-primary:#16211d; --button-primary:#16211d;
--button-primary-ink:#fff;
--button-primary-hover:#22302b; --button-primary-hover:#22302b;
--button-secondary:#eef3f1; --button-secondary:#eef3f1;
--button-secondary-hover:#e4ece8; --button-secondary-hover:#e4ece8;
@ -52,12 +53,29 @@
--log-empty:#86968e; --log-empty:#86968e;
--shadow:0 16px 40px rgba(0,0,0,.28); --shadow:0 16px 40px rgba(0,0,0,.28);
} }
/* EVAx10 Android uses the shared Console components and client SettingsTheme palette. */
[data-console-brand="evax10"]{
--bg:#f1f4fa; --bg-top:#f7f9fd; --ink:#162338; --muted:#52647b;
--line:#d7e0ed; --accent:#087c6a; --brand-glow:rgba(83,220,192,.10);
--button-primary:#193d3c; --button-primary-hover:#24504c;
--surface-strong:#e5eeef; --surface-connected:rgba(83,220,192,.10);
}
[data-console-brand="evax10"][data-theme="dark"]{
--bg:#0a101a; --bg-top:#0a101a; --panel:#111c2b; --ink:#e6edf7;
--muted:#94a8c1; --line:#2b3d53; --accent:#53dcc0;
--surface-soft:#152235; --surface-muted:#19283b; --surface-strong:#193d3c;
--surface-empty:#111c2b; --surface-idle:#152235;
--button-primary:#53dcc0; --button-primary-hover:#70e6cf; --button-primary-ink:#0a101a;
--button-secondary:#19283b; --button-secondary-hover:#263a52;
--log-bg:#0a101a; --log-ink:#e6edf7; --log-empty:#94a8c1;
}
[data-console-brand="evax10"] .brandDevice{width:88px;max-height:88px;border-radius:20px}
*{box-sizing:border-box} *{box-sizing:border-box}
body{ body{
margin:0; margin:0;
font-family:system-ui,-apple-system,"Segoe UI",sans-serif; font-family:system-ui,-apple-system,"Segoe UI",sans-serif;
background: background:
radial-gradient(circle at top left, rgba(14,122,83,.10), transparent 32%), radial-gradient(circle at top left, var(--brand-glow, rgba(14,122,83,.10)), transparent 32%),
linear-gradient(180deg, var(--bg-top) 0%, var(--bg) 100%); linear-gradient(180deg, var(--bg-top) 0%, var(--bg) 100%);
color:var(--ink); color:var(--ink);
} }
@ -75,7 +93,7 @@ html[dir="rtl"] .emptyInline,
html[dir="rtl"] .banner{ html[dir="rtl"] .banner{
text-align:right; text-align:right;
} }
.shell{max-width:1600px;margin:0 auto;padding:28px 18px 40px} .shell{max-width:1180px;margin:0 auto;padding:28px 18px 40px}
.hero{ .hero{
display:grid;grid-template-columns:minmax(0,1fr) auto auto;gap:16px;align-items:center; display:grid;grid-template-columns:minmax(0,1fr) auto auto;gap:16px;align-items:center;
margin-bottom:18px; margin-bottom:18px;
@ -340,7 +358,7 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
border-radius:999px;padding:10px 16px;font-size:14px;font-weight:700;cursor:pointer; border-radius:999px;padding:10px 16px;font-size:14px;font-weight:700;cursor:pointer;
} }
.tabBtn.is-active{ .tabBtn.is-active{
background:var(--button-primary);color:#fff;border-color:var(--button-primary); background:var(--button-primary);color:var(--button-primary-ink);border-color:var(--button-primary);
} }
.tabBtn:hover:not(.is-active):not(:disabled){ .tabBtn:hover:not(.is-active):not(:disabled){
background:var(--surface-soft);border-color:var(--line); background:var(--surface-soft);border-color:var(--line);
@ -378,10 +396,6 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
.cards{ .cards{
display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:16px; display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:16px;
} }
.healthServiceGrid{
grid-template-columns:repeat(3,minmax(0,1fr));
align-items:start;
}
.itscreenCards{ .itscreenCards{
grid-template-columns:repeat(2,minmax(0,1fr)); grid-template-columns:repeat(2,minmax(0,1fr));
align-items:start; align-items:start;
@ -391,40 +405,6 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
.cards > .card{height:100%} .cards > .card{height:100%}
.cardTop{display:flex;justify-content:space-between;gap:12px;align-items:flex-start} .cardTop{display:flex;justify-content:space-between;gap:12px;align-items:flex-start}
.serviceCard{display:flex;flex-direction:column} .serviceCard{display:flex;flex-direction:column}
.healthServiceGrid .serviceProfileCard{
display:grid;
grid-template-columns:repeat(2,minmax(0,1fr));
column-gap:20px;
align-content:start;
}
.healthServiceGrid .itscreenServiceCard{
grid-column:span 2;
grid-template-columns:repeat(3,minmax(0,1fr));
}
.healthServiceGrid .serviceProfileCard > .cardTop,
.healthServiceGrid .serviceProfileCard > .serviceSummary,
.healthServiceGrid .serviceProfileCard > .banner,
.healthServiceGrid .serviceProfileCard > .emptyInline,
.healthServiceGrid .serviceProfileCard > .serviceAlertSection{
grid-column:1 / -1;
}
.serviceSummary{
display:grid;
grid-template-columns:repeat(3,minmax(0,1fr));
gap:10px;
margin-top:14px;
padding:10px 12px;
border:1px solid var(--line);
border-radius:12px;
background:var(--surface-soft);
}
.serviceSummaryItem{display:grid;gap:3px;min-width:0}
.serviceSummaryItem .key{color:var(--muted);font-size:11px;text-transform:uppercase;letter-spacing:.06em}
.serviceSummaryValue{min-width:0;overflow-wrap:anywhere;font-size:13px}
.healthServiceGrid .serviceProfileCard > .list{min-width:0;align-self:start}
.healthServiceGrid .serviceProfileCard > .serviceDetailsWide{grid-column:1 / -1}
.serviceDetailsWide .compactMeta{grid-template-columns:minmax(90px,24%) minmax(0,1fr)}
.serviceProfileAside{min-width:0}
.card h2{margin:0;font-size:19px} .card h2{margin:0;font-size:19px}
.cardSubtitle{margin:6px 0 0;color:var(--muted);font-size:13px} .cardSubtitle{margin:6px 0 0;color:var(--muted);font-size:13px}
.badge{ .badge{
@ -923,7 +903,7 @@ html[dir="rtl"] .itscreenLogsActions{
border:0;border-radius:12px;background:var(--ink);color:#fff;padding:10px 14px;font-weight:700;cursor:pointer; border:0;border-radius:12px;background:var(--ink);color:#fff;padding:10px 14px;font-weight:700;cursor:pointer;
display:inline-flex;align-items:center;justify-content:center;text-decoration:none; display:inline-flex;align-items:center;justify-content:center;text-decoration:none;
} }
.actionBtn{background:var(--button-primary)} .actionBtn{background:var(--button-primary);color:var(--button-primary-ink)}
.actionBtn:hover:not(:disabled){background:var(--button-primary-hover)} .actionBtn:hover:not(:disabled){background:var(--button-primary-hover)}
.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)}
@ -1664,17 +1644,11 @@ html[dir="rtl"] .timezoneOption{text-align:right}
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)}
} }
@media (max-width:1100px){
.healthServiceGrid{grid-template-columns:repeat(2,minmax(0,1fr))}
}
@media (max-width:940px){ @media (max-width:940px){
.hero{grid-template-columns:1fr} .hero{grid-template-columns:1fr}
.identityPanel{min-width:0} .identityPanel{min-width:0}
.gboxHero{grid-template-columns:1fr} .gboxHero{grid-template-columns:1fr}
.itscreenCards{grid-template-columns:repeat(2,minmax(0,1fr))} .itscreenCards{grid-template-columns:repeat(2,minmax(0,1fr))}
.healthServiceGrid .serviceProfileCard{grid-template-columns:1fr}
.healthServiceGrid .itscreenServiceCard{grid-template-columns:repeat(2,minmax(0,1fr))}
.serviceSummary{grid-template-columns:repeat(2,minmax(0,1fr))}
} }
@media (max-width:720px){ @media (max-width:720px){
.brand{flex-direction:column;align-items:flex-start} .brand{flex-direction:column;align-items:flex-start}
@ -1686,7 +1660,6 @@ html[dir="rtl"] .timezoneOption{text-align:right}
.tunnelSummaryGrid{grid-template-columns:repeat(2,minmax(0,1fr))} .tunnelSummaryGrid{grid-template-columns:repeat(2,minmax(0,1fr))}
.brandDevice{width:min(70vw, 260px);max-height:180px} .brandDevice{width:min(70vw, 260px);max-height:180px}
.wideCard,.displayCard,.accessPointCard{grid-column:auto} .wideCard,.displayCard,.accessPointCard{grid-column:auto}
.healthServiceGrid .itscreenServiceCard{grid-column:auto;grid-template-columns:1fr}
.audioDeviceGrid{grid-template-columns:1fr} .audioDeviceGrid{grid-template-columns:1fr}
.displayDetailsRow{grid-template-columns:1fr;align-items:start} .displayDetailsRow{grid-template-columns:1fr;align-items:start}
.displayModePanel{ .displayModePanel{
@ -1697,7 +1670,6 @@ html[dir="rtl"] .timezoneOption{text-align:right}
} }
.displayHeroText{font-size:18px} .displayHeroText{font-size:18px}
.itscreenCards{grid-template-columns:1fr} .itscreenCards{grid-template-columns:1fr}
.healthServiceGrid{grid-template-columns:1fr}
.itscreenLogsToolbar{grid-template-columns:1fr} .itscreenLogsToolbar{grid-template-columns:1fr}
.itscreenLogsActions{justify-content:flex-start} .itscreenLogsActions{justify-content:flex-start}
.modbusLayout{grid-template-columns:1fr} .modbusLayout{grid-template-columns:1fr}

Some files were not shown because too many files have changed in this diff Show More