From 8b9afef36dddf575bb23b174f3a1e9257b05c2ca Mon Sep 17 00:00:00 2001 From: Andrei Smaliak Date: Thu, 29 Oct 2026 13:00:13 +0100 Subject: [PATCH] Add embedded Android Console and native reverse enrollment --- android_console/AndroidManifest.xml | 15 ++ android_console/README.md | 221 ++++++++++++++++++ android_console/THIRD_PARTY.md | 29 +++ android_console/build.sh | 82 +++++++ android_console/export-client-library.sh | 22 ++ .../com/iomatex/console/AndroidClient.java | 160 +++++++++++++ .../com/iomatex/console/AndroidPlatform.java | 103 ++++++++ .../com/iomatex/console/AndroidSettings.java | 62 +++++ .../com/iomatex/console/AndroidUpdates.java | 25 ++ .../src/com/iomatex/console/BootReceiver.java | 8 + .../iomatex/console/ClientRegistration.java | 40 ++++ .../com/iomatex/console/ConsoleBootstrap.java | 42 ++++ .../com/iomatex/console/ConsoleService.java | 139 +++++++++++ .../src/com/iomatex/console/CpuSample.java | 18 ++ .../src/com/iomatex/console/RemoteAccess.java | 202 ++++++++++++++++ .../com/iomatex/console/SetupActivity.java | 16 ++ .../com/iomatex/console/ThermalSensors.java | 35 +++ android_console/test_bench.py | 58 +++++ .../tests/ClientRegistrationTest.java | 20 ++ android_console/tests/CpuSampleTest.java | 11 + android_console/tests/ThermalSensorsTest.java | 21 ++ android_console/tests/browser_bench.cjs | 63 +++++ android_console/tests/test_apk.py | 13 ++ .../tests/test_embedded_contract.py | 33 +++ android_console/tests/test_shared_contract.py | 31 +++ docs/releases/android-console-0.2.0-dev.md | 13 ++ docs/releases/android-console-0.3.0-dev.md | 36 +++ docs/releases/android-console-0.4.0-dev.md | 21 ++ docs/releases/android-console-0.4.1-dev.md | 15 ++ docs/releases/android-console-0.4.2-dev.md | 22 ++ docs/releases/android-console-0.5.0-dev.md | 27 +++ stage_ui/console_core/ARCHITECTURE.md | 29 +++ stage_ui/console_core/frontend/console.css | 24 +- stage_ui/console_core/frontend/console.js | 84 ++++--- stage_ui/console_core/frontend/index.html | 2 +- 35 files changed, 1704 insertions(+), 38 deletions(-) create mode 100644 android_console/AndroidManifest.xml create mode 100644 android_console/README.md create mode 100644 android_console/THIRD_PARTY.md create mode 100644 android_console/build.sh create mode 100755 android_console/export-client-library.sh create mode 100644 android_console/src/com/iomatex/console/AndroidClient.java create mode 100644 android_console/src/com/iomatex/console/AndroidPlatform.java create mode 100644 android_console/src/com/iomatex/console/AndroidSettings.java create mode 100644 android_console/src/com/iomatex/console/AndroidUpdates.java create mode 100644 android_console/src/com/iomatex/console/BootReceiver.java create mode 100644 android_console/src/com/iomatex/console/ClientRegistration.java create mode 100644 android_console/src/com/iomatex/console/ConsoleBootstrap.java create mode 100644 android_console/src/com/iomatex/console/ConsoleService.java create mode 100644 android_console/src/com/iomatex/console/CpuSample.java create mode 100644 android_console/src/com/iomatex/console/RemoteAccess.java create mode 100644 android_console/src/com/iomatex/console/SetupActivity.java create mode 100644 android_console/src/com/iomatex/console/ThermalSensors.java create mode 100644 android_console/test_bench.py create mode 100644 android_console/tests/ClientRegistrationTest.java create mode 100644 android_console/tests/CpuSampleTest.java create mode 100644 android_console/tests/ThermalSensorsTest.java create mode 100644 android_console/tests/browser_bench.cjs create mode 100644 android_console/tests/test_apk.py create mode 100644 android_console/tests/test_embedded_contract.py create mode 100644 android_console/tests/test_shared_contract.py create mode 100644 docs/releases/android-console-0.2.0-dev.md create mode 100644 docs/releases/android-console-0.3.0-dev.md create mode 100644 docs/releases/android-console-0.4.0-dev.md create mode 100644 docs/releases/android-console-0.4.1-dev.md create mode 100644 docs/releases/android-console-0.4.2-dev.md create mode 100644 docs/releases/android-console-0.5.0-dev.md diff --git a/android_console/AndroidManifest.xml b/android_console/AndroidManifest.xml new file mode 100644 index 0000000..d1ff4c5 --- /dev/null +++ b/android_console/AndroidManifest.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/android_console/README.md b/android_console/README.md new file mode 100644 index 0000000..36e317d --- /dev/null +++ b/android_console/README.md @@ -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. diff --git a/android_console/THIRD_PARTY.md b/android_console/THIRD_PARTY.md new file mode 100644 index 0000000..f72ce11 --- /dev/null +++ b/android_console/THIRD_PARTY.md @@ -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. diff --git a/android_console/build.sh b/android_console/build.sh new file mode 100644 index 0000000..d2c5acb --- /dev/null +++ b/android_console/build.sh @@ -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']*data-tab="(?!(?:health|tscreen|security|network)")[^"]+"[^>]*>.*?','',s) +s=s.replace('','').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" diff --git a/android_console/export-client-library.sh b/android_console/export-client-library.sh new file mode 100755 index 0000000..3737acd --- /dev/null +++ b/android_console/export-client-library.sh @@ -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='''''' +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 diff --git a/android_console/src/com/iomatex/console/AndroidClient.java b/android_console/src/com/iomatex/console/AndroidClient.java new file mode 100644 index 0000000..f71a7c7 --- /dev/null +++ b/android_console/src/com/iomatex/console/AndroidClient.java @@ -0,0 +1,160 @@ +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(); + 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="Client settings channel is unavailable ("+e.getClass().getSimpleName()+")"; } + sampledAt=System.currentTimeMillis(); + } + 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)); + } + 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(!operation.tryLock())throw new IllegalStateException("Client operation already in progress"); + try { + 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() get server / register. */ + final class Channel implements AutoCloseable { + final MqttClient mqtt; + final BlockingQueue 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(){ + 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)); + } +} diff --git a/android_console/src/com/iomatex/console/AndroidSettings.java b/android_console/src/com/iomatex/console/AndroidSettings.java new file mode 100644 index 0000000..42fc5ca --- /dev/null +++ b/android_console/src/com/iomatex/console/AndroidSettings.java @@ -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."); + } +} diff --git a/android_console/src/com/iomatex/console/AndroidUpdates.java b/android_console/src/com/iomatex/console/AndroidUpdates.java new file mode 100644 index 0000000..a203ab7 --- /dev/null +++ b/android_console/src/com/iomatex/console/AndroidUpdates.java @@ -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); + } +} diff --git a/android_console/src/com/iomatex/console/BootReceiver.java b/android_console/src/com/iomatex/console/BootReceiver.java new file mode 100644 index 0000000..ac8e512 --- /dev/null +++ b/android_console/src/com/iomatex/console/BootReceiver.java @@ -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); + } +} diff --git a/android_console/src/com/iomatex/console/ClientRegistration.java b/android_console/src/com/iomatex/console/ClientRegistration.java new file mode 100644 index 0000000..2de9d74 --- /dev/null +++ b/android_console/src/com/iomatex/console/ClientRegistration.java @@ -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 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{ + 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); + } +} diff --git a/android_console/src/com/iomatex/console/ConsoleService.java b/android_console/src/com/iomatex/console/ConsoleService.java new file mode 100644 index 0000000..a21c752 --- /dev/null +++ b/android_console/src/com/iomatex/console/ConsoleService.java @@ -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(16)); + private final Map 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=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 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(nowe.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();} +} diff --git a/android_console/src/com/iomatex/console/CpuSample.java b/android_console/src/com/iomatex/console/CpuSample.java new file mode 100644 index 0000000..b9309dc --- /dev/null +++ b/android_console/src/com/iomatex/console/CpuSample.java @@ -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; + } +} diff --git a/android_console/src/com/iomatex/console/RemoteAccess.java b/android_console/src/com/iomatex/console/RemoteAccess.java new file mode 100644 index 0000000..7df2d6d --- /dev/null +++ b/android_console/src/com/iomatex/console/RemoteAccess.java @@ -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= 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(); } +} diff --git a/android_console/src/com/iomatex/console/SetupActivity.java b/android_console/src/com/iomatex/console/SetupActivity.java new file mode 100644 index 0000000..4a70fd5 --- /dev/null +++ b/android_console/src/com/iomatex/console/SetupActivity.java @@ -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); + } +} diff --git a/android_console/src/com/iomatex/console/ThermalSensors.java b/android_console/src/com/iomatex/console/ThermalSensors.java new file mode 100644 index 0000000..f909b2f --- /dev/null +++ b/android_console/src/com/iomatex/console/ThermalSensors.java @@ -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 read(File root){ + List 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)&°rees>=-50&°rees<=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 "";}} +} diff --git a/android_console/test_bench.py b/android_console/test_bench.py new file mode 100644 index 0000000..0b346fe --- /dev/null +++ b/android_console/test_bench.py @@ -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') diff --git a/android_console/tests/ClientRegistrationTest.java b/android_console/tests/ClientRegistrationTest.java new file mode 100644 index 0000000..486af6c --- /dev/null +++ b/android_console/tests/ClientRegistrationTest.java @@ -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"); + } +} diff --git a/android_console/tests/CpuSampleTest.java b/android_console/tests/CpuSampleTest.java new file mode 100644 index 0000000..bba8656 --- /dev/null +++ b/android_console/tests/CpuSampleTest.java @@ -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"); + } +} diff --git a/android_console/tests/ThermalSensorsTest.java b/android_console/tests/ThermalSensorsTest.java new file mode 100644 index 0000000..32533c9 --- /dev/null +++ b/android_console/tests/ThermalSensorsTest.java @@ -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 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 paths=Files.walk(root)){paths.sorted(Comparator.reverseOrder()).forEach(p->{try{Files.delete(p);}catch(Exception ignored){}});}} + } +} diff --git a/android_console/tests/browser_bench.cjs b/android_console/tests/browser_bench.cjs new file mode 100644 index 0000000..476db25 --- /dev/null +++ b/android_console/tests/browser_bench.cjs @@ -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); +})(); diff --git a/android_console/tests/test_apk.py b/android_console/tests/test_apk.py new file mode 100644 index 0000000..cef7d16 --- /dev/null +++ b/android_console/tests/test_apk.py @@ -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') diff --git a/android_console/tests/test_embedded_contract.py b/android_console/tests/test_embedded_contract.py new file mode 100644 index 0000000..6c6a495 --- /dev/null +++ b/android_console/tests/test_embedded_contract.py @@ -0,0 +1,33 @@ +"""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) +if __name__=='__main__':unittest.main() diff --git a/android_console/tests/test_shared_contract.py b/android_console/tests/test_shared_contract.py new file mode 100644 index 0000000..0e22c2f --- /dev/null +++ b/android_console/tests/test_shared_contract.py @@ -0,0 +1,31 @@ +"""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('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() diff --git a/docs/releases/android-console-0.2.0-dev.md b/docs/releases/android-console-0.2.0-dev.md new file mode 100644 index 0000000..86a2526 --- /dev/null +++ b/docs/releases/android-console-0.2.0-dev.md @@ -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. diff --git a/docs/releases/android-console-0.3.0-dev.md b/docs/releases/android-console-0.3.0-dev.md new file mode 100644 index 0000000..3244cad --- /dev/null +++ b/docs/releases/android-console-0.3.0-dev.md @@ -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. diff --git a/docs/releases/android-console-0.4.0-dev.md b/docs/releases/android-console-0.4.0-dev.md new file mode 100644 index 0000000..630ceb6 --- /dev/null +++ b/docs/releases/android-console-0.4.0-dev.md @@ -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. diff --git a/docs/releases/android-console-0.4.1-dev.md b/docs/releases/android-console-0.4.1-dev.md new file mode 100644 index 0000000..080fc36 --- /dev/null +++ b/docs/releases/android-console-0.4.1-dev.md @@ -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. diff --git a/docs/releases/android-console-0.4.2-dev.md b/docs/releases/android-console-0.4.2-dev.md new file mode 100644 index 0000000..99606a3 --- /dev/null +++ b/docs/releases/android-console-0.4.2-dev.md @@ -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. diff --git a/docs/releases/android-console-0.5.0-dev.md b/docs/releases/android-console-0.5.0-dev.md new file mode 100644 index 0000000..6620828 --- /dev/null +++ b/docs/releases/android-console-0.5.0-dev.md @@ -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. diff --git a/stage_ui/console_core/ARCHITECTURE.md b/stage_ui/console_core/ARCHITECTURE.md index d50321a..d11ec51 100644 --- a/stage_ui/console_core/ARCHITECTURE.md +++ b/stage_ui/console_core/ARCHITECTURE.md @@ -65,3 +65,32 @@ 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 confirmation dialog. No new CSS or independent modal/serial transport is added. + +## Android adapter (development) + +`android_console` packages this frontend verbatim, with the EVAx10 brand and a +supported-tab allowlist; it must not carry its own HTML/JS/CSS component copy. +AndroidPlatform and AndroidClient implement the same health, display and client +registration URLs. DeviceSettingsMessenger remains the owner of client actions; +Console may adapt transport but must not create a second registration store or +write the client's private configuration. RemoteAccess follows canonical +RegistrationStore changes and projects readiness into the shared reverse card. + +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. diff --git a/stage_ui/console_core/frontend/console.css b/stage_ui/console_core/frontend/console.css index 9da732a..ff7f2a1 100644 --- a/stage_ui/console_core/frontend/console.css +++ b/stage_ui/console_core/frontend/console.css @@ -15,6 +15,7 @@ --surface-connected:rgba(14,122,83,.08); --surface-idle:#f7f8f7; --button-primary:#16211d; + --button-primary-ink:#fff; --button-primary-hover:#22302b; --button-secondary:#eef3f1; --button-secondary-hover:#e4ece8; @@ -52,12 +53,29 @@ --log-empty:#86968e; --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} body{ margin:0; font-family:system-ui,-apple-system,"Segoe UI",sans-serif; 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%); color:var(--ink); } @@ -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; } .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){ background:var(--surface-soft);border-color:var(--line); @@ -885,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; 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.secondary{background:var(--button-secondary);color:var(--ink);border:1px solid var(--line)} .actionBtn.secondary:hover:not(:disabled){background:var(--button-secondary-hover)} diff --git a/stage_ui/console_core/frontend/console.js b/stage_ui/console_core/frontend/console.js index 42208df..b3739d5 100644 --- a/stage_ui/console_core/frontend/console.js +++ b/stage_ui/console_core/frontend/console.js @@ -42,6 +42,8 @@ toastStack: document.getElementById("toastStack") }; + const isEvax10Console = document.documentElement.dataset.consoleBrand === "evax10"; + const ITSCREEN_SERVER_OPTIONS = [ { mode: "dev", label: "dev.it-screen.com", host: "rest.dev.it-screen.com" }, { mode: "uae", label: "uae.iomatex.com", host: "rest.uae.iomatex.com" }, @@ -290,7 +292,7 @@ bootstrapOpen: false, configuring: false }, - theme: "light", + theme: loadThemePreference(), language: "en", audioActions: { busyTarget: "", @@ -963,10 +965,10 @@ } function applyStaticTranslations() { - document.title = t("IOMATEX Console"); - if (nodes.brandEyebrow) nodes.brandEyebrow.textContent = "IOMATEX G-Box"; - if (nodes.heroTitle) nodes.heroTitle.textContent = t("Edge Automation Gateway"); - if (nodes.capabilityBadge) nodes.capabilityBadge.textContent = t("Digital DNA ready"); + document.title = isEvax10Console ? "EVAx10 Console" : t("IOMATEX Console"); + if (nodes.brandEyebrow) nodes.brandEyebrow.textContent = isEvax10Console ? "EVAx10 · Android" : "IOMATEX G-Box"; + if (nodes.heroTitle) nodes.heroTitle.textContent = isEvax10Console ? "EVAx10 Console" : t("Edge Automation Gateway"); + if (nodes.capabilityBadge) nodes.capabilityBadge.textContent = isEvax10Console ? "Android" : t("Digital DNA ready"); if (nodes.osLabel) nodes.osLabel.textContent = t("Unified diagnostics, network operations and gateway commissioning."); if (nodes.edgeSerialLabel) nodes.edgeSerialLabel.textContent = t("Edge Serial Number"); if (nodes.hostIpLabel) nodes.hostIpLabel.textContent = t("Host / IP"); @@ -981,7 +983,7 @@ if (nodes.tabSecurity) nodes.tabSecurity.textContent = t("Security & Region"); if (nodes.tabNetwork) nodes.tabNetwork.textContent = t("Network"); if (nodes.tabModbus) nodes.tabModbus.textContent = t("Modbus"); - if (nodes.tabTscreen) nodes.tabTscreen.textContent = t("It-Screen"); + if (nodes.tabTscreen) nodes.tabTscreen.textContent = "EVAx10"; if (nodes.tabGbox) nodes.tabGbox.textContent = t("G-Box Instructions and Manual"); const nav = document.querySelector(".tabs"); if (nav) nav.setAttribute("aria-label", t("Primary navigation")); @@ -1145,6 +1147,7 @@ } function boolPill(label, value) { + if (value === null) return `${esc(t(label))}: ${esc(t("Unknown"))}`; return `${esc(t(label))}: ${value ? t("yes") : t("no")}`; } @@ -1548,7 +1551,7 @@
- ${esc(t("Configure remote access using the saved device registration. If setup was skipped or failed, try again here without registering the device again. Each click makes one attempt."))} + ${esc(t(card.configuration_hint || "Configure remote access using the saved device registration. If setup was skipped or failed, try again here without registering the device again. Each click makes one attempt."))}
${bootstrapCommand ? ` @@ -1581,10 +1584,10 @@
${esc(t("Actions"))}
- -
@@ -1795,6 +1798,7 @@ function itscreenCanRegister(registration) { if (state.itscreen.busyAction || state.itscreen.loading) return false; + if (registration && registration.capabilities && registration.capabilities.can_register === false) return false; if (itscreenHostValidationError()) return false; if (!(registration && registration.registered)) return true; return comparableServerAddress(itscreenResolvedHost()) !== comparableServerAddress(registration.server || registration.host); @@ -1859,7 +1863,7 @@
${boolPill("Installed", !!card.installed)} ${boolPill("Configured", !!card.configured)} - ${boolPill("Active", !!card.active)} + ${boolPill("Active", card.active === null ? null : !!card.active)}
${renderServiceActions(card)} @@ -1940,11 +1944,11 @@
${esc(t("Thermals"))}
${renderKeyValueRows(thermalRows)}
-
+ ${!storage || storage.supported !== false ? `
${esc(t("Storage"))}
${renderKeyValueRows(storageHealthRows(storage))}
${esc(t("Wear is a coarse JEDEC estimate. This eMMC does not expose exact power-on hours or write cycles."))}
-
+
` : ""} `; @@ -2064,7 +2068,7 @@
${renderKeyValueRows(details)}
-
- + ` : ""} -
+ ${!card.capabilities || card.capabilities.pulse_audio !== false ? `
${esc(t("Audio diagnostics"))}
${renderAudioDevice(audioDevices.hdmi || { target: "hdmi", label: "HDMI audio" }, "Test HDMI sound")} @@ -2093,6 +2097,7 @@
${pulseErrors.length ? `
${esc(pulseErrors.join("\n"))}
` : ""}
+ ` : ""}
- ${connectors.length ? `
${connectors.map(renderConnector).join("")}
` : `
${esc(t("No DRM connectors detected."))}
`} + ${connectors.length ? `
${connectors.map(renderConnector).join("")}
` : `
${esc(t("No display connectors detected."))}
`}
@@ -2462,7 +2467,7 @@ const reason = updates.busy ? t("Another installation is running") : updates.checking ? t("Checking versions...") : updates.error ? t(updates.error) - : needsCheck ? t("Check available versions before installing.") : ""; + : release.reason ? t(release.reason) : needsCheck ? t("Check available versions before installing.") : ""; const versionButton = ``; return `
${compact ? renderPanelTitle(t(card.title), `service:${card.id}`, "", versionButton) : `
${esc(t("Stage version"))}
@@ -2532,7 +2537,7 @@
${boolPill("Installed", !!card.installed)} ${boolPill("Configured", !!card.configured)} - ${boolPill("Active", !!card.active)} + ${boolPill("Active", card.active === null ? null : !!card.active)}
${renderServiceActions(card)} @@ -2573,7 +2578,7 @@
- ${renderPanelTitle(t("Account security"), "security_account", t("Change the WEB UI login password for the local iomatex user."))} + ${renderPanelTitle(t("Account security"), "security_account", t(isEvax10Console ? "Change the Android Console login password. EVAx10 registration and the Android lock screen are unchanged." : "Change the WEB UI login password for the local iomatex user."))}
@@ -2587,7 +2592,7 @@ ${account.message ? `` : ""} ${account.error ? `` : ""}
- +
@@ -2595,6 +2600,7 @@ } function renderPasswordRecoveryPanel() { + if (isEvax10Console) return renderSimplePanel(t("Forgot password?"), [{label: t("Recovery"), value: t("Use authorized local ADB access to recover the Android Console account. Debian sudo iomatex-passwd does not apply to Android.")}]); return `
@@ -2743,7 +2749,7 @@ const updateJob = updates.job || {}; const jobLabels = { queued: "Queued", running: "Installing...", success: "Installation completed", failed: "Installation failed", interrupted: "Installation interrupted" }; const metrics = [ - { label: t("CPU usage"), value: health.cpu_usage_percent === null || health.cpu_usage_percent === undefined ? t("Collecting...") : `${health.cpu_usage_percent}%` }, + { label: t("CPU usage"), value: health.cpu_usage_percent === null || health.cpu_usage_percent === undefined ? t(health.cpu_usage_supported === false ? "Not available" : "Collecting...") : `${health.cpu_usage_percent}%` }, renderLoadAverageMetric(health), { label: t("Disk usage"), value: health.disk && health.disk.used_percent !== undefined ? `${health.disk.used_percent}% ${t("used")}` : t("Not available") } ]; @@ -2782,11 +2788,11 @@

${esc(t("Installed Services"))}

${renderHelpButton("service_generic")}

${esc(t("Core diagnostics and service state from providers."))}

-
+ ${updates.supported === false ? "" : `
${esc(t("Last version check"))}: ${esc(updates.checked_at ? new Date(updates.checked_at * 1000).toLocaleString() : t("Not checked"))} -
+
`} ${updates.error ? `` : ""} ${updateJob.state ? `` : ""}
@@ -2827,7 +2833,7 @@ const errorNode = document.getElementById("wifiFormError"); const successNode = document.getElementById("wifiFormSuccess"); const validationError = networkValidationError(); - if (applyBtn) applyBtn.disabled = !!(state.networkForm.busy || validationError); + if (applyBtn) applyBtn.disabled = !!(state.networkForm.busy || validationError || (state.networkForm.ssid === ((state.network || {}).desired_profile || {}).ssid && !state.networkForm.password)); if (errorNode) { errorNode.textContent = validationError || state.networkForm.error || ""; errorNode.hidden = !(validationError || state.networkForm.error); @@ -3049,7 +3055,7 @@ const canStartService = !!((typeof capabilities.can_start === "boolean" ? capabilities.can_start : (service.installed && service.status !== "running")) && !serviceBusy); const canStopService = !!((typeof capabilities.can_stop === "boolean" ? capabilities.can_stop : (service.installed && service.status !== "stopped" && service.status !== "not_installed")) && !serviceBusy); const selectedServerDiffers = payload && payload.registered && comparableServerAddress(serverHost) !== comparableServerAddress(payload.server || payload.host); - const registerHelper = payload && payload.registered && !selectedServerDiffers + const registerHelper = payload && payload.capability_reason ? t(payload.capability_reason) : payload && payload.registered && !selectedServerDiffers ? t("Device is already registered on the selected server") : (hostError || (selectedServerDiffers ? t("Register the device on the newly selected server.") : t("Select the target cloud server and start registration."))); const serviceWarnings = Array.isArray(service && service.warnings) ? service.warnings : []; @@ -3142,7 +3148,7 @@
${esc(hostError)}
- +
${busy === "register" ? `
@@ -3188,7 +3194,7 @@
- ${renderItscreenLogsCard()} + ${capabilities.logs === false ? "" : renderItscreenLogsCard()}
`; @@ -3471,6 +3477,7 @@ if (logs.request) return logs.request; logs.request = (async () => { try { + if ((itscreenService().capabilities || {}).logs === false) return; const payload = await fetchJson(`/api/itscreen/logs?lines=${encodeURIComponent(String(lines))}`, { cache: "no-store" }); const incoming = Array.isArray(payload.lines) ? payload.lines.map((line) => (line ?? "").toString()) : []; logs.buffer = replace ? trimItscreenLogBuffer(incoming) : trimItscreenLogBuffer(logs.buffer.concat(incoming)); @@ -3504,6 +3511,7 @@ updateItscreenLogsUi(); return; } + if ((itscreenService().capabilities || {}).logs === false) return; const source = new EventSource("/api/itscreen/logs/stream"); logs.eventSource = source; logs.status = "disconnected"; @@ -4817,8 +4825,8 @@
- -
${esc(t("IOMATEX EDGE"))}
+ +
${esc(isEvax10Console ? "EVAx10 · Android" : t("IOMATEX EDGE"))}

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

${renderHelpButton("auth_webui")}

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

@@ -4836,11 +4844,11 @@
- -
${esc(t("IOMATEX EDGE"))}
+ +
${esc(isEvax10Console ? "EVAx10 · Android" : t("IOMATEX EDGE"))}

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

${renderHelpButton("auth_webui")}

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

-

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

+

${esc(t(isEvax10Console ? "Session expires after 15 minutes." : "Session stays active for up to 1 hour after your last action."))}

@@ -4872,7 +4880,12 @@ state.identity = safe; nodes.edgeId.textContent = safe.serial_number || "-"; nodes.hostName.textContent = currentHostLabel(); - nodes.osLabel.textContent = t("Unified diagnostics, network operations and gateway commissioning."); + nodes.osLabel.textContent = safe.os || t("Unified diagnostics, network operations and gateway commissioning."); + if (safe.platform === "android") { + nodes.brandEyebrow.textContent = "EVAx10 · Android"; + nodes.heroTitle.textContent = "EVAx10 Console"; + nodes.capabilityBadge.textContent = safe.prototype ? "Development prototype" : "Android"; + } } function updateHeaderMeta(payload) { @@ -5486,6 +5499,7 @@ }; window.__applyWifiProfile = async function () { + if (state.networkForm.busy || (state.networkForm.ssid === ((state.network || {}).desired_profile || {}).ssid && !state.networkForm.password)) return; const validationError = networkValidationError(); if (validationError) { state.networkForm.error = validationError; @@ -6704,6 +6718,8 @@ state.accountPassword[field] = (value ?? "").toString(); state.accountPassword.error = ""; state.accountPassword.message = ""; + const button = document.querySelector("[data-account-password-form] button[type=submit]"); + if (button) button.disabled = !!(state.accountPassword.busy || accountPasswordValidationError()); }; window.__accountPasswordToggle = function (field) { @@ -6827,7 +6843,7 @@ window.__timezoneSubmit = async function (event) { if (event && typeof event.preventDefault === "function") event.preventDefault(); const timezone = state.timezone; - if (timezone.busy || !timezone.selected) return; + if (timezone.busy || !timezone.selected || timezone.selected === textValue(timezone.data && timezone.data.timezone, "")) return; const validationError = timezoneValidationError(); if (validationError) { timezone.error = validationError; diff --git a/stage_ui/console_core/frontend/index.html b/stage_ui/console_core/frontend/index.html index 27fe291..25de44c 100644 --- a/stage_ui/console_core/frontend/index.html +++ b/stage_ui/console_core/frontend/index.html @@ -101,7 +101,7 @@ - +