Generated: 2026-07-15
Automated HITSZ (Harbin Institute of Technology, Shenzhen) campus-network authentication — two independent implementations sharing operational constants but no code:
- Android App (primary): Native Kotlin app with foreground service,
WebView-based login,DataStorepreferences. Manual on-device testing. - Python Daemon: Single-file
hitsz_net.py— pure-HTTP Srun login, persistent per-interface session reconciliation, and macOS LaunchAgent service. Synchronouswhile Trueloop plus optional lid watcher.
Both probe http://www.baidu.com for connectivity, detect captive-portal redirects, and authenticate against http://10.248.98.2/srun_portal_pc?ac_id=1&theme=basic2 on a 60-second loop.
| Constant | Value |
|---|---|
| Login URL | http://10.248.98.2/srun_portal_pc?ac_id=1&theme=basic2 |
| Check URL | http://www.baidu.com |
| Poll interval | 60 seconds |
BootReceiver ──(if auto-start)──> NetworkMonitorService
│
MainActivity ──(start/stop)─────────────┤
│
┌── while(true) every 60s ──┐
│ │
NetworkChecker.isOnline() │
│ │
┌──────┴──────┐ │
│ offline? │ │
└──────┬──────┘ │
│ yes │
LoginManager.login() │
(WebView + JS injection) │
│ │
Notification ─────────────────────┘
NetworkChangeReceiveris passive — logs connectivity changes but does not drive the loop; the service owns the check/login cycle.NetworkCheckeruses two-tier validation:ConnectivityManager+NET_CAPABILITY_VALIDATEDfor local state, then OkHttp GET to Baidu with body inspection for'百度'to rule out captive portals.LoginManagercreates a headlessWebViewonDispatchers.Main, injects JavaScript to fill credentials and click the login button, then verifies viaHttpURLConnectionto Baidu. Falls back through multiple DOM selectors (PC vs mobile Vue.js portal versions). Timeouts: 30s page load, 2s page-load delay, 3s submit delay.PreferencesManageruses JetpackDataStore(notSharedPreferences). Keys:username,password,auto_start. Credentials stored unencrypted.
main() ──> argparse ──> load_config() ──> while True:
│
reconcile_historical_sessions()
(persistent IP history + targeted logout)
│
check_internet()
(requests.get to Baidu)
│
┌──────┴──────┐
│ offline? │
└──────┬──────┘
│ yes
login()
(challenge + encrypted HTTP API)
│
notify()
│
time.sleep(60)
- Config lookup order (fixed): CLI
--configpath >~/.config/hitsz-autonet/.env>/etc/hitsz-autonet/.env>./.env - Pure HTTP login: Queries
rad_user_info, obtains a challenge, computes HMAC-MD5 + Srun XXTEA/base64 + SHA1, then submitssrun_portal; portal requests force-resolvenet.hitsz.edu.cnto10.248.98.2for pre-login DNS failures. - Interface binding (macOS):
InterfaceAdaptersupplies bothsource_addressand DarwinIP_BOUND_IFso probes and login requests cannot drift to another interface. - Persistent session reconciliation: State lives at
~/Library/Application Support/hitsz-autonet/session-state.jsonwith mode0600, keyed by account, interface, and historical IP. Every remembered non-current IP is queried directly; logout requires a fresh exact-IP and account match, a stable default route, acceptedrad_user_dm, and a post-operation offline result. - MAC policy: Portal and hardware MACs are retained as diagnostic metadata. A changed/mismatched MAC triggers a notification but does not block logout because private/random MACs may change; the historical IP plus fresh account ownership are authoritative.
- Capacity diagnostics:
LoginResultcarries rejected-login details. Capacity errors such asE2620notify with portal code/message, current interface/port/IP, device total, and returned device rows. - Error handling: Portal and subprocess failures are logged and retried by the main loop. Credential absence exits immediately; route races and account mismatches fail closed.
| Directory | Purpose |
|---|---|
android-app/ |
Android app: Gradle project, Kotlin source, shell scripts, debug docs |
android-app/app/src/main/java/com/hitsz/autonet/ui/ |
MainActivity — single screen |
android-app/app/src/main/java/com/hitsz/autonet/service/ |
Foreground service + boot/network receivers |
android-app/app/src/main/java/com/hitsz/autonet/utils/ |
LoginManager, NetworkChecker, PreferencesManager |
hitsz_net/ |
Python daemon: monolithic runtime, Srun crypto helper, project metadata |
service/ |
macOS LaunchAgent installer (install.py) — wraps hitsz_net.py |
research-findings/ |
Archival research (~47 .md files, Jan 2026). Reference only; not source of truth |
config/ |
Empty — reserved for future config artifacts |
scripts/ |
Empty — reserved for future automation scripts |
cd android-app
# Build
export JAVA_HOME=/opt/homebrew/opt/openjdk@17
export ANDROID_HOME=/opt/homebrew/share/android-commandlinetools
./gradlew assembleDebug # Debug APK
./gradlew assembleRelease # Release APK (with signing config)
./gradlew lint # Static analysis
# Convenience scripts
./build.sh # Clean assembleDebug with env vars pre-set
adb install -r app/build/outputs/apk/debug/app-debug.apk
# Debugging (require adb + connected device with USB debugging)
./view-logs.sh # Filtered logcat with device check
./clear-and-watch.sh # Clear logs, start fresh stream
./save-logs.sh # Capture 2 min of logs to timestamped file
./install-and-test.sh # Full install + log watching workflow
./test-login.sh # Force-stop, clear logs, watch for login
./quick-test.sh # Shorter variant of test-login.shAll log scripts filter on three tags: LoginManager|NetworkMonitorService|NetworkChecker.
# Install dependencies
uv sync
# Run
uv run hitsz_net/hitsz_net.py --once
uv run hitsz_net/hitsz_net.py --daemon
# macOS service management
uv run service/install.py install --config .env
uv run service/install.py uninstall
uv run service/install.py status
# Handoff contract tests
uv run ./test_handoff.pyService logs: ~/Library/Logs/hitsz-autonet/service.log and error.log.
| Component | Version/Tool | Notes |
|---|---|---|
| Python | >=3.13 | Managed via root uv.lock; dependencies are requests and python-dotenv |
| Kotlin | 2.0.0 | Android |
| AGP | 8.5.0 | Android Gradle Plugin |
| Gradle | 8.7 | Wrapper included |
| compileSdk / targetSdk | 34 (Android 14) | |
| minSdk | 24 (Android 7.0) | |
| JDK | 17 (Homebrew path) | JAVA_HOME=/opt/homebrew/opt/openjdk@17 |
| Android SDK | Command-line tools (Homebrew) | ANDROID_HOME=/opt/homebrew/share/android-commandlinetools |
| File | Role |
|---|---|
hitsz_net/hitsz_net.py |
Python daemon: config, interface binding/handoff, connectivity check, Srun login, retry, notifications |
hitsz_net/pyproject.toml |
Python project metadata + deps |
hitsz_net/uv.lock |
Pinned transitive dependency versions |
hitsz_net/.env.example |
Config template: HITSZ_USERNAME, HITSZ_PASSWORD |
test_handoff.py |
Stdlib unittest coverage for persisted history, targeted logout, MAC alerts, account ownership, capacity failures, and online reconciliation |
service/install.py |
macOS LaunchAgent plist generator + lifecycle (label: com.github.hitsz.autonet) |
android-app/app/build.gradle.kts |
Android dependencies, SDK versions, build config |
android-app/app/src/main/AndroidManifest.xml |
Permissions, components, foregroundServiceType="dataSync" |
android-app/app/src/main/res/xml/network_security_config.xml |
Cleartext allowed for 10.248.98.2 + *.baidu.com only |
android-app/app/src/main/java/com/hitsz/autonet/service/NetworkMonitorService.kt |
Foreground service monitor loop, notifications |
android-app/app/src/main/java/com/hitsz/autonet/utils/LoginManager.kt |
WebView login with JS injection, DOM fallbacks, connectivity verification |
android-app/app/src/main/java/com/hitsz/autonet/utils/NetworkChecker.kt |
Two-tier connectivity check (Android APIs + OkHttp to Baidu) |
android-app/app/src/main/java/com/hitsz/autonet/utils/PreferencesManager.kt |
DataStore-backed credentials + auto-start toggle |
android-app/app/src/main/java/com/hitsz/autonet/service/BootReceiver.kt |
Auto-start service after boot if preference enabled |
android-app/app/src/main/java/com/hitsz/autonet/service/NetworkChangeReceiver.kt |
Passive connectivity change logger (does not drive login) |
android-app/app/src/main/java/com/hitsz/autonet/ui/MainActivity.kt |
Single AppCompatActivity entry point |
- Treat Android and Python as parallel implementations of the same operational flow, not interchangeable modules.
- Canonical operational constants must stay aligned across platforms (login URL, check URL, 60s interval).
- Do not commit
.envor any credentials. - Do not assume HTTP 200 means internet access — captive-portal detection depends on redirect/content validation against Baidu.
- Monolithic: Runtime orchestration remains in
hitsz_net.py; cryptography lives insrun_crypto.py. - Synchronous: Blocking
while Trueloop withtime.sleep(60); the optional lid watcher is the only background thread. - Historical-IP handoff: Never choose an arbitrary account-wide device. For each remembered IP, require a fresh exact-IP/configured-account match, stable current route, accepted DM response, and post-logout offline state. MAC disagreement is notify-only, never a blocker.
- Config:
python-dotenvkeys are onlyHITSZ_USERNAMEandHITSZ_PASSWORD. - Logging:
force=TruebasicConfigwith%Y-%m-%d %H:%M:%S; expected portal TLS warnings and urllib3 logs are suppressed. - macOS integration:
route,networksetup,ipconfig, DarwinIP_BOUND_IF,osascript, and LaunchAgent labelcom.github.hitsz.autonet.
- Manual DI: No Hilt, no Koin, no Dagger. Dependencies created in
onCreateand passed explicitly. - No Navigation, No ViewModel: Single
AppCompatActivitywith manualfindViewById.ViewBindingcompile flag enabled but unused. - Coroutine patterns:
NetworkMonitorServiceuses a customCoroutineScope(Dispatchers.Default + Job()).BootReceiverfires-and-forgets with a freshCoroutineScope.MainActivityuseslifecycleScope. suspendCancellableCoroutine: Used inLoginManagerto bridge WebView callbacks (onPageFinished,onReceivedError) into coroutine suspension.- DataStore:
preferencesDataStoredelegate extension onContext. Three keys:username,password,auto_start. - Foreground service:
START_STICKYreturn. Notification channelhitsz_autonet_channel(LOW importance). Notification icon:android.R.drawable.ic_dialog_info(no custom icon). - WebView login:
Handler(Looper.getMainLooper()).postDelayed()for delayed DOM readiness — NOTview.postDelayed()(project docs explicitly call this out). - Network security: Cleartext scoped to
10.248.98.2+*.baidu.comvianetwork_security_config.xml. Do NOT broaden this.
- All Android scripts live under
android-app/. Depend onadbon PATH and a connected device. - Hard-coded Homebrew paths for JDK 17 and Android SDK (macOS development environment).
install-and-test.shhas a maintainer-specific absolute APK path — do not replicate this pattern.- Log filter tag triple (
LoginManager|NetworkMonitorService|NetworkChecker) is hard-coded across all log scripts.
- Do not commit
.envor any credentials. - Do not treat
research-findings/as maintained application code or source of truth. - Do not assume HTTP 200 means internet access.
- Do not break cross-platform constant parity when changing login URL, connectivity target, or retry interval.
- Do not remove or broaden
network_security_config.xml; the cleartext exception is intentionally narrow. - Do not switch WebView delayed handling to
view.postDelayed(). - Do not treat
NetworkChangeReceiveras the primary orchestration path — it is passive. - Do not add child AGENTS.md files under
hitsz_net/,service/,ui/, orutils/unless those areas stop being single-purpose. - Do not hardcode new absolute user paths in scripts.
- Python daemon: Run
uv run ./test_handoff.pyfor handoff contracts, thenuv run hitsz_net/hitsz_net.py --once --config .envfor a real non-daemon cycle and inspect the LaunchAgent log after restart. - Android app: Test dependencies declared in
build.gradle.kts(JUnit, Espresso) but no real test classes exist insrc/test/orsrc/androidTest/. All validation is manual on-device testing withadb logcatfiltering. - Debug workflow: See
android-app/DEBUG.mdfor the operational debugging guide — covers DNS issues, cleartext blocks, form structure changes, WebView DevTools debugging. - The project has no CI pipeline. Builds, linting, and testing are developer-driven.