feat: add graphical installer and fix Unisoc WPA3 hotspots

Integrate the shared Tauri installer with resumable installation, offline help, packaging and CI. Harden desktop storage and update flows. Add the firmware SAE bridge, matching hostapd packages and Wi-Fi configuration compatibility for the shared 6.18 and 7.2 driver.
This commit is contained in:
kanoqwq committed 2026-10-15 18:33:34 +08:00
1 parent e114999dac
commit 0e19fe326e
111 files changed
+20241 -42

No files matched your search

+39
View File
@@ -0,0 +1,39 @@
name: Portable Windows installer
on:
workflow_call:
workflow_dispatch:
push:
paths: ['installer/**', 'desktop/**', 'tools/add-desktop-installer.py', '.github/workflows/gui.yml']
pull_request:
paths: ['installer/**', 'desktop/**', 'tools/add-desktop-installer.py', '.github/workflows/gui.yml']
permissions:
contents: read
jobs:
windows:
runs-on: windows-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.12'
- uses: actions/setup-node@v4
with:
node-version: '22'
cache: npm
cache-dependency-path: installer/ui/package-lock.json
- name: Rust build toolchain
run: rustup toolchain install 1.90.0 --profile minimal
- name: Python build dependencies
run: python -m pip install pyinstaller paramiko lz4
- name: State and recovery tests (no device writes)
run: python -m unittest discover -s installer/tests -v
- name: Build portable release
run: python installer/build.py
- uses: actions/upload-artifact@v4
with:
name: openwrt-installer-windows
path: installer/artifacts/windows/
if-no-files-found: error
+3
View File
@@ -1,5 +1,8 @@
# Linux on the ZTE F50 / MU300 and U30 Air
Windows desktop installer: extract the complete release package and run root `OpenWrt-Installer.exe`. Device selection, persistent recovery and the two-stage Android reset flow share the existing backend. Python/CLI and Magisk entries remain available. See the bilingual [user guide](installer/GUIDE.md), [build instructions](installer/README.md), and [verification/screenshots](installer/VERIFICATION.md). Multiple ADB devices can be selected in the GUI or interactive CLI, or explicitly bound with `--serial SERIAL`.
V50/MU3351 desktop-installer support and the new LED driver are documented in
[the V50 adaptation record](docs/V50-MU3351-20261014.zh-CN.md), including what has
been checked on hardware and what remains unverified.
+3
View File
@@ -4,6 +4,7 @@
set -eu
set -o pipefail
P=${MU300_PAYLOAD_DIR:?};T=${MU300_INSTALL_TMP:?}
. "$P/desktop-settings.env"
. "$P/android-loop.sh"
# BusyBox's losetup lacks a size-limit option. Use Android Toybox explicitly;
# PATH in the installer intentionally points at BusyBox for other applets.
@@ -69,10 +70,12 @@ repair=$P/desktop/files/boot/repair
"$repair/lib/ld-musl-aarch64.so.1" --library-path "$repair/lib:$repair/usr/lib" "$repair/usr/sbin/e2fsck" -pf "$loop" || {
rc=$?; [ "$rc" = 1 ] || exit "$rc";
}
if [ "${GROW_FS:-1}" = 1 ]; then
"$repair/lib/ld-musl-aarch64.so.1" --library-path "$repair/lib:$repair/usr/lib" "$repair/usr/sbin/resize2fs" -f "$loop" "$((need/8))"
"$repair/lib/ld-musl-aarch64.so.1" --library-path "$repair/lib:$repair/usr/lib" "$repair/usr/sbin/e2fsck" -fn "$loop"
low=$(od -An -tu4 -j1028 -N4 "$loop" | tr -d ' \n');high=$(od -An -tu4 -j1360 -N4 "$loop" | tr -d ' \n')
[ "$high" = 0 ] && [ "$low" = "$((need/8))" ]
fi
mount -t ext4 -o ro,noload "$loop" "$T/image-root"
mounted=1
(cd "$T/image-root" && sha256sum -c "$T/image.sha256" >/dev/null)
+3
View File
@@ -3,6 +3,7 @@
set -eu
set -o pipefail
P=${MU300_PAYLOAD_DIR:?};T=${MU300_INSTALL_TMP:?}
. "$P/desktop-settings.env"
dev=${1:?root device}; expected_cid=${2:?cid}; expected_sectors=${3:?size}; expected_sha=${4:?image checksum}
node=${dev##*/};disk=${node%p*}
case "$node" in mmcblk[0-9]p[0-9]*) ;; *) exit 1 ;; esac
@@ -29,9 +30,11 @@ repair=$P/desktop/files/boot/repair
"$repair/lib/ld-musl-aarch64.so.1" --library-path "$repair/lib:$repair/usr/lib" "$repair/usr/sbin/e2fsck" -pf "$dev" || {
rc=$?; [ "$rc" = 1 ] || exit "$rc";
}
if [ "${GROW_FS:-1}" = 1 ]; then
"$repair/lib/ld-musl-aarch64.so.1" --library-path "$repair/lib:$repair/usr/lib" "$repair/usr/sbin/resize2fs" -f "$dev" "$((expected_sectors/8))"
low=$(od -An -tu4 -j1028 -N4 "$dev" | tr -d ' \n');high=$(od -An -tu4 -j1360 -N4 "$dev" | tr -d ' \n')
[ "$high" = 0 ] && [ "$low" = "$((expected_sectors/8))" ]
fi
mount -t ext4 -o ro,noload "$dev" "$T/image-root"
trap 'umount "$T/image-root" 2>/dev/null || :' EXIT
(cd "$T/image-root" && sha256sum -c "$T/image.sha256" >/dev/null)
+3 -14
View File
@@ -1,19 +1,8 @@
#!/usr/bin/env python3
"""Build the optional Windows desktop launcher (pip install pyinstaller paramiko lz4)."""
import hashlib
import json
"""Build the shared Tauri portable GUI (the CLI remains OpenWrt-Installer.py)."""
from pathlib import Path
import subprocess
import sys
HERE=Path(__file__).resolve().parent
out=HERE.parent/'work/desktop-exe';out.mkdir(parents=True,exist_ok=True)
source={n:hashlib.sha256((HERE/n).read_bytes()).hexdigest() for n in ('installer.py','boot_image.py')}
subprocess.run([sys.executable,'-m','PyInstaller','--noconfirm','--clean','--onefile',
'--name','OpenWrt-Installer','--distpath',str(out),'--workpath',str(out/'build'),
'--specpath',str(out),'--hidden-import','lz4.block','--hidden-import','tarfile','--collect-all','paramiko',
str(HERE/'installer.py')],check=True)
if source!={n:hashlib.sha256((HERE/n).read_bytes()).hexdigest() for n in source}:
raise RuntimeError('Installer source changed during EXE compilation; rebuild before packaging')
(out/'OpenWrt-Installer.exe.json').write_text(json.dumps({'source':source},indent=2)+'\n')
print(out/'OpenWrt-Installer.exe')
TOP=Path(__file__).resolve().parents[1]
subprocess.run([sys.executable,str(TOP/'installer/build.py'),*sys.argv[1:]],cwd=TOP,check=True)
+57 -20
View File
@@ -22,6 +22,7 @@ import time
import urllib.request
import uuid
import zlib
GUI = None # Optional structured observer for the shared Tauri backend.
class Outcome:
def __init__(self,state,message,next_step=''):
@@ -118,6 +119,9 @@ def verify(root):
return m
def confirm(message):
if GUI:
GUI.ctx.boundary()
return
print('\n'+message)
if input('Type yes to continue / 输入 yes 继续: ').strip()!='yes': raise InstallerCancelled()
@@ -234,13 +238,13 @@ def env(values):
return ''.join(k+'='+shlex.quote(str(v))+'\n' for k,v in values.items())
def settings(args, image_mib, mode, kernel):
ssid=input('Hotspot name / 热点名称 [import Android]: ').strip()
ssid='' if GUI else input('Hotspot name / 热点名称 [import Android]: ').strip()
key=input('Hotspot key / 热点密码 (visible / 明文输入): ') if ssid else ''
if ssid and (len(ssid.encode())>32 or '\n' in ssid or '\r' in ssid): raise ValueError('SSID must be 1–32 UTF-8 bytes')
if ssid and (not 8<=len(key)<=63 or any(ord(c)<32 or ord(c)>126 for c in key)): raise ValueError('Wi-Fi key must be 8–63 ASCII characters')
apn=input('APN [SIM default / SIM 默认]: ').strip()
apn='' if GUI else input('APN [SIM default / SIM 默认]: ').strip()
if apn and not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9.-]{0,99}',apn):raise ValueError('Invalid APN')
return env({'IMAGE_MIB':image_mib,'DESKTOP_MODE':mode,'KERNEL':kernel,'SSID':ssid,'WIFI_KEY':key,'APN':apn,'PWHASH':''})
return env({'IMAGE_MIB':image_mib,'DESKTOP_MODE':mode,'KERNEL':kernel,'SSID':ssid,'WIFI_KEY':key,'APN':apn,'PWHASH':'','GROW_FS':int(getattr(args,'grow_fs',True))})
class Android:
def __init__(self,args):
@@ -250,6 +254,11 @@ class Android:
serials=[l.split()[0] for l in listing.splitlines() if len(l.split())==2 and l.split()[1]=='device']
if args.serial: self.serial=args.serial
elif len(serials)==1: self.serial=serials[0]
elif len(serials)>1 and sys.stdin.isatty() and not GUI:
for index,serial in enumerate(serials,1):print(f' {index}. Device / 设备 ••••{serial[-4:]}')
selected=input('Select device number / 选择设备编号: ').strip()
if not selected.isdigit() or not 1<=int(selected)<=len(serials):raise ValueError('Invalid device number; use --serial SERIAL')
self.serial=serials[int(selected)-1]
else: raise ValueError('Specify --serial; expected one online Android device: '+repr(serials))
if self.serial not in serials: raise ValueError('Android is not online: '+self.serial)
if self.shell('id -u',root=False).strip()=='0': self.su=False
@@ -270,7 +279,8 @@ class Android:
cmd=[self.adb]
selected=serial if serial is not None else getattr(self,'serial',None)
if selected:cmd+=['-s',selected]
proc=subprocess.Popen(cmd+list(args),stdout=subprocess.PIPE,stderr=subprocess.PIPE)
proc=subprocess.Popen(cmd+list(args),stdout=subprocess.PIPE,stderr=subprocess.PIPE,
**({'creationflags':subprocess.CREATE_NO_WINDOW} if os.name=='nt' else {}))
start=time.monotonic()
while True:
try: out,err=proc.communicate(timeout=min(10,timeout));break
@@ -284,9 +294,12 @@ class Android:
return out
def reboot(self):
if GUI:GUI.reboot()
# The ADB reboot service acknowledges the request before shutting down;
# a root shell may disconnect before it can return an exit status.
self.call('reboot',timeout=30)
try:self.call('reboot',timeout=30)
except (RuntimeError,ConnectionError,EOFError):
if not GUI:raise
print('Reboot request sent / 已发送重启请求。')
def shell(self,script,root=True,timeout=1800):
@@ -302,6 +315,9 @@ class Android:
# adb push runs as Android shell even when su is available. Private
# staging belongs to shell; root remains able to consume it.
self.shell('mkdir -p '+parent+'; chown 2000:2000 '+parent+'; chmod 700 '+parent)
if GUI:
GUI.push(self.call,self.shell,path,remote)
return remote
self.call('push',str(path),remote)
want=digest(path)
got=self.shell('sha256sum '+shlex.quote(remote)).split()[0]
@@ -320,7 +336,10 @@ class Android:
cmd='su -c '+shlex.quote(encoded) if self.su else 'sh -c '+shlex.quote(encoded)
return base64.b64decode(b''.join(self.call('exec-out',cmd).split()),validate=True)
def run(self,body):
def run(self,body,effect=None):
if GUI and effect:
GUI.stage('transfer_install')
return GUI.action(effect,lambda:self.run(body))
script='#!/system/bin/sh\nset -eu\nP='+self.p+'\nT='+self.t+'\nBB='+self.bb+'\nexport MU300_PAYLOAD_DIR=$P MU300_INSTALL_TMP=$T MU300_BUSYBOX=$BB MU300_KEEP_PAYLOAD=1\nmkdir -p "$T/bin"\n"$BB" --install -s "$T/bin"\nexport PATH="$T/bin:$PATH"\n'+body+'\n'
p=self.put(script,'run.sh')
result=self.shell(self.bb+' nsenter -t 1 -m '+self.bb+' sh '+p)
@@ -416,6 +435,10 @@ class Android:
path.joinpath('gpt-layout.json').write_text(json.dumps({'front_sectors':front,'tail_start':tail,'disk_sectors':s['DISK_SIZE']},indent=2)+'\n')
def flash(self,image,bc):
if GUI:return GUI.action('boot-and-misc-'+hashlib.sha256(image).hexdigest()[:16],lambda:self._flash(image,bc))
return self._flash(image,bc)
def _flash(self,image,bc):
self.put(image,'boot-desktop.img');self.put(bc,'misc-linux.bin')
self.run('''[ "$(getprop ro.boot.slot_suffix)" = "_'''+self.slot+'''" ]
"$BB" sh "$P/android-bootchain.sh" sync "$T/bootchain-backup"
@@ -442,12 +465,13 @@ echo 'BOOT-VERIFIED; OpenWrt selected'
def transaction(path,record):
tmp=path.with_suffix('.tmp');tmp.write_text(json.dumps(record,indent=2)+'\n');tmp.replace(path)
if GUI:GUI.saved(path,record)
def validate_resume(s,r,slot,serial,root_geometry,marker):
def validate_resume(s,r,slot,serial,root_geometry,marker,root_verified=False):
if s['CID']!=r['storage']['CID'] or s['NODE']!=r['storage']['NODE'] or s['START']!=r['storage']['START'] or slot!=r['android_slot'] or serial!=r['serial']:
raise ValueError('Resume device/slot differs from the saved transaction')
if s['SIZE']!=r['target'] or root_geometry!=(s['START']+r['target'],r['need']):raise ValueError('Prepared partition geometry differs')
if marker.strip()!=('MU300-PART-PREPARED-V2 '+r['token']).encode():raise ValueError('Preparation token mismatch; refusing to overwrite a root')
if not root_verified and marker.strip()!=('MU300-PART-PREPARED-V2 '+r['token']).encode():raise ValueError('Preparation token mismatch; refusing to overwrite a root')
def resume_payload_id(manifest):
# Paths, EXE, prompts and upload scripts can change in a repair release.
@@ -502,7 +526,8 @@ def load_resume(args,root,manifest,a,s):
if not rootnode:raise ValueError('No prepared mu300root found')
geometry=tuple(int(x) for x in a.shell('cat /sys/class/block/'+rootnode+'/start /sys/class/block/'+rootnode+'/size').split())
marker=a.read('dd if=/dev/block/'+rootnode+' bs=512 count=1 2>/dev/null').split(b'\0',1)[0]
validate_resume(s,r,a.slot,a.serial,geometry,marker)
verified=r.get('state')=='installed' or bool(GUI and GUI.ctx.record['effects'].get('root-part-write',{}).get('state')=='done')
validate_resume(s,r,a.slot,a.serial,geometry,marker,root_verified=verified)
validate_resume_package(root,manifest,r,record)
return record,r,geometry
@@ -540,6 +565,7 @@ def install(args,root,manifest):
if args.tf:
sd=a.shell('if [ -b /dev/block/mmcblk1p1 ]; then echo /dev/block/mmcblk1p1; elif [ -b /dev/block/mmcblk1 ]; then echo /dev/block/mmcblk1; fi').strip()
if not sd:raise ValueError('No TF card found; choose an internal-storage method instead')
if GUI:GUI.validate_plan(sd,capacity=int(a.shell('cat /sys/class/block/'+sd.rsplit('/',1)[-1]+'/size').strip())*512)
confirm('This formats '+sd+'; its existing data will be erased / 会清空所选 TF 分区。')
a.prepare_payload(root,tf=True)
custom=settings(args,2048,'sd',manifest['kernel'])
@@ -568,7 +594,7 @@ def install(args,root,manifest):
a.put(env({'SD_MODE':1,'SD_DEV':sd,'FORMAT':1,'SYNC_BOOTCHAIN':1,'OSES':'openwrt','WIPE_LEGACY':0,'UPDATE':0,'BOOT_OS':'openwrt','DEFAULT_LINUX':1,'BOOT_ATTEMPTS':5,'IMPORT_HOTSPOT':1,'KERNEL':manifest['kernel'],'PWHASH':''}),'mu300-install.env')
# The original TF worker handles release, formatting and readback.
# Only its desktop upload has custom settings and fresh A/B blocks.
a.run('export MU300_TF_BOOTDEV=/dev/block/by-name/boot_'+a.linux+'\n"$BB" sh "$P/tf-install-worker.sh"')
a.run('export MU300_TF_BOOTDEV=/dev/block/by-name/boot_'+a.linux+'\n"$BB" sh "$P/tf-install-worker.sh"',**({'effect':'root-tf-write'} if GUI else {}))
return Outcome('success','TF installation verified / TF 安装和写入校验已完成。','Reboot the device manually / 请手动重启设备。')
base=Path(args.backup_dir).expanduser()
if args.resume:
@@ -581,6 +607,7 @@ def install(args,root,manifest):
node=s.get('ROOT')
if not node:raise ValueError('No existing mu300root to reinstall')
capacity=int(a.shell('cat /sys/class/block/'+node+'/size').strip())
if GUI:GUI.validate_plan(node,capacity=capacity*512)
confirm('Reinstall erases only the existing OpenWrt partition, including its settings / 会清空原 OpenWrt 分区及设置。')
a.prepare_payload(root)
return direct_write(a,root,m,manifest,s,capacity)
@@ -599,6 +626,7 @@ def install(args,root,manifest):
size=image_size(args.size or input(f'OpenWrt partition GiB / 分区大小 [4], max {maximum/1024:.2f}: ') or '4',maximum)
offset=free_root_range(space,size*2048)
if offset is not None:
if GUI:GUI.validate_plan('GPT unallocated space',capacity=size*1048576,gap_start=offset)
if args.format_userdata:raise ValueError('Free-space installation preserves userdata; omit --format-userdata')
confirm(f'Use {size/1024:.2f} GiB of unallocated eMMC space; Android userdata is preserved / 使用未分配空间,不缩容、不格式化 Android。Selected raw range will be overwritten / 所选空闲区域原始内容将被覆盖。')
backup=base/(time.strftime('%Y%m%d-%H%M%S')+'-'+s['CID'][-8:]);a.backup(backup,s)
@@ -614,16 +642,18 @@ def install(args,root,manifest):
maximum=(s['FREE']//1024-1024-256)
print(f'Available / 可用: {s["FREE"]/1048576:.2f} GiB; image maximum {maximum/1024:.2f} GiB')
size=image_size(args.size or input('Image size GiB / 镜像大小 [4]: ') or '4',maximum)
if GUI:GUI.validate_plan('userdata-image',capacity=size*1048576)
confirm('Create a userdata image; an existing image will be retained as a backup / 新建镜像,保留已有镜像备份。')
a.prepare_payload(root)
a.put(settings(args,size,'data-image',manifest['kernel']),'desktop-settings.env')
a.run('"$BB" sh "$P/android-image.sh"')
a.run('"$BB" sh "$P/android-image.sh"',**({'effect':'root-image-write'} if GUI else {}))
live=a.live();a.flash(boot(root,m,'data-image',live,a.slot),m.boot_control(live,a.slot))
return Outcome('success','Userdata image and boot verified / userdata 镜像和启动镜像已安装并校验。','Reboot the device manually / 请手动重启设备。')
if s['START']%2048:raise ValueError('userdata starts at an unsupported unaligned sector')
target,need=allocation(s['SIZE'],size)
destructive=is_encrypted or args.format_userdata
if not destructive:
if GUI:GUI.validate_plan('userdata shrink',wipe=destructive,capacity=size*1048576)
if not destructive and not GUI:
destructive=input('Format Android userdata instead of preserving it? / 是否格式化 Android 数据?[no]: ').strip().lower()=='yes'
if not destructive and (target//2 < (s['SIZE']//2-s['FREE']+1048576)):
raise ValueError('Android data + 1 GiB reserve does not fit the selected smaller userdata')
@@ -648,7 +678,7 @@ def install(args,root,manifest):
a.prepare_payload(root)
a.put(settings(args,2048,'part-stage',manifest['kernel']),'desktop-settings.env')
a.run('"$BB" sh "$P/android-image.sh"')
a.run('printf "PART_MIB='+str(size)+'\\nDATA_MIB='+str(target//2048)+'\\nGROW_FS=1\\nFORMAT_DATA=0\\n" > /data/mu300linux/part-install.conf\nsync')
a.run('printf "PART_MIB='+str(size)+'\\nDATA_MIB='+str(target//2048)+'\\nGROW_FS='+str(int(getattr(args,'grow_fs',True)))+'\\nFORMAT_DATA=0\\n" > /data/mu300linux/part-install.conf\nsync')
identity=':'.join(map(str,(s['CID'],s['NODE'],s['START'],s['SIZE'],target)))
a.flash(boot(root,m,'install-part',live,a.slot,identity=identity),m.boot_control(live,a.slot))
print('Offline shrink/install starts after reboot; progress at http://192.168.77.1:8089/progress.txt (U30Air: .78.1). / 重启后开始离线安装。')
@@ -659,10 +689,12 @@ def install(args,root,manifest):
def direct_write(a,root,m,manifest,s,sectors,record=None,r=None):
node=s['ROOT']
a.put(settings(a.args,2048,'part',manifest['kernel']),'desktop-settings.env')
a.run('"$BB" sh "$P/android-image.sh"')
checksum=a.shell('sha256sum '+a.t+'/openwrt.ext4.new').split()[0]
a.run('"$BB" sh "$P/android-write-part.sh" /dev/block/'+node+' '+s['CID']+' '+str(sectors)+' '+checksum)
verified=bool(GUI and GUI.ctx.record['effects'].get('root-part-write',{}).get('state')=='done')
if not verified:
a.put(settings(a.args,2048,'part',manifest['kernel']),'desktop-settings.env')
a.run('"$BB" sh "$P/android-image.sh"')
checksum=a.shell('sha256sum '+a.t+'/openwrt.ext4.new').split()[0]
a.run('"$BB" sh "$P/android-write-part.sh" /dev/block/'+node+' '+s['CID']+' '+str(sectors)+' '+checksum,**({'effect':'root-part-write'} if GUI else {}))
live=a.live();a.flash(boot(root,m,'part',live,a.slot),m.boot_control(live,a.slot))
if record:r['state']='installed';transaction(record,r)
return Outcome('success',f'Independent partition installed and verified: {sectors/2097152:.2f} GiB / 独立分区已安装、扩容并校验。',
@@ -679,7 +711,7 @@ def free_write(a,root,m,manifest,s,space,offset,sectors):
if not re.fullmatch('[a-f0-9]{64}',checksum):raise ValueError('Invalid image checksum')
disk='/dev/block/'+s['NODE'].split('p')[0]
a.run('"$BB" sh "$P/android-write-free.sh" '+env_args([
disk,s['CID'],s['DISK_SIZE'],offset,sectors,checksum,space['front'],space['tail']]))
disk,s['CID'],s['DISK_SIZE'],offset,sectors,checksum,space['front'],space['tail']]),**({'effect':'root-free-write'} if GUI else {}))
# Independent verification after the device-side comparison, before
# writing boot or selecting the alternate slot.
if a.read(f'dd if={disk} bs=512 count={space["front"]} 2>/dev/null')!=first or a.read(
@@ -728,9 +760,11 @@ def ssh_upload(c,path,destination):
channel.settimeout(120)
channel.exec_command('umask 077; cat > '+shlex.quote(destination))
size=path.stat().st_size;sent=0;last=0
started=time.monotonic()
with path.open('rb') as stream:
while data:=stream.read(262144):
channel.sendall(data);sent+=len(data)
if GUI:GUI.transfer(path.name,sent,size,started)
if time.monotonic()-last>=1:
print(f'\r {path.name}: {sent>>20}/{size>>20} MiB',end='',flush=True)
last=time.monotonic()
@@ -749,7 +783,8 @@ def update(args,root):
# key for this connection without loading or saving a persistent IP pin.
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
host=args.host or input('Device IP / 设备 IP [192.168.77.1]: ').strip() or '192.168.77.1'
c.connect(host,username='root',password=os.environ.get('MU300_SSH_PASSWORD') or getpass.getpass('SSH root password: '),timeout=15,look_for_keys=False,allow_agent=False)
c.connect(host,username='root',password=GUI.password if GUI else os.environ.get('MU300_SSH_PASSWORD') or getpass.getpass('SSH root password: '),timeout=15,look_for_keys=False,allow_agent=False)
if GUI:GUI.validate_ssh(c)
try:
info=ssh_exec(c,'''set -e
cat /run/mu300/device
@@ -785,7 +820,9 @@ fi''').strip().splitlines()
with tempfile.TemporaryDirectory() as t:
for name,data in (('boot-desktop.img',newboot),('misc-linux.bin',bc)):
f=Path(t)/name;f.write_bytes(data);send(f,name)
ssh_exec(c,'chmod 700 '+p+'/busybox && sh '+p+'/local-update.sh '+p)
command='chmod 700 '+p+'/busybox && sh '+p+'/local-update.sh '+p
if GUI:GUI.action('update-commit',lambda:ssh_exec(c,command))
else:ssh_exec(c,command)
finally:c.close()
return Outcome('success','Update verified; device is rebooting / 更新校验完成,设备正在重启。',
'Wait for OpenWrt to start / 等待 OpenWrt 启动。')
+7 -3
View File
@@ -7,6 +7,7 @@ import json
import os
from pathlib import Path
import shutil
import runpy
TOP = Path(__file__).resolve().parents[1]
@@ -63,17 +64,18 @@ unset MU300_DEPLOY_ROOT
shutil.copyfile(TOP/'desktop/START-HERE.md',stage/'START-HERE.md')
shutil.copyfile(TOP/'desktop/installer.py',stage/'OpenWrt-Installer.py')
# Python source runs from the archive root, so resolve its support files there.
if exe:
if exe and not Path(exe).is_dir():
fingerprint=json.loads(Path(str(exe)+'.json').read_text())
current={n:sha(TOP/'desktop'/n) for n in ('installer.py','boot_image.py')}
if fingerprint['source'] != current: raise ValueError('desktop EXE is stale; rebuild it')
shutil.copyfile(exe,stage/'OpenWrt-Installer.exe')
(stage/'tools/legacy').mkdir(parents=True,exist_ok=True)
shutil.copyfile(exe,stage/'tools/legacy/installer.exe')
actions={'start-installer':'','install-to-tf-card':'--tf','install-to-internal-storage':'--part',
'install-to-userdata-image':'--data','reinstall-internal-system':'--reinstall-part',
'resume-internal-install':'--resume','switch-to-openwrt':'--boot-openwrt','update-openwrt':'--update'}
launchers=stage/'launchers';launchers.mkdir()
for name,flags in actions.items():
cmd='@echo off\r\ncd /d "%~dp0.."\r\nif exist "OpenWrt-Installer.exe" (\r\n "OpenWrt-Installer.exe" '+flags+' --no-pause %*\r\n) else (\r\n py -3 "OpenWrt-Installer.py" '+flags+' --no-pause %*\r\n)\r\npause\r\n'
cmd='@echo off\r\ncd /d "%~dp0.."\r\nif exist "tools\\backend\\openwrt-backend.exe" (\r\n "tools\\backend\\openwrt-backend.exe" --cli --package-root "%cd%" '+flags+' --no-pause %*\r\n) else (\r\n py -3 "OpenWrt-Installer.py" '+flags+' --no-pause %*\r\n)\r\npause\r\n'
(launchers/(name+'.cmd')).write_bytes(cmd.encode())
(launchers/(name+'.sh')).write_text('#!/bin/sh\ncd "$(dirname "$0")/.." || exit 1\nexec python3 OpenWrt-Installer.py '+flags+' "$@"\n',newline='\n')
(launchers/(name+'.sh')).chmod(0o755)
@@ -82,6 +84,8 @@ unset MU300_DEPLOY_ROOT
(stage/'tools').mkdir(exist_ok=True)
for n in ('adb.exe','AdbWinApi.dll','AdbWinUsbApi.dll'):
shutil.copyfile(Path(adb_dir)/n,stage/'tools'/n)
if os.environ.get('OPENWRT_GUI_OPTIONAL') != '1':
runpy.run_path(str(TOP/'installer/package_gui.py'))['attach'](stage,exe if exe and Path(exe).is_dir() else None)
after={n:sha(stage/layout[n]) for n in before}
if after!=before: raise ValueError('original Magisk payload changed')
relocated={layout[n]:h for n,h in before.items()}
+164
View File
@@ -0,0 +1,164 @@
# WPA3 热点连接失败:分析与公共适配
日期:2026-10-15。范围:E5 公共 OpenWrt 构建及 MU300 仓库的 SC2355 驱动。
## 结论与验证边界
现有配置界面能提供 WPA3-SAE 选项,但这不代表展锐固件热点的 SAE
认证接口已经接通。两边存在相同的用户态/驱动适配缺口;E5 另有 PMF
显式关闭值残留的风险。不能把换成完整版 wpad 当成完整修复。
已补齐下述公共代码、配套 APK 和构建校验。T551M 已热部署,纯 WPA3 与
WPA2/WPA3 混合模式均已完成手机客户端 SAE 握手、PMF 和上网验证。
## 1. 包含 SAE,但界面没有验证固件认证链路
两个构建脚本均安装 `wpad-basic-mbedtls`。OpenWrt 25.12 的 hostapd
Makefile 对 mbedtls 变体设置 `CONFIG_SAE=y`,包说明也包括 WPA3-Personal。
已打包 LuCI 的 `view/network/wireless.js` 根据
`L.hasSystemFeature('hostapd', 'sae')` 等软件功能展示加密选项。
这是软件编译能力判断,不能确认展锐固件所需接口完整可用。
官方源:
<https://github.com/openwrt/openwrt/blob/openwrt-25.12/package/network/services/hostapd/Makefile>
## 2. 固件热点认证与标准 hostapd 之间缺少桥接
MU300 可直接核对的代码在 `upstream/modules/sprd_wlan_combo/`;E5 检查的是
当前构建树 `/home/kano/e5-live-20261014/linux/drivers/unisoc_platform/sprd_wlan_combo/`。
两边的关键行为一致:
- `sc2355/init.c` 根据固件能力设置 `WIPHY_FLAG_HAVE_AP_SME`,认证状态机
由设备/固件参与;同时无条件设置 `NL80211_FEATURE_SAE`。
- `sc2355/vendor.c` 的 `vendor_set_sae_password()` 接受展锐私有命令
`VENDOR_CMD_SET_SAE_PASSWORD`(43,OUI `0x001374`),检查固件的
`SPRD_EXTEND_SOATAP_WPA3`(BIT(6)),再通过 `CMD_SET_SAE_PARAM` 下发。
- `sc2355_start_ap()` 主要向固件发送 beacon,没有把标准
`settings->crypto.sae_pwd` 交接到上面的 SAE 参数命令。
- 没有声明标准 `NL80211_EXT_FEATURE_SAE_OFFLOAD_AP`;也没有实现
`.external_auth` / `cfg80211_external_auth_request()` 这条标准外部认证链路。
对照官方 OpenWrt 25.12 hostapd:标准 AP SAE offload 密码下发依赖
`SAE_OFFLOAD_AP` 能力,使用 `NL80211_ATTR_SAE_PASSWORD`。设备 SME 的
外部认证路径则需要驱动配合处理认证交互和结果。这些路径没有自动调用
展锐私有的命令 43。
核对的官方 hostapd 源码包:
`hostapd-2025.08.26~ca266cc2.tar.zst`,SHA-256:
`59ac677093f524ff98588abd9f33805a336a6e929d6814222f0d784c854f2343`,
与 OpenWrt 分支 Makefile 的 `PKG_MIRROR_HASH` 一致。
因此不能只凭 `iw`/LuCI 出现 SAE,或源码里有 SAE 常量,就判定 WPA3 热点
已经支持。MU300 的旧 FINDINGS §14 还记录过 WPA3 上联关联失败,但那个
记录属于 STA 模式,不能用来替代本次 AP 模式验证。
## 3. E5 的 PMF 关闭值可能随切换保留下来
`openwrt/overlay/etc/uci-defaults/91-e5-wireless` 显式写入
`ieee80211w='0'`,这对默认 WPA2 配置有效。
离线 rootfs 的 `/lib/netifd/hostapd.sh` 在 SAE 模式使用
`set_default ieee80211w 2`,混合模式通常默认 1。`set_default` 不覆盖
已有的 0。如果切换加密方式时没有清除这个旧值,就可能产生关闭 PMF 的
SAE 配置。LuCI 有自己的动态默认值和写入行为,因此不能断言所有界面操作
都会保留 0;需要检查最终 UCI 和生成的 hostapd 配置。
WPA3-only 要求 PMF;混合模式允许传统 WPA2 客户端不启用 PMF,但 SAE
客户端仍需满足相应保护要求。不能用关闭 PMF 来修 WPA3。
官方配置说明:
<https://android.googlesource.com/platform/external/wpa_supplicant_8/+/refs/heads/main/hostapd/hostapd.conf>
## 验收要求
1. 接通标准 hostapd 到展锐固件的 SAE 认证路径。选择固件卸载或外部认证
方案前,确认固件能力、命令顺序、PMK 交接、失败传播和 PMF 密钥处理;
不能仅设置能力位或仅发送密码就宣称完成。
2. 加密方式切换时正确处理 PMF 默认值,兼顾网页、脚本和已有配置升级;
保持 WPA2 用户配置语义,不强行全局开启 PMF。
3. 固件不支持时明确拒绝所选模式,不要静默改成 WPA2,也不要只发布一个
无法关联的热点。
4. 分别验证 WPA2、WPA3-only、WPA2/WPA3 mixed、修改密码和重启后重连。
混合模式手机连上还不够,必须确认客户端实际使用 SAE 而非 WPA2 回退。
5. 实机验证需覆盖 E5/T551M/M8 及 MU300 PCIe 系列的实际固件差异。
密码、PMK 不得写入诊断日志。
## 已实现的修复
### 原厂认证链路的逆向结论
对本机提取的 Android `vendor/bin/hw/hostapd` 进行了 AArch64 反汇编核对。
原厂不是完整四次握手卸载:固件负责 SAE,hostapd 负责 EAPOL 四次握手。
固件在 NEW_STATION 关联信息尾部附加私有 IE:
```text
dd 34 40 45 da 04 <PMK:32> <PMKID:16>
```
这不是需要客户端发送的空中协议。Android 在关联事件中提取这些数据,
将该 station 标记为 SAE,随后正常执行四次握手。本修复沿用这条链路,
不会伪造已授权状态,也不声明完整四次握手卸载。
### 内核与 hostapd
- 仅在固件同时支持 SoftAP WPA3、AP SME 和 802.11w 时公布 AP SAE 卸载能力。
- 同时公布至少三种 AKM 的下发容量。混合模式实际携带 PSK、PSK-SHA256、
SAE,旧的默认容量为二,hostapd 因此省略整个 AKM 属性;驱动看不到 SAE,
就不会给固件设置密码。实机复测已经确认并修复这个独立问题。
- START_AP 之前,把标准 SAE 密码转换为原厂命令 85:请求类型 2,
ENTRY、PWD、END 三组 16 位小端 TLV;密码不附加 NUL。
- 保留命令串行锁,传播锁获取失败、命令被关闭路径拦截和固件拒绝的错误。
- 固件 AP SME 接管 AUTH 帧,避免 hostapd 注册 AUTH 后把认证帧从固件引走。
- hostapd 仅对明确启用 `unisoc_sae=1` 的此类接口导入固件 PMK/PMKID。
严格检查 IE 长度、重复项、RSN 的 SAE 和 PMF;缺失密钥时只允许真实 PMKSA
缓存重连。WPA2 不使用该密钥,SAE 切回 WPA2 时清理旧 station 状态。
- 调试输出隐藏 SAE 密码命令及带 PMK 的关联事件,不记录密码和密钥。
### 配置与构建
- 从 WPA2 切换到 SAE 后,生成配置会纠正遗留 PMF=0:纯 SAE 使用必需 PMF,
混合模式至少启用可选 PMF。不会全局改写 WPA2 的 PMF 设置。
- 仅 SC2355 生成私有桥接配置。默认使用已逆向确认的传统 SAE
hunting-and-pecking、group 19;不支持的 H2E/FT-SAE/额外组明确拒绝,
不静默退回 WPA2。不宣称支持 WPA3 R3 的 H2E 或 6 GHz。
- 同时接入 OpenWrt 25.12 默认 ucode 生成器和可选旧 shell 生成器。
只修 shell 文件并不会影响默认 ucode 路径。
- 此类固件接口关闭 RSN Override 广告。实机发现固件未把 RSN Selection
扩展完整带入关联事件,混合模式会在四次握手的消息 2/4 上校验失败。
保留正常校验,禁用不兼容的扩展,不绕过 EAPOL 检查。
- 只有固件 SAE BSS 配置发生变化时才完整重启 AP,再下发密码;配置未变的
普通 reload 保留连接。Linux SET_BEACON 没有 crypto 更新回调,原先的
原地 BSS 更新不能保证新密码进入固件。
- 固定 OpenWrt 25.12.5 与对应 hostapd 源码哈希,重建并配套安装
`wpad-basic-mbedtls`、`hostapd-common`、`wifi-scripts` 三个 APK。
- 显式保留 AC/AX/BE 编译开关。外置展锐模块不经过 OpenWrt 的 kmod 选择,
不能依赖它自动打开这些开关,否则旧热点的 VHT 配置都会被新 daemon 拒绝。
- E5 三机型内核准备流程、原生构建及容器构建均接入同一适配;MU300 的
公共 SC2355 模块和 rootfs 构建同步。增量重打包检查源码指纹和三个 APK
哈希,避免旧 rootfs 丢掉用户态修复。
## 已执行验证
- 两仓库的 C 测试使用 ASan/UBSan 执行实际共用头文件,检查 1~63 字节
密码编码、能力/错误分支、PMK/PMKID 交接、截断/重复 IE、PMF、缓存重连、
分配失败和 SAE/WPA2 状态切换;配置生成 shell 测试也通过。
- E5 内核相关对象、MU300 的 6.18.54 与 7.2.8 相关对象编译通过。
- T551M 使用实机相同 BTF 和版本、相同 Clang 18 工具链编译完整模块,
实机加载成功并出现 `SAE_OFFLOAD_AP` 能力。
- 配套 APK 交叉编译、离线清单校验、ARM64 容器安装和程序加载通过。
- 实际 ucode 策略测试通过,包括非展锐接口隔离、PMF、显式 H2E 配置保留、
以及禁用不兼容 RSN Override。
- T551M 纯 WPA3 与混合模式都观察到 `auth_alg=sae`、四次握手完成、
`authorized=true`、`mfp=true`;用户分别确认可以正常连接和上网。
- 实机临时更换和恢复密码时,分别确认固件收到新的 SAE 密码命令,
原密码已恢复;不在日志中记录密码内容。
- 重启验证发现 Wi-Fi 驱动在 initramfs 中提前加载,单独更新根分区的 `.ko`
只在手动重载后生效。T551M 已同步更新现有 boot_b 内的那一份模块,
校验只改变该文件,内核、启动参数、其余 initramfs 文件与持久日志区保留。
再次重启后 `SAE_OFFLOAD_AP` 仍存在,热点自动启动。
- 本次恢复了 T551M 原来的 `psk2+ccmp` 设置,未改变原密码;后续可自行
在网页选择 WPA3 或混合模式。修复及配套软件包保留。
不包含 E5、M8 或 MU300 系列手机客户端的实机关联验收。不同固件仍需分别验证。
+6
View File
@@ -0,0 +1,6 @@
ui/node_modules/
ui/dist/
ui/*.tsbuildinfo
ui/src-tauri/target/
artifacts/
__pycache__/
+149
View File
@@ -0,0 +1,149 @@
# OpenWrt Installer
## 中文
完整解压 ZIP 后,双击根目录 **OpenWrt-Installer.exe**。请保留旁边的 `tools/`、`files/` 或 `payload/`、`desktop/`、`scripts/` 等目录。Windows 用户无需安装 Python、Node 或 Rust。程序使用系统 Microsoft Edge WebView2 Evergreen Runtime;缺失时会显示原生提示和安装地址:<https://developer.microsoft.com/microsoft-edge/webview2/>。不包含独立浏览器,不安装 Docker。
`OpenWrt-Installer.py` 是兼容的命令行入口,需要 Python 及相应模块。Windows 的 `launchers/*.cmd` 优先使用随包解释器运行 CLI,普通用户应从根目录 EXE 开始。Magisk 用户仍可直接刷入同一个 ZIP;根目录 `module.prop`、`customize.sh` 和 Magisk 必需文件保留原用途。桌面依赖不会进入设备系统镜像。整个包只有一份系统载荷。
### 选择用途
- **安装 OpenWrt**:TF 卡或独立内置分区。先校验包,再明确选择 USB 设备并检查。即使连接多台设备,后续 ADB 操作也只发送到所选序列号。最终确认前会再次检查实际机型、槽位、闪存身份和计划。
- **更新 OpenWrt**:从运行中的 OpenWrt 通过 SSH 上传,输入设备管理地址及 root 密码。密码仅在本次进程内存中使用,不写入事务或日志。保留设置、已有容量及本机固件;设备端升级互斥和校验继续有效,不要求 SFTP。请先手动连接设备网络。
- **继续未完成的安装**:选择本机事务,使用原包或兼容修复版。按真实机型、系统/启动载荷和文件系统工具哈希验证,不按目录名判断;可以移动或重命名包。载荷不一致会明确列出差异。
- **临时启动已安装的 OpenWrt**:检查启动签名及启动链后,只修改 misc 试启动信息。与“设为默认启动”不同,不修改默认值,不为探测安装状态挂载或写入 OpenWrt 根分区。现有设备端默认启动管理入口继续可用。
- **高级选项**:重装已有内置分区会替换其中的 OpenWrt 与设置,保留 Android;userdata 镜像属于**实验性功能,可能损坏 Android F2FS 文件系统**。镜像大小受真实可用空间、Android 预留及上传/生成临时空间限制。
### TF 卡
按仓库原有规则选择第一分区;只有确实没有分区时才选择整卡。不会重划 TF 卡,也没有 32 GiB 上限。请核对计划中的准确块设备与容量。安装前校验载荷、提取本机固件、释放 Android 对目标卡的挂载;释放失败就停止。所选目标会被格式化并使用其容量,其他分区不参与。原 Magisk TF 部署入口保留。
### 独立内置分区
优先使用已验证 GPT 未分配区域,足够时不缩容或清空 userdata。没有合适区域时使用既有离线缩容逻辑。计划显示 Android 保留空间、OpenWrt 分配大小及数据影响。
“使用全部已分配的 OpenWrt 分区容量”默认开启,意思是扩满选定大小的 OpenWrt 分区,**不是占用设备所有剩余空间**。设备端写入后检查文件系统块数,进入 OpenWrt 后再次读取 ext4 超级块验证实际容量。验证没通过不会显示安装成功。
首次启动会进行离线分区准备,可能需要数分钟,完成后设备会自动重启一次。数据较多或存储较慢时可能更久,请一直供电。检查、缩容、格式化、扩容显示阶段与耗时,不显示虚构百分比。
### 加密 userdata:重置后自动续装
检测到 FBE/FDE 或映射加密 data,且必须缩容时,计划会明确说明 Android 用户数据全部清空。仅在最终确认后继续。安装器将事务与必要备份先写入电脑,再准备 initramfs 交接。第一阶段依靠启动镜像中的请求及准备标记,系统载荷留在电脑,不依赖即将被清空的 `/data` 文件。
1. 保持设备供电,等待离线分区准备和原厂 recovery 清空数据。
2. 设备回到 Android 后完成初始设置。
3. 开启开发者选项、USB 调试,在设备上允许这台电脑调试。
4. 若 root 不存在,安装或恢复 Magisk;若出现 root 请求,请允许。已经可用的 root 会被直接接受,不要求重复安装。
5. 安装器验证同一设备、实际 `su` 权限、原槽位、分区几何与准备标记,然后继续传输安装。
这些等待**没有总超时**。预期重启或 USB 消失属于等待状态,不是 EOF 失败。无 ADB 时电脑无法区分“Android 仍在开机”和“尚未开启调试”;界面同时给出初始化、开启调试与允许授权的具体步骤。未加密 userdata 保留离线保数据缩容,不默认清空。
### 暂停、关闭与失败恢复
事务默认位于 `%LOCALAPPDATA%\OpenWrt-Installer\transactions\<transaction-id>\`。通过“打开事务目录”查看,通过“导出事务与备份”生成 ZIP。备份含设备身份和可能含无线配置的旧后端记录,请妥善保管,不要公开上传。默认日志不包含原终端输出、密码、短信正文或完整设备标识。
“在安全边界暂停”会等待正在进行的存储操作结束,不会直接杀进程。任务执行中关闭窗口会被阻止并提示先暂停。暂停后可以关闭、重启电脑或移动包;重新打开 EXE,选择“继续未完成的安装”。若已提交离线准备,暂停不会撤销设备已收到的启动请求,仍须保持设备供电。完成页保持显示,不会自动关闭。
意外断线时保留完整事务和备份,从原记录复核并继续;不要重新创建一次首次分区任务。已经确认完成的操作有独立检查点,不重复执行。若在写分区表或启动信息中断,且无法凭回读证明完成,会停止并要求用备份恢复,而不会猜测并盲写。设备端旧标记本身不能替代缺失的电脑身份、布局、哈希及备份证据。
从另一台电脑恢复:先解压导出的事务 ZIP,使用“导入恢复目录”选择含 `transaction.json` 的完整目录。仅有孤立 JSON、缺少备份或标记不匹配时不能保证自动恢复。修复版包必须保留相同的机型、布局、关键系统/启动载荷与工具;仅改 GUI、提示、上传逻辑允许续装。损坏或不同版本系统载荷需另行评估,不会自动接受。
安装完成后手动连接设备 USB 网络或热点。默认管理地址:E5/M8/T551M 为 `http://192.168.9.1`;MU300/F50/V50 为 `http://192.168.77.1`;U30Air 为 `http://192.168.78.1`。GUI 会验证同一闪存 CID 后再报告结果。修改过设备地址或 SSH 密码时,请在对应维护页面提供实际值。安装器不启停电脑网卡、不改路由、不自动连接热点。请在首启后修改管理员和无线密码。
窗口顶部、步骤导航和底部操作按钮保持固定;安装内容、续装列表和展开的日志各自滚动。侧栏底部可打开事务目录。操作结果、错误与阶段变化统一通过右上角通知提示;错误通知可以手动关闭,详细信息仍可在日志或对应事务页面查阅。通知不会覆盖底部最终确认按钮。数据影响、等待操作指引和完成结果会持续显示在页面中。界面动效会遵循 Windows 的“动画效果/减少动态效果”设置。
### 连接与常见问题
#### 第一次使用,从哪里开始?
首次打开且没有安装记录时会显示三个步骤的新手引导,可以跳过;首页可随时重看。窗口右上角“帮助与使用指南”或 F1 打开可搜索的离线指南。安装中查看帮助不会暂停、重新开始或取消任务;关闭帮助会回到原来的安装页面。界面语言决定指南语言。所有引导都只作说明,不会连接、格式化或写入设备。
#### 没有发现设备,或者同时连接了多台设备?
先完成安装包校验,再刷新设备。确认 USB 线支持数据传输、设备供电正常;必要时更换线缆或 USB 口,并在 Windows 设备管理器检查设备及其 USB 驱动。Android 中开启开发者选项和 USB 调试。多台设备会列在下拉列表中,请核对型号和序列号末四位,明确选择目标后检查;后续操作绑定所选设备,不会任选另一台。
#### 显示“等待调试授权”或“离线”?
解锁 Android,查看是否出现“允许 USB 调试”提示并允许此电脑。没有提示时确认 USB 调试已开启,再重新插拔数据线并刷新。离线时先确认设备是否正在预期重启;等待它开机后重新连接。已有安装进行中时保留原记录,不要另开一个分区任务。
#### 已经安装 Magisk,为什么还在等待 root?
安装了 Magisk 应用不等于 `su` 已可用。打开 Magisk 确认 root 环境,留意并允许 root 授权请求;若 root 环境在重置后丢失,再恢复 Magisk。工作正常的 root 会直接使用,不会要求重复安装。完成初始化和授权没有固定的几分钟时限。
#### 续装一定要手动创建“事务”吗?
不需要。安装记录由程序自动保存在电脑,里面保存设备身份、分区计划、载荷哈希、备份和已完成阶段。关掉程序、重启电脑或移动安装包后,从“继续未完成的安装”读取原记录即可。换电脑前导出完整事务与备份;在另一台电脑解压并导入完整目录。**电脑记录和导出备份都丢失时,当前版本不能仅凭设备自动重建续装记录。** 不要用新建首次分区任务代替丢失的记录。已经装好后进行更新或临时启动,不需要上一次安装的记录。
#### 什么时候会清空数据?等待时能关闭吗?
以最终安装计划为准。TF 安装格式化选定目标;重装替换已有 OpenWrt;必须缩容的加密 userdata 会明确提示 Android 重置。未加密 userdata 保留原有保数据缩容路径,足够的未分配空间优先使用。先读清楚计划,再作一次最终确认。写入中保持供电;需要退出时点击“在安全边界暂停”,等任务实际暂停后关闭。暂停不能撤销已提交给设备的离线启动请求。
## English
Extract the complete ZIP and run **OpenWrt-Installer.exe** at its root. Keep all adjacent folders. Windows users need no separate Python, Node or Rust. The application uses the system **Microsoft Edge WebView2 Evergreen Runtime**. If missing, a native dialog provides <https://developer.microsoft.com/microsoft-edge/webview2/>. No standalone browser or Docker is included.
**OpenWrt-Installer.py** remains the Python CLI. Windows command launchers prefer the bundled interpreter. Magisk can still install the same ZIP through its original root entry files. Desktop code and dependencies stay outside device payloads, and there is only one system payload in the package.
### Choose your purpose
- **Install OpenWrt**: use a TF card or an independent internal partition. Verify the package, explicitly select a USB device, inspect it, then review the final plan. All later ADB operations are serial bound, including when multiple devices are connected.
- **Update OpenWrt**: provide the management host and SSH root password. Passwords stay in process memory. Existing update locks, checksum checks, SSH compatibility, settings, capacity and local firmware are retained. SFTP is not required. Connect to the device network manually.
- **Continue an unfinished installation**: select a saved transaction. Moving/renaming the package is supported. A repair release is accepted when the model, layout, system/boot payloads and filesystem tools are compatible; incompatibilities name the changed fields or files.
- **Boot installed OpenWrt once**: validate the boot signature/chain and change only the trial information in misc. Do not mount or write the OpenWrt root or change its default boot setting. Existing on-device default-boot controls remain available.
- **Advanced options**: reinstall replaces an existing internal OpenWrt partition and its settings while keeping Android. **Userdata image installation is experimental and may damage Android F2FS**. Image size is constrained by actual free space, Android reserve, uploads and temporary image preparation.
### Storage and capacity
TF installation follows the existing first-partition preference, using the raw card only when it has no partitions. It does not repartition cards or impose a 32 GiB ceiling. Check the exact target and capacity. The payload and local firmware are prepared before releasing Android mounts and formatting. A release failure stops installation. Magisk TF installation remains supported.
Internal installation first checks validated GPT gaps. A sufficient gap avoids shrinking/resetting userdata. Otherwise the existing offline resize is used. The plan displays retained Android space, allocated OpenWrt space and data impact. **Use all allocated OpenWrt partition capacity** is enabled by default: it fills the chosen allocation, not all remaining device storage. Device-side block-count checks and final ext4 superblock verification prevent a 10 GiB partition with an unexpanded 2 GiB filesystem from being reported as success.
The first boot performs offline partition preparation. This may take several minutes; the device reboots automatically once it finishes. Keep power connected. Checks, formatting, shrink and growth use phase/elapsed indicators without invented percentages. Transfer progress uses actual acknowledged bytes and elapsed speed.
### Encrypted userdata and reset
When encrypted userdata must be resized, the final plan explicitly warns that all Android apps, accounts, photos and internal storage are erased. Back up personal data before confirming. The installer saves its computer transaction and essential backups before preparing initramfs. Stage-one handoff lives in the boot request and verified preparation marker; the system payload remains on the computer and is not lost with `/data`.
Wait for offline preparation and stock recovery to finish. Complete Android setup, enable developer options and USB debugging, then authorize this computer. Restore/install Magisk only when root is unavailable, and allow the root request. Working root is accepted immediately. The installer rechecks the same hardware identity, original slot, partition geometry and preparation marker before continuing.
There is **no overall deadline** for user setup or authorization. Expected reboots and missing USB are waiting states. Without ADB the computer cannot distinguish Android still booting from USB debugging not yet enabled; the UI provides both instructions. Unencrypted userdata retains its preserving offline-shrink path.
### Recovery and results
Transactions live in `%LOCALAPPDATA%\OpenWrt-Installer\transactions\<transaction-id>\`. Open this directory or export the full transaction/backup ZIP from the application. Backups include private hardware identity and may contain wireless settings in legacy records; do not publish them. Default logs omit legacy terminal output, passwords, SMS bodies and full hardware identifiers.
Pause takes effect at a safe boundary. A partition or boot write is not killed. Closing an active window is blocked until a safe pause. Pausing cannot undo an already submitted offline boot request: keep the device powered. After closing the application, restarting the computer or moving the package, reopen it and choose **Continue an unfinished installation**. The completed page stays open.
After an unexpected disconnect, use the saved record instead of creating another first-install transaction. Completed effects have checkpoints. An uncertain GPT/boot write that cannot be proved complete stops for backup-based recovery; it is not guessed or blindly replayed. A device marker alone cannot replace missing host identity, geometry, payload hashes and backup evidence.
To move recovery to another computer, extract the exported transaction ZIP and import the complete folder containing `transaction.json`. An isolated JSON or insufficient backups may not be recoverable automatically. Compatible repair releases may change UI/prompts/upload logic while keeping model, root layout, critical system/boot payloads and tools unchanged.
Connect to USB networking or the device hotspot manually. Default management addresses: E5/M8/T551M `http://192.168.9.1`; MU300/F50/V50 `http://192.168.77.1`; U30Air `http://192.168.78.1`. Final verification checks the eMMC CID before reporting success. Supply actual management details when previously changed. The installer does not modify adapters/routes or join hotspots. Change administrator and wireless passwords after first boot.
The header, step navigation and bottom actions stay fixed. Installation content, recovery records and expanded logs scroll independently. The transaction-folder shortcut stays at the bottom of the sidebar. Results, errors and phase changes share the notification area at the upper right, away from the final confirmation buttons. Dismiss error notifications manually; consult the log or transaction page for details. Data-impact warnings, waiting instructions and completed results remain on the page. Interface motion follows the Windows animation/reduced-motion preference.
### Connection and troubleshooting
#### Where should a beginner start?
The three-step getting-started guide appears on first launch when no installation records exist. You can skip it and replay it from the home page. Open the searchable offline manual with Help and user guide at the upper right, or F1. Reading help during installation does not pause, restart or cancel the task. Closing help returns to the original installation page. The interface language selects the manual language. The guide itself does not connect to, format or write a device.
#### No devices, or several devices connected?
Verify the package before refreshing devices. Use a data-capable USB cable, keep power connected and try another cable or USB port if necessary. Check the device and USB driver in Windows Device Manager. Enable Android developer options and USB debugging. With multiple devices, check the model and last four serial characters in the list, explicitly select your target and inspect it. Later operations remain bound to that device.
#### Awaiting debugging authorization, or offline?
Unlock Android and allow this computer in the USB debugging prompt. If no prompt appears, verify USB debugging, reconnect the cable and refresh. An offline device may be in an expected reboot; let it finish starting and reconnect. Keep an existing installation record instead of creating another partitioning task.
#### Magisk is installed, but root is still pending?
Having the Magisk app installed does not prove that `su` works. Check the root environment in Magisk and grant any root request. Restore Magisk if the root environment was lost after a reset. Already-working root is accepted immediately without reinstalling Magisk. Setup and authorization have no fixed deadline of a few minutes.
#### Must I create a transaction manually to resume?
No. The installer automatically saves a record on the computer, including device identity, partition plan, payload hashes, backups and completed phases. Reopen the application and choose Continue an unfinished installation after closing, restarting the computer or moving the package. Export the full transaction and backups before moving to another computer, then extract and import the full directory there. **If both computer records and exported backups are lost, this version cannot reconstruct a record from the device alone.** Do not substitute a fresh partitioning task for missing records. Updating or temporarily booting an already-installed system does not need its previous installation record.
#### When is data erased, and can I close while waiting?
Read the final plan. TF installation formats the selected target; reinstallation replaces existing OpenWrt; encrypted userdata that must shrink requires an explicitly warned Android reset. Unencrypted userdata keeps its preserving shrink path, and sufficient unallocated space is preferred first. Confirm once after reviewing the plan. Keep power connected during writes. To exit, request Pause at a safe boundary and close only after it actually pauses. Pausing cannot undo an offline boot request already submitted to the device.
+17
View File
@@ -0,0 +1,17 @@
# Installer protocol and recovery contract
The canonical implementation is `e5-linux/installer`. `sync.py <mu300-repository>` generates the other repository's mirror and `SHARED-SOURCE.json`. Edit the canonical source, synchronize, and run `--check`. Do not independently maintain two frontends/state machines. Both builds use the same Tauri executable and backend; repository-specific behavior is in `backend/adapter.py` and the existing Python/device scripts.
Protocol 1: one JSON object per line on stdin/stdout. A request is `{"protocol":1,"id":1,"command":"hello","params":{}}`. Responses contain the same `id`, `type:"response"` and `data:{ok,result}` or `{ok:false,error}`. Events use `type:"transaction"`, `"transfer"`, `"log"`. No terminal-text matching. Legacy stdout/stderr is suppressed; named observer callbacks produce events.
Commands are allowlisted in both Rust and Python: hello, snapshot, list, package, devices, probe, probe_update, plan, start, resume, retry, cancel, can_close, export, import. There is no shell/exec command. A frontend-selected serial is checked against an actual device. All ADB operations use that serial; eMMC CID and profile are rechecked after reset. SSH maintenance binds the key fingerprint between planning and execution; final verification binds the hardware CID. A plan cannot become executable without `confirmed:true` on its persisted transaction ID.
Transactions include format/version, device identity/profile/original slot/storage geometry, selected method/allocation, original partition layout, content-based payload identity, backups, legacy transaction path, completed effects, started/done mutation ledger, current stage/status and final measured result. Writes use flush/fsync plus atomic replacement. Per-CID and per-serial OS locks are shared between repositories. Kernel-released locks survive abnormal process termination correctly. Device scripts retain their own upgrade/partition locks.
Statuses: ready, running, waiting_user, waiting_device, failed, cancelled (a resumable pause), completed. Stages are independent of frontend navigation. Waiting for Android initialization, ADB authorization or root has no transaction deadline. Expected reboot is checkpointed before the reboot command. Every write has a stored intent and a completion checkpoint; completed effects are skipped. Uncertain nonrepeatable writes stop for readback/recovery. Existing backend transaction/geometry/token checks remain authoritative during stage-two resume.
Safety boundaries are before effects and between verified transfer chunks. Cancellation is requested, not process termination. Close is blocked for active operations; the user first requests a pause. If the host disappears during an unsafe operation, the ledger retains the incomplete intent. Reconnecting is not permission to repeat GPT shrink/format. Backups must be exported before reinstalling Windows or deleting app data. Device-only recovery with insufficient identity/layout/backup evidence is refused.
Transfer events contain `name`, actual acknowledged `bytes`, `total`, and `bytes_per_second`. Check/format/shrink/grow only emit phase and activity. Final verification reads an ext4 superblock over SSH base64, checks the expected allocated byte count and running OpenWrt, and reports filesystem bytes separately from partition size. No `od` or SFTP is required by that verification.
Content compatibility binds adapter, profile, root layout, kernel family and critical boot/rootfs/filesystem-tool hashes. Package paths and GUI/host-script versions are not compatibility keys. Package checksums are verified again on resume. This is integrity against corruption and accidental mismatch, not a signed release authenticity mechanism.
+50
View File
@@ -0,0 +1,50 @@
# Building the desktop installer
Build dependencies (users do not need these): Windows x64, MSVC C++ Build Tools and Windows SDK, Rust 1.90.0, Node 22+, Python 3.12, PyInstaller, Paramiko, lz4. A system WebView2 Runtime is required to run the GUI. See the [Tauri Windows prerequisites](https://v2.tauri.app/start/prerequisites/) and [portable WebView2 configuration](https://v2.tauri.app/reference/config/).
```powershell
python -m pip install pyinstaller paramiko lz4
python -m unittest discover -s installer/tests -v
python installer/build.py
```
`ui/rust-toolchain.toml`, Cargo.lock and package-lock.json pin the build graph. `build.py` runs a Tauri release build with size optimization/LTO/strip and builds a console-protocol Python sidecar. The Tauri host spawns it with CREATE_NO_WINDOW. `installer/artifacts/windows` contains `OpenWrt-Installer.exe`, `tools/backend/`, and `build.json` with source/binary hashes. No browser runtime, Node, Rust, Python installation, cache, large fonts or development dependencies are shipped. The bundled interpreter is private to the sidecar.
The artifact also includes ADB and its two Windows USB DLLs under `tools/`, plus `ADB-NOTICE.txt`. `platform-tools.json` pins Google's 37.0.1 archive URL and SHA256; only these necessary files are extracted. `--adb-dir` accepts a pre-fetched official platform-tools folder for offline builds. Normal packaging therefore does not rely on ADB installed on the end user's PATH or an optional environment variable.
The host uses fixed Rust commands for dialogs, protocol requests and opening the application-data directory. CSP restricts remote content and scripts. Window-close handling prevents killing an active backend. A missing WebView2 Runtime produces native installation instructions. Portable distribution requires the complete adjacent `tools/backend` directory; the root EXE by itself is not the complete package.
`OPENWRT_GUI_ARTIFACT` can point to an extracted Windows build artifact while packaging on Linux. Existing e5 `install-entrypoints.py` and MU300 `desktop/package.py` call `package_gui.attach` before generating final manifests. GUI sources and binaries are fingerprinted; missing/stale artifacts fail normal packaging. `OPENWRT_GUI_OPTIONAL=1` permits source-only/test fixtures and must not be used for a GUI release. Old optional console EXEs are stored under `tools/legacy`; the root EXE is always Tauri.
MU300's `--exe` packaging option accepts the GUI artifact **directory**. Legacy console EXE input remains accepted under `tools/legacy`. `tools/build-openwrt-tf-magisk.sh` still calls the same package assembler; set `OPENWRT_GUI_ARTIFACT` (or its existing MU300_DESKTOP_EXE to the directory). e5's profile builder and make-flash-bundle paths use the same attachment. Root Magisk files and a single rootfs remain intact; desktop code is not added to any device initramfs or rootfs.
To refresh the generated MU300 mirror:
```powershell
python installer/sync.py D:\Git\mu300-linux-clean-tf-7.2
python installer/sync.py D:\Git\mu300-linux-clean-tf-7.2 --check
```
`package_gui.size_report(package, archive)` reports GUI, backend/tools, device firmware payload and final compressed archive bytes separately. `release.py` augments an existing validated package into a new output directory, refreshes only host installer sources/manifests, preserves the firmware payload, then tests ZIP CRCs. Never overwrite an existing published package.
Validation uses fake transports and disposable files. Run POSIX device-script tests in Linux/WSL; Windows path syntax is not valid in those shell test fixtures. Actual hardware erase, resize, boot synchronization and Magisk installation require a separate authorized hardware run. See the verification report for what was actually executed.
## Desktop layout, feedback and motion
The window has a fixed viewport: header, sidebar, primary actions and footer stay visible. Purpose lists, recovery records, installation content and expanded logs have independent scroll areas. The package extraction reminder and transaction-folder shortcut stay at the bottom of the sidebar. Recovery controls remain compact at the minimum 800×650 window size, including when the log is open.
[Sonner](https://sonner.emilkowal.ski/) is the single notification surface for request results, native/clipboard errors and transaction changes. Transaction snapshots are deduplicated by identity, stage, status and error; repeated polling does not reset elapsed time or flood notifications. Destructive warnings, actionable waiting guidance, failures and final results also remain in context. Notifications appear above the content, away from the bottom confirmation controls. Loading notifications transition to their result; cancelling a save dialog does not report a successful export.
[Motion for React](https://motion.dev/docs/react) supplies short page entrances/exits, purpose-row interactions, phase/result entrances and log expansion. `LazyMotion` loads the DOM animation feature set without layout/drag features. `MotionConfig`, `useReducedMotion` and CSS respect the operating system's reduced-motion preference; waiting for the user uses a static device icon rather than an endless execution spinner. No transfer percentages are synthesized.
To exercise the production UI without ADB/SSH, install Playwright on the development machine, build the frontend, serve `installer/ui/dist` on `127.0.0.1:1420`, and run `python -X utf8 installer/tests/ui_smoke.py`. This test injects its transport fixture only into the browser test context. It checks bounded scrolling, large record/log lists, notifications and deduplication, device binding, confirmation controls, themes/languages and reduced motion, and refreshes the screenshots.
## Onboarding and offline help
The three-step getting-started guide appears after a successful startup when no saved transactions exist and `onboarding-v1` has not been acknowledged in this application's local storage. Completing, skipping or closing it remembers that choice. Home can replay it at any time. Existing records suppress automatic onboarding so recovery remains the priority. The guide performs no backend operations.
The header help button and F1 open an independent help dialog without navigating away from the current plan, password fields or running task. Waiting phases link to the relevant setup/authorization topic. Closing with Escape or the close button restores focus to the originating control. Radix Dialog provides modal keyboard focus management; topic lists and article bodies scroll independently within the minimum 800×650 window. Help and onboarding honor the existing theme/language/reduced-motion preferences.
`ui/src/help-data.ts` imports the bilingual `GUIDE.md` as text at build time and selects localized topics, so root `START-HERE.md`, the packaged guide and in-app detailed help share one source. Search matches topic titles and full content. Markdown is rendered with `react-markdown`, without raw HTML or remote content; displayed URLs are selectable text. The help module/Markdown renderer loads on demand. `GUIDE.md` is part of the source fingerprint: a guide change requires rebuilding the GUI artifact.
Run `python -X utf8 installer/tests/help_smoke.py` against the same production-bundle test server to cover first launch, replay, skip/persistence, saved-record suppression, search/no-match state, focus trapping/restoration, F1/Escape, relevant help during installation, bilingual bounded dialogs and the absence of help-driven backend commands. This is browser automation with a test-only bridge, not device installation validation.
+90
View File
@@ -0,0 +1,90 @@
{
"source": "e5-linux/installer",
"policy": "Generated mirror. Edit upstream then run sync.py; do not fork UI/protocol.",
"sha256": {
".gitignore": "a5773f83330fc9adddfd159fe0391bccffbf7663dccb2b873f6b2d1b2d2eca11",
"backend_entry.py": "b7fea0acd7f3ddbd268c465fb089a258203c1d65f8e4230e35a98d78d7382e90",
"build.py": "e3adff7e7c6a20e19ed541a4fc22589ba65306cd70dae2b4afde582e8c55a976",
"GUIDE.md": "f812f7ee5c2873d7eeade1b5f0a234bf6fefa3c218b88634a4e4b10374cf7671",
"package_gui.py": "76435dcfd5c6386f39735b74e8c1dd541dbfdf4da391d02636c4482cc1b6d715",
"platform-tools.json": "d8fcf938e150bc314b5e6b2660c540976bb12ea6108fa75a8fb183115ebbd01e",
"PROTOCOL.md": "fa1353791fd861a0b7e649e3be3224a91384489b73817ced88a17d6d52bd3dd4",
"README.md": "7d906eb6693180b1c05cdf0c928437523240414b55e48a246cbb2434be7505bf",
"release.py": "c1432d3b4e48e094d79753d6be3f432d9e05744abfa816bd4d6e1a04d06b6432",
"requirements-build.txt": "762ee573a22c790eb3c5ccba4616632373d947dc88eb91fc85f3c678ac7b2259",
"sync.py": "8a6160a68cadbb3295303505c94d6cb5a8229c9ccb2d652408660b1711fccfdf",
"VERIFICATION.md": "56048f975f614824f627442f8376234e98c4359d09bf6e7292f83c2c066e288e",
"backend/adapter.py": "ea817c559d9abc8748b8b528622620a2abcd215eb6937ad2c80717353f5be52d",
"backend/gpt.py": "4eca5ccf458ef86b9dfcea6388da61defe61af6389565cadf2fda6616e28b791",
"backend/package.py": "5c55e91f2c348ac957d7803810e6396edf3aae573da401ecf46e773ac75e70ee",
"backend/service.py": "0bd4137a37cb6346bc5c6ad6f9f580e6fc9e3311e32510022340c4505e95a89c",
"backend/state.py": "af15010d0b1cb7b827f2cf69cb4b18139d5f33d408aae47da65b2c7cacc5952a",
"backend/transport.py": "91017d0116a0d7b2c6f763ac6c8b092dedca987dce0b686e9b6f57681af25d1b",
"backend/__init__.py": "4227d63763e764fd2de7fc2bc13e474ae5de33176fb57aa0fd51cbb4ad80b88c",
"screenshots/complete-dark-en.png": "f8709858ee45e4a562195684cdb17087ce7d6c60dcd7e3e0883f83b5baac4e07",
"screenshots/help-recovery-light-zh.png": "7443b3880bcd616e861a436e50778414e246ae299c6ddf3eec65f2e44671c874",
"screenshots/help-small-dark-en.png": "001502ca276fb48b5370a95c4211828809ffd53c6a110bc58eb71f30a63c563d",
"screenshots/home-light-zh.png": "fe8e87a1c37d05dcc2eee9c688f10d0fd170b6ff0495a71270881378eb366a7a",
"screenshots/install-small-light-zh.png": "46b3e5a494c32da5959b4cb5a80694a5a7eefd86f0c6942e9978c5723ea1dd5d",
"screenshots/native-home.png": "c5503e2ad3b01508b86cf5802501ce12c8c7b8856d452487941b5fcb44b18c80",
"screenshots/native-mu300-home.png": "48ca20b2732f9a3d9522512ddd6121fc5eac4943d2cd928d7a21f0ba7c82a3a3",
"screenshots/onboarding-light-zh.png": "37d8e26be61aff5b7c1851bce83af415666d8b6916775a58ac8e2f0446fbb4be",
"screenshots/onboarding-small-dark-en.png": "f4f82bb46596db713021ec3d1398f83b5f96e0413ae7711a7b384c5c11b140fa",
"screenshots/plan-light-zh.png": "9ff13ad155cb5c2fc58f34dae0345971787216f3a70ccadcd28d4adf1da37b3c",
"screenshots/plan-small-dark-en.png": "13910ce085be317b4f72783a2275728a513257e31b693713510a2bcaa4f1843a",
"screenshots/resume-small-light-zh.png": "b6ba295df3405b99434b153874be27f291038d4a61e63155b0914667bdafaa59",
"screenshots/wait-root-dark-en.png": "940dd1a9059c32b08acd9adbc626fa5e59ef1999d9e84f2846ca503d9629805d",
"screenshots/wait-setup-light-zh.png": "4c5be7057a8e9c7ce15e8fa9294678bda3a28d7a11208ee36ec63e03ead3d1d9",
"tests/help_smoke.py": "18469c928604d5e8581c1aa702aa7cb9fae59a0dccca2ddd0a808263ae8b920f",
"tests/package_smoke.py": "f9ea830ae0e1801f52c8669b0b06033c6ee8c9a16745acc56c4b70b5f575ed26",
"tests/test_legacy_binding.py": "b2bbae1ef0c2ecdecb2b3caeaee47047293d89507bf890592c1bd23d76908c82",
"tests/test_recovery.py": "a3dac4c91f6a7bd5ee0e3f6d7e6ae2e3f692d28224be03bd30c58f1eb0db51c3",
"tests/test_state.py": "7fcce0b6788210c6f0378be961aa1561a5f77bcca57e4ed9c9492d2e156b2649",
"tests/ui_smoke.py": "d66191f40544b27109f99d6743e80077888f637a1fe9bf47394f359d5229305d",
"ui/components.json": "c9956b81d4afe05c5df651ab933d75a4aae6782e499fba9a653fd992381b2fba",
"ui/index.html": "0ce43c18781e1d0d6184ab0e4dade150a2a79ab8afc3693c54f491bd19dae5d8",
"ui/package-lock.json": "20dc70b3177789a10c9de3f2d6bcdc3cbc570dac47bd8a5c4e31ff137cbe1cda",
"ui/package.json": "395563111a5c62e0a1a3d24861a2803ed2df4c1c0c6f28d15711b9715fae2115",
"ui/postcss.config.js": "f03ac604d74acc4f945ac1c5932485e1636f24ea1014da8bbfa1bc4a93010820",
"ui/rust-toolchain.toml": "9cbde07377abdce69bc9580adb0315d52e2a09d6494a2005550a7e6733d9688b",
"ui/tailwind.config.js": "83a2b606389ae80ddc566da9f28fc5a87b6b012c33d0e2140396b81f8c784131",
"ui/tsconfig.json": "cd09393aa9aab0b15cb2020d329e9f77a745efaa83c032a81121ea6f80c4face",
"ui/vite.config.ts": "0cdd04c180bc500cfbada1781eaba986a84637c820c0bea668c148ed08136d7b",
"verification/help-e5-packages.json": "a2fbf23958da15413d69ec5f5b177bd8628aa2fe54a335308df1374d446f5b88",
"verification/help-e5-sizes.json": "78dd447ba24857800450358348e7fad3bba9e81ac11673aad7e00e2e1477f23f",
"verification/help-mu300-packages.json": "bdd34148c3fe201dac204166635bbc2c1db7a706472031ea98119319aa6ff3fd",
"verification/help-mu300-sizes.json": "7cb880644efb91a6db992746455a6fdbe4019fdb49837c8364ddcaab6a16656b",
"verification/help.json": "d96debbb19bb0f25114fba7e6aa3d5dde9078da64c6e53154114904b2267e11b",
"verification/payload-invariance.json": "e7b36a11dc32fbbaad6bc58a9fd57dff6578bfe0b63ff99fa8218af3cecb2e62",
"verification/ui-polish-e5-packages.json": "ae81da39699cdd8fac3acde62928d4299d6c15c5da9ff2cb1dc16ad072983a1f",
"verification/ui-polish-e5-sizes.json": "93c7833215d99598951392c2608c82f4c6e23605398db02aae6aebd8f1a4d013",
"verification/ui-polish-mu300-packages.json": "0002096d1a12d38c68d09166ed3b63bddc6ec1c199a43ccedc3bac2836f40e86",
"verification/ui-polish-mu300-sizes.json": "31e0df9b4645e98f1fe91c5b831b556424d413d2afa31000e6a90e2ea5c8a350",
"verification/ui-polish-t551m-package.json": "a59c13ef8903326cafae846b00803de934b28ff128c85c55a5b1c3936685d726",
"verification/ui-polish.json": "014d2e86010336d9fafac14eb5852139172cc228c389d5efb1a74fd9acfd7245",
"verification/windows-packages.json": "2527a520a27d9eb0f9243aa9e2ed05b0e4b90caefc8257ea3afe76acdb75a19d",
"ui/src/help-data.ts": "3559333ab059b60829b7aef8fbdf92b932c2ce01cee5d7d8b5eef40cae42e4b6",
"ui/src/help-i18n.ts": "ffc22b67831f01ae70e8d3d98c6e3c0a351f22a1049e05b998bc072ca9b2864a",
"ui/src/i18n.ts": "7f8c2f012a05f0b929b5e24d5474b3757416c2676e96f416134555c11d6db35f",
"ui/src/main.tsx": "04503826ce30559f2f7ad491336de8adcb68970fe5fa20b50f5a0121a1955cbe",
"ui/src/protocol.ts": "c2395c2a4bfea8f0ee399d121087f70c9be1c110f794848648689600c9bbe653",
"ui/src/style.css": "3ce3723977143c46d9ed0bc996540aea0f6b509608a8e4742ff99de24890df8a",
"ui/src/utils.ts": "dd51582c0905c3507bd5dc3d32215a43fc156f6432042a7deb393fe4258b05ba",
"ui/src/vite-env.d.ts": "65996936fbb042915f7b74a200fcdde7e410f32a669b1ab9597cfaa4b0faddb5",
"ui/src-tauri/build.rs": "8af41c0062014fc594e4bb9899e60ee9930ab57d4cf0c73041ff557d6ec736e6",
"ui/src-tauri/Cargo.lock": "d02cf50cd3e518902c97160061cb847dde6a3645a09b7d64842191505e7c25f7",
"ui/src-tauri/Cargo.toml": "af4665509c4623e209c9c8ba95615005b2c52d360d0a1abffe61ba3314455ce7",
"ui/src-tauri/tauri.conf.json": "9ef663647cd1e0e71534b8c39dbe0b12bac69e537f367dd3f0de3e323d7889eb",
"ui/src/components/help-center.tsx": "c81d8d9953e4ce42bcf727f1510460b1b3ef84219efbc1499534068149f90679",
"ui/src/components/ui/button.tsx": "8c1c85a19a49c40d46c575cc6f98fdda85af70edfe381c6f5acdb95ebd44d614",
"ui/src/components/ui/dialog.tsx": "bb174d025902fc427aa605381c5c5807fb397904f04599c6329837eb25a194c0",
"ui/src/components/ui/sonner.tsx": "59738d9ced20160c9d74971beb4fd23b794e5ff0682b998af55f604f92fdc9f8",
"ui/src-tauri/capabilities/default.json": "84a9a609f4cae132de6b7ee626a8d5c396eee5c2030d416922f4db5dc9624299",
"ui/src-tauri/icons/icon.ico": "5851131da4274abc593d41fa701a14ea3a99fda2da02bc5845c70664f7766094",
"ui/src-tauri/src/main.rs": "41368ae5682cd8e71af470ce07685b50267324b9082d87f05bbce08e332c5024",
"ui/src-tauri/gen/schemas/acl-manifests.json": "bdc3ced2ae416f11b23bc9c9b62341a3a59aa7bb5322f04f197bb08cb610409f",
"ui/src-tauri/gen/schemas/capabilities.json": "a4a9ce710aadc06946c296cfb8a0df506767ed310de13e32b5914d295fc81e56",
"ui/src-tauri/gen/schemas/desktop-schema.json": "4a946fe48fbb0c7c535ea53e6070bd8276f3f3d74f96efbaa6d85bd7b53b0f05",
"ui/src-tauri/gen/schemas/windows-schema.json": "4a946fe48fbb0c7c535ea53e6070bd8276f3f3d74f96efbaa6d85bd7b53b0f05"
}
}
+73
View File
@@ -0,0 +1,73 @@
# Windows installer verification — 2026-10-15
Implemented in both repositories with one canonical shared source and a hash-checked generated MU300 mirror. Existing unrelated working-tree changes were preserved. FM_U20 support was not restored.
## Executed
| Check | Result |
|---|---|
| Persistent protocol/state/recovery tests | 27 passed on Windows; real temporary journals, CLI selection among multiple devices and a separate-process OS lock contender |
| e5 targeted installer suites | 65 passed across entrypoints (7), installed detection (3), diagnostics (22), two-stage preparation (9), TF growth (5), partition boot (5), userdata size/failure ordering (6), hybrid package/Magisk fixtures (8) |
| MU300 desktop suites | 43 run in WSL; 39 passed, 4 environment-dependent checks skipped |
| React/TypeScript/Vite release | Passed; main JS about 430 kB (138 kB gzip), help module about 184 kB (61 kB gzip), CSS about 26 kB; help/Markdown code loads on demand |
| Tauri Windows x64 release | Passed with Rust 1.90.0/MSVC, size optimization, LTO and strip |
| Native Windows launch | Passed using system WebView2; real native window captured in `screenshots/native-home.png` |
| UI interaction smoke | Passed: fixed 1120×900 and 800×650 viewport; 120 recovery records; 500-line bounded log; independent scrolling; fixed titles/actions/footer; bottom sidebar reminder; Sonner results/errors and repeated-state deduplication; native dialog/export error handling; light/dark/system themes, Chinese/English, reduced motion, explicit multi-device selection, confirmation, waiting states and completion |
| Onboarding/help smoke | Passed: first launch, three steps/back/finish/skip/replay, persistent acknowledgement, saved-record suppression, offline manual/search/no matches, keyboard focus trapping/restoration, Escape/F1, contextual help during a waiting transaction without sending backend commands, English/Chinese, dark/light and minimum-window bounds |
| Visible button contrast | Home/install pages: minimum 4.91:1 in light mode and 8.76:1 in dark mode (computed colors with alpha compositing; hidden/disabled controls excluded) |
| Frozen backend and CLI | All five final package folders pass real NDJSON hello/package/list and bundled CLI package verification; stdout is strict UTF-8 |
| Frozen MU300 boot builder | Both kernel families pass `--check-boot`, constructing actual boot images for Android A/B on the computer without device access |
| Final ZIP integrity | ZIP CRC tested, exactly one system payload per archive, separate SHA256 and size reports |
| Payload invariance | Existing validated 20261015-all-r5 system/boot/filesystem-tool payload hashes retained; desktop changes stay outside them |
| Source synchronization | `installer/sync.py <mu300-repository> --check` passes |
The new coordinator tests cover expected reboot disconnects, stale pre-reboot ADB sessions, unauthorized ADB, Android setup, missing Magisk, pending su authorization, accepting already-working root, multiple devices, application restart, host record import/export, moved/compatible repair packages, incompatible payload rejection, failed safe-operation retry, nonrepeatable-write refusal, deferred cancellation, OS mutex ownership, stage-specific boot-chain checkpoints, and measured filesystem capacity mismatch.
Device-script tests ran in WSL Ubuntu 22.04 with disposable files and mock block/transport commands. Initial attempts to run POSIX shell fixtures directly with Windows paths failed from path syntax/missing BusyBox; the listed results are the successful Linux/WSL runs. One stale userdata-size fixture was updated to stub its read-only encryption probe so it cannot accidentally reach a real device.
## Screenshots
- [Native desktop home](screenshots/native-home.png): actual Windows Tauri/WebView2 application.
- [Light home, Chinese](screenshots/home-light-zh.png).
- [Final destructive plan, Chinese](screenshots/plan-light-zh.png).
- [Android setup wait, Chinese](screenshots/wait-setup-light-zh.png).
- [Root authorization wait, dark English](screenshots/wait-root-dark-en.png).
- [Completed result and actual capacity, dark English](screenshots/complete-dark-en.png).
- [Recovery list and expanded log at 800×650](screenshots/resume-small-light-zh.png).
- [Scrollable installation form with fixed actions at 800×650](screenshots/install-small-light-zh.png).
- [Final plan at 800×650, dark English](screenshots/plan-small-dark-en.png).
- [Getting started, Chinese](screenshots/onboarding-light-zh.png).
- [Offline help and recovery FAQ, Chinese](screenshots/help-recovery-light-zh.png).
- [Help at 800×650, dark English](screenshots/help-small-dark-en.png).
- [Getting started at 800×650, dark English](screenshots/onboarding-small-dark-en.png).
The browser screenshots use the production React bundle with a **test-only** protocol fixture in `tests/ui_smoke.py` and `tests/help_smoke.py`. That fixture is not imported into production, does not exist in the firmware packages, and does not open ADB/SSH. These screenshots verify rendering and interaction, not a completed hardware installation. The native screenshot verifies an actual Windows launch.
The UI polish pass also cleared stale device inspection results on package/view changes, disabled device selection during inspection, preserved an explicitly chosen serial on refresh among multiple devices, caught rejected native and clipboard operations, moved focus to the new page heading without scrolling the document, distinguished waiting from execution icons, and prevented prior-phase transfer counters from appearing in a later phase. Motion honors reduced motion without weakening the final confirmation or safe-pause rules.
Onboarding and help use the same source in both repositories. The detailed manual is generated from the same bilingual `GUIDE.md` copied to `START-HERE.md`, and that document is now fingerprinted with the compiled sources. The FAQ explicitly states that no manual transaction creation is needed, records are automatic, full exported backups can be imported elsewhere, and this version cannot reconstruct a record from device state alone if both host records and exported backups are lost. Help never starts, pauses or cancels an installation.
## Hardware boundary and recovery limitations
No connected-device installation, formatting, GPT mutation, userdata reset/shrink, boot-chain synchronization, misc write, live SSH upgrade or Magisk flash was performed in this task. ADB enumeration during read-only package smoke found zero devices. Hardware behavior of those paths is therefore **not newly hardware-validated**. Their existing device code is reused; automatic tests exercise the host protocol and recovery logic with simulated transports.
Uncertain interrupted writes do not automatically repeat partition preparation. A trusted host transaction plus matching hardware/geometry/token is required to enter stage two. A completed effect is skipped; a started nonrepeatable effect without conclusive completion stops for recovery. Missing host records with insufficient backups/markers stop rather than infer a partition layout. This is deliberate fail-closed behavior, not a guarantee that every power-loss point can recover without manual backup-based repair.
Without ADB, the host cannot know whether Android is still booting or USB debugging is disabled. The UI presents the full concrete setup/debugging steps and does not time out the transaction. Management verification requires the user to connect the USB network/hotspot and supply the correct SSH credentials. The application never modifies the computer's adapters/routes or joins a hotspot.
Release payloads were taken from the repositories' existing `20261015-all-r5` validated package directories. Unrelated in-progress kernel/UI changes were not rebuilt into these firmware images or reverted. Future normal packaging uses current repository payloads and requires a matching portable GUI artifact.
## Artifacts and sizes
Use the `*-windows.zip` archives and matching `.zip.sha256`/`.size.json` in:
- e5: `out/gui-releases/20261015/` (E5, M8, T551M).
- MU300: `release/gui-20261015/` (6.18.54 and 7.2.8; F50/MU300, V50, U30Air via the existing profile adapter).
The polished UI refresh is delivered separately in e5 `out/gui-releases/20261015-ui2/` and MU300 `release/gui-20261015-ui2/`, keeping the same validated firmware. The old M8 GUI was running during the refresh, so its executable and original release were left in place. The refreshed GUI executable is 3,451,904 bytes (3.29 MiB). The version remains 1.0.0 for this local, unpublished UI revision; use the `ui2` paths for the updated builds.
The subsequent onboarding/offline-help revision is in e5 `out/gui-releases/20261015-guide/` and MU300 `release/gui-20261015-guide/`. It retains the same system/boot payloads and independent package directories. Use these `guide` paths for the latest local build. Per-package sizes and frozen-backend checks are recorded under `verification/help-*.json`.
Each extracted folder contains `OpenWrt-Installer.exe`, compatible `OpenWrt-Installer.py`, bilingual `START-HERE.md`, Magisk root entries and subdirectories for tools/resources. The EXE must be kept with its package. `verification/windows-packages.json` contains actual frozen-backend/CLI results. Machine-readable per-archive size reports distinguish root GUI executable, host backend/tools (`tools/`, `scripts/`, `desktop/`), firmware payload (`files/` or `payload/`) and compressed ZIP bytes. Counts do not include build caches or development dependencies.
See [build instructions](README.md), [user guide](GUIDE.md) and [protocol contract](PROTOCOL.md).
+1
View File
@@ -0,0 +1 @@
"""Shared desktop installer protocol. No device operations on import."""
+393
View File
@@ -0,0 +1,393 @@
"""Repository adapters call existing installation code, never frontend shell."""
from contextlib import redirect_stdout, redirect_stderr
import gzip
import hashlib
import importlib.util
import io
import json
from pathlib import Path
import re
import secrets
import shlex
import struct
import sys
import time
from types import SimpleNamespace
from . import gpt
from .state import Pending, RecoveryRequired, atomic_json, sha
from .transport import Adb, push_chunks
def load(path, name):
spec = importlib.util.spec_from_file_location(name, path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
class Quiet(io.TextIOBase):
def write(self, text):
return len(text)
def flush(self):
pass
def args_for(record, directory):
choices = record['choices']
selected_gib = record['plan']['openwrt_bytes'] / (1 << 30) if choices['method'] in ('part','image') else choices.get('size_gib',4)
return SimpleNamespace(y=True, apn='', ssid=None, wifi_key=record.get('secrets', {}).get('wifi_key', ''), grow_fs=choices.get('grow', True),
part_size=str(selected_gib), image_size=str(selected_gib),
size=str(selected_gib), format_userdata=record['plan'].get('wipe', False),
tf=choices['method'] == 'tf', data=choices['method'] == 'image',
part=choices['method'] == 'part', reinstall_part=choices['method'] == 'reinstall',
boot_openwrt=choices['method'] == 'boot', resume=False, resume_part=None,
transaction=None, backup_dir=str(directory / 'legacy-backups'), probe=False,
serial=record['device']['serial'], adb=None, host=choices.get('host'))
class Adapter:
def __init__(self, package, context=None):
self.package = package
self.root = Path(package['path'])
self.kind = package['adapter']
self.ctx = context
self.legacy = load(self.root / 'OpenWrt-Installer.py', '_installer_' + secrets.token_hex(4))
self.legacy.GUI = self
if self.kind == 'e5':
self.legacy.B, self.legacy.F, self.legacy.SCRIPTS = str(self.root), str(self.root/'files'), str(self.root/'scripts')
else:
self.legacy.package_root = lambda: self.root
self.adb = None
self.password = ''
self.expected_ssh_key = None
def stage(self, stage, status='running', **details):
if self.ctx:
self.ctx.stage(stage, status, **details)
def transfer(self, name, done, total, since):
if self.ctx:
self.ctx.transfer(name, done, total, since)
def action(self, name, operation, retry_safe=False):
if not self.ctx:
raise ValueError('Writes are unavailable during a probe')
if self.ctx.record.get('legacy') and name in ('bootchain-sync', 'misc-trial'):
state = json.loads(Path(self.ctx.record['legacy']).read_text(encoding='utf-8'))
name += '-' + state.get('phase', state.get('state', 'unknown'))
return self.ctx.effect(name, operation, retry_safe=retry_safe)
def saved(self, path, record):
if self.ctx:
self.ctx.legacy_record(path, record)
def validate_plan(self, target, wipe=False, capacity=None, gap_start=None):
plan = self.ctx.record['plan']
if (target != plan['target'] or bool(wipe) != bool(plan['wipe']) or
capacity is not None and capacity != plan['openwrt_bytes'] or
gap_start is not None and gap_start != plan.get('gap_start')):
raise ValueError('Actual installation path differs from the confirmed plan; nothing further written / 实际安装路径与已确认计划不一致,已停止后续写入')
def backup_base(self):
return str(self.ctx.directory)
def wait_android(self, *_):
self.stage('android_boot', 'waiting_device')
raise Pending()
def reboot(self):
# Persist expected loss of transport BEFORE sending reboot.
self.stage('android_boot' if self.ctx.record['plan'].get('two_stage') else 'openwrt_boot', 'waiting_device')
def push(self, call, shell, local, remote):
return push_chunks(call, shell, local, remote, self.ctx)
def validate_ssh(self, client):
fingerprint = hashlib.sha256(client.get_transport().get_remote_server_key().asbytes()).hexdigest()
if self.expected_ssh_key and fingerprint != self.expected_ssh_key:
raise ValueError('SSH device identity changed / SSH 设备身份改变')
return fingerprint
def bind(self, serial):
self.adb = Adb(self.root, serial)
if self.kind == 'e5':
self.legacy.ADB = self.adb.exe
self.legacy.SERIAL = serial
self.legacy.SU = None
self.legacy.find_adb = lambda: None
def probe(self, serial, method='part'):
self.bind(serial)
devices = self.adb.devices()
entry = next((d for d in devices if d['serial'] == serial), None)
if not entry:
return {'serial': serial, 'readiness': 'android_boot'}
if entry['state'] != 'device':
return {'serial': serial, 'readiness': 'debug_authorization' if entry['state'] == 'unauthorized' else 'android_boot'}
properties = self.adb.properties()
device = {'serial': serial, 'model': properties['ro.product.model'], 'system': 'Android',
'slot': properties['ro.boot.slot_suffix'], 'root': False, 'readiness': 'android_boot'}
device['boot_id'] = self.adb.shell('cat /proc/sys/kernel/random/boot_id').strip()
if properties['sys.boot_completed'] != '1':
return device
initialized = self.adb.shell('settings get secure user_setup_complete').strip()
if initialized == '0':
device['readiness'] = 'android_setup'
return device
status = self.adb.root_status()
device.update(root=status == 'ready', readiness=status)
if status != 'ready':
return device
if self.kind == 'e5':
self.legacy.SU = self.adb.su
profile = self.legacy.package_profile()
if device['model'] not in profile['android_models']:
raise ValueError('Package model differs / 安装包机型不匹配: ' + device['model'])
device['profile'] = profile['profile']
if device['slot'] != '_a' or properties['ro.boot.verifiedbootstate'] != 'orange':
raise ValueError('E5 requires unlocked Android slot A / E5 要求已解锁且当前 Android 在 A 槽')
else:
device['profile'] = self.legacy.android_profile(device['model'] + '\n' + properties['ro.product.device'], properties['ro.board.platform'])
# Trial boot uses only the boot signature, boot-chain check and misc.
# Do not access the root filesystem to detect an installation.
text = self.adb.shell('set -e; d=$(readlink -f /dev/block/by-name/userdata); n=${d##*/}; b=${n%p*}; '
'echo NODE=$n; echo CID=$(cat /sys/class/block/$b/device/cid); '
'echo START=$(cat /sys/class/block/$n/start); echo SIZE=$(cat /sys/class/block/$n/size); '
'echo DISK_SIZE=$(cat /sys/class/block/$b/size); '
'echo FREE=$(df -Pk /data | tail -n1 | awk \'{print $4}\'); '
'echo SOURCE=$(awk \'$2=="/data" {print $1;exit}\' /proc/mounts); '
'for u in /sys/class/block/${b}p*/uevent; do '
'grep -qE "^PARTNAME=(e5root|mu300root)$" "$u" && { n=${u%/uevent}; echo ROOT=${n##*/}; } || true; done; '
'if [ -b /dev/block/mmcblk1p1 ]; then echo TF=/dev/block/mmcblk1p1; '
'elif [ -b /dev/block/mmcblk1 ]; then echo TF=/dev/block/mmcblk1; fi', root=True)
storage = dict(line.split('=', 1) for line in text.splitlines() if '=' in line)
if not re.fullmatch(r'mmcblk\d+p\d+', storage['NODE']) or not re.fullmatch('[a-f0-9]{32}', storage['CID']):
raise ValueError('Cannot establish eMMC identity / 无法确认闪存身份')
for key in ('START', 'SIZE', 'DISK_SIZE', 'FREE'):
storage[key] = int(storage[key])
encrypted = properties['ro.crypto.state'] == 'encrypted' or properties['ro.crypto.type'] in ('file', 'block') or storage['SOURCE'].startswith(('/dev/block/dm-', '/dev/mapper/'))
device.update(cid=storage['CID'], storage=storage, encrypted=encrypted, existing=bool(storage.get('ROOT')),
tf=storage.get('TF'), userdata_bytes=storage['SIZE']*512, free_bytes=storage['FREE']*1024)
if storage.get('TF'):
node = storage['TF'].rsplit('/', 1)[-1]
device['tf_bytes'] = int(self.adb.shell('cat /sys/class/block/' + node + '/size', root=True).strip())*512
disk_node = re.sub(r'p\d+$', '', node)
device['tf_identity'] = {'cid': self.adb.shell('cat /sys/class/block/'+disk_node+'/device/cid', root=True).strip(),
'sectors': device['tf_bytes']//512,
'start': self.adb.shell('cat /sys/class/block/'+node+'/start 2>/dev/null || echo 0', root=True).strip()}
if storage.get('ROOT'):
node = storage['ROOT']
storage['ROOT_START'], storage['ROOT_SIZE'] = map(int, self.adb.shell('cat /sys/class/block/'+node+'/start /sys/class/block/'+node+'/size', root=True).split())
if method != 'boot':
space = self.read_gpt(storage)
device['gpt'] = {k: v for k, v in space.items() if k not in ('first', 'last')}
if self.kind == 'e5':
# Reuse the existing internal-vs-removable selection policy.
try:
disk = self.legacy.device_sd()
node = disk.rsplit('/', 1)[-1]
if self.adb.shell('test -b '+disk+'p1; echo $?', root=True).strip() == '0':
target = disk+'p1'
else:
parts = self.adb.shell('ls /sys/class/block/'+node+'p* 2>/dev/null; true', root=True).strip()
if parts: raise ValueError('TF has partitions but no p1; cannot select the whole card')
target = disk
device['tf'] = target
device['tf_bytes'] = int(self.legacy.device_size(target))
device['tf_identity'] = {'cid': self.adb.shell('cat /sys/class/block/'+node+'/device/cid', root=True).strip(),
'sectors': device['tf_bytes']//512,
'start': self.adb.shell('cat /sys/class/block/'+target.rsplit('/',1)[-1]+'/start 2>/dev/null || echo 0', root=True).strip()}
storage['TF'] = target
except SystemExit:
device['tf'] = None
storage.pop('TF', None)
return device
def read_gpt(self, storage):
disk = '/dev/block/' + storage['NODE'].split('p')[0]
sectors = storage['DISK_SIZE']
primary = self.adb.read(f'dd if={disk} bs=512 skip=1 count=1 2>/dev/null')
backup = self.adb.read(f'dd if={disk} bs=512 skip={sectors-1} count=1 2>/dev/null')
front, tail = gpt.gpt_backup_layout(primary, backup, sectors)
first = self.adb.read(f'dd if={disk} bs=512 count={front} 2>/dev/null')
last = self.adb.read(f'dd if={disk} bs=512 skip={tail} count={sectors-tail} 2>/dev/null')
space = gpt.gpt_space(first, last, sectors)
# Retain unlisted old filesystems rather than declaring their gap free.
safe = []
for start, size in space['gaps']:
candidates = {start}
if self.kind == 'mu300':
# Match Android.gpt exactly: old MU300 roots may sit at a raw
# offset inside a GPT gap, rather than at its first sector.
end = max(p['end'] for p in space['parts'])
candidates.update(offset for offset in (27762098176//512, (end//4096+1)*4096)
if start <= offset and offset+4 <= start+size)
occupied = False
for offset in sorted(candidates):
raw = self.adb.read(f'dd if={disk} bs=512 skip={offset} count=4 2>/dev/null')
if len(raw) != 2048:
raise ValueError('Incomplete free-space signature read')
occupied |= raw[1080:1082] == b'\x53\xef' or raw[1024:1028] == bytes.fromhex('1020f5f2')
if not occupied:
safe.append((start, size))
space.update(first=first, last=last, safe_gaps=safe,
largest=max((size for _, size in safe), default=0) if space['empty'] else 0)
return space
def backup(self, device):
destination = self.ctx.directory / 'backup'
if 'backup' in self.ctx.record['completed']:
sums = json.loads((destination/'checksums.json').read_text())
if not sums or any(sha(destination/n) != h for n, h in sums.items()):
raise ValueError('Computer backup is damaged / 电脑备份损坏')
return
self.stage('backup')
destination.mkdir(parents=True, exist_ok=True)
storage = device['storage']
space = self.read_gpt(storage)
(destination/'gpt-first.bin').write_bytes(space['first'])
(destination/'gpt-last.bin').write_bytes(space['last'])
atomic_json(destination/'identity.json', device)
for name in ['misc'] + [f'{n}_{slot}' for n in ('boot', 'uboot', 'sml', 'teecfg', 'trustos', 'vbmeta') for slot in ('a', 'b')]:
self.ctx.boundary()
script = f'dd if=/dev/block/by-name/{name} bs=4096 count=1 2>/dev/null' if name == 'misc' else f'cat /dev/block/by-name/{name}'
data = self.adb.read(script)
if not data:
raise ValueError('Empty backup / 备份为空: ' + name)
(destination/(name+'.bin')).write_bytes(data)
expected = hashlib.sha256(data).hexdigest()
actual = self.adb.shell('(set -o pipefail; ' + script + ') | sha256sum', root=True, timeout=120).split()[0]
if expected != actual:
raise ValueError('Backup readback checksum mismatch / 备份回读校验失败: ' + name)
atomic_json(destination/'checksums.json', {p.name: sha(p) for p in destination.iterdir() if p.is_file() and p.name != 'checksums.json'})
self.ctx.record['completed'].append('backup')
self.ctx.store.save(self.ctx.record)
def execute(self):
record = self.ctx.record
choices = record['choices']
method = choices['method']
a = args_for(record, self.ctx.directory)
if method != 'update':
self.bind(record['device']['serial'])
a.adb = self.adb.exe
self.expected_ssh_key = record['device'].get('ssh_key')
with redirect_stdout(Quiet()), redirect_stderr(Quiet()):
if method == 'update':
self.stage('transfer_install')
if self.kind == 'e5':
return self.update_e5(a)
return self.legacy.update(a, self.root)
self.probe(record['device']['serial'], method)
if record.get('legacy'):
self.stage('recheck')
saved = json.loads(Path(record['legacy']).read_text(encoding='utf-8'))
if self.kind == 'mu300' and saved.get('state') == 'installed':
# Host checkpoint follows root, boot and misc verification.
# A preparation token no longer occupies the formatted root.
# Recheck hardware/geometry, then wait for the installed OS;
# never pass an installed root back to a preparation writer.
actual = self.probe(record['device']['serial'], method)
expected = saved['storage']
current = actual['storage']
if (actual['cid'] != expected['CID'] or actual['slot'].removeprefix('_') != saved['android_slot'] or
current.get('ROOT_START') != expected['START']+saved['target'] or current.get('ROOT_SIZE') != saved['need']):
raise RecoveryRequired('Installed partition differs from saved geometry / 已安装分区与记录不一致')
return None
if self.kind == 'e5':
a.resume_part = record['legacy']
return self.legacy.part_two_stage('resume', a)
a.part = False
a.resume = True
a.transaction = record['legacy']
return self.legacy.install(a, self.root, json.loads((self.root/'desktop/manifest.json').read_text()))
done = {name for name, value in record['effects'].items() if value['state'] == 'done'}
if (self.kind == 'e5' and 'misc-trial' in done or self.kind == 'mu300' and
('root-tf-write' in done or any(name.startswith('boot-and-misc-') for name in done))):
# Final selection is after image/root readback in the legacy
# installers. A crash before the coordinator's next checkpoint
# must only wait for boot, never replay the full entrypoint.
return None
# A whole initial run must never be replayed after a write started.
# Explicit prepared records are the only entry into destructive resume.
if any(not name.startswith('backup') for name in record['effects']) and not (self.kind == 'e5' and method == 'tf'):
raise RecoveryRequired('Interrupted installation has no verified resume marker; export backups for recovery / 写入中断且无可验证续装标记,请导出备份进行恢复')
self.backup(record['device'])
self.stage('prepare')
if self.kind == 'mu300':
return self.legacy.install(a, self.root, json.loads((self.root/'desktop/manifest.json').read_text()))
if method == 'tf':
return self.legacy.install_sd(a)
if method == 'image':
return self.legacy.install(a)
if method == 'reinstall':
return self.legacy.part_two_stage('reinstall', a)
if method == 'boot':
return self.legacy.boot_openwrt(a)
if record['plan'].get('gap_start') is not None:
return self.e5_free(a)
return self.legacy.install_part(a)
def e5_free(self, args):
"""Add a GPT entry in verified free space, then use the existing writer.
Android reboot refreshes block nodes. Only a token is staged outside GPT;
the system payload remains on the PC until the existing writer runs.
"""
m, record = self.legacy, self.ctx.record
s, plan = record['device']['storage'], record['plan']
space = self.read_gpt(s)
first, last = gpt.gpt_add_root(space['first'], space['last'], s['DISK_SIZE'], plan['gap_start'], plan['openwrt_bytes']//512, 'e5root')
directory = self.ctx.directory/'legacy-backups/free-space'
directory.mkdir(parents=True, exist_ok=True)
token = secrets.token_hex(16)
raw = 0
with gzip.open(self.root/'files/openwrt.ext4.gz', 'rb') as stream:
for data in iter(lambda: stream.read(1 << 20), b''):
raw += len(data)
data = dict(node=s['NODE'], cid=s['CID'], start=s['START'], size=s['SIZE'])
state = dict(version=2, phase='awaiting-android', token=token, serial=record['device']['serial'],
model=record['device']['model'], data=data, target=s['SIZE'], need=plan['openwrt_bytes']//512,
root_start=plan['gap_start'], grow=int(args.grow_fs), raw_size=raw, apn='',
ssid=m.default_hotspot_name(), key=secrets.token_urlsafe(12),
boot_sha=sha(self.root/'files/boot.img'), image_sha=sha(self.root/'files/openwrt.ext4.gz'))
path = directory/'transaction.json'
atomic_json(path, state)
self.saved(path, state)
disk = '/dev/block/'+s['NODE'].split('p')[0]
for name, content in [('before-first', space['first']), ('before-last', space['last']), ('new-first', first), ('new-last', last),
('marker', ('E5-PART-PREPARED-V2 '+token+'\n').encode().ljust(512, b'\0'))]:
local = directory/(name+'.bin')
local.write_bytes(content)
m.push(str(local), '/data/local/tmp/gui-'+name, name)
front, tail = space['front'], space['tail']
def commit():
# Compare using files: Android shells need not support process substitution.
check = (f'dd if={disk} of=/data/local/tmp/gui-read-first bs=512 count={front}; '
f'dd if={disk} of=/data/local/tmp/gui-read-last bs=512 skip={tail} count={s["DISK_SIZE"]-tail}; '
'cmp -s /data/local/tmp/gui-before-first /data/local/tmp/gui-read-first; '
'cmp -s /data/local/tmp/gui-before-last /data/local/tmp/gui-read-last; ')
write = (f'dd if=/data/local/tmp/gui-marker of={disk} bs=512 seek={plan["gap_start"]} conv=notrunc,fsync; '
f'dd if=/data/local/tmp/gui-new-last of={disk} bs=512 seek={tail} conv=notrunc,fsync; '
f'dd if=/data/local/tmp/gui-new-first of={disk} bs=512 conv=notrunc,fsync')
m.su_checked('Creating root partition / 创建独立分区', check+write)
if self.adb.read(f'dd if={disk} bs=512 count={front} 2>/dev/null') != first or self.adb.read(
f'dd if={disk} bs=512 skip={tail} count={s["DISK_SIZE"]-tail} 2>/dev/null') != last:
raise RecoveryRequired('GPT readback differs; do not reboot / GPT 回读不一致,请勿重启')
self.action('gpt-free-space', commit)
self.reboot()
self.adb.call('reboot')
raise Pending()
def update_e5(self, args):
helper = load(self.root/'scripts/tools/e5-update.py', '_update')
helper.GUI = self
raw_size, raw_hash = self.legacy.gz_metadata(str(self.root/'files/openwrt.ext4.gz'))
previous = sys.argv
try:
sys.argv = ['e5-update', '--package', str(self.root), '--host', args.host,
'--raw-size', str(raw_size), '--raw-sha256', raw_hash]
return helper.main()
finally:
sys.argv = previous
+84
View File
@@ -0,0 +1,84 @@
"""Validated GPT gap operations, shared with the existing MU300 installer."""
import struct
import uuid
import zlib
def gpt_backup_layout(primary, backup, sectors):
def header(raw,at):
if len(raw)!=512 or raw[:8]!=b'EFI PART':raise ValueError('Invalid GPT header')
size=struct.unpack_from('<I',raw,12)[0]
if not 92<=size<=512:raise ValueError('Invalid GPT header size')
check=bytearray(raw[:size]);expected=struct.unpack_from('<I',check,16)[0];check[16:20]=bytes(4)
if zlib.crc32(check)!=expected:raise ValueError('GPT header checksum failed')
current,alternate=struct.unpack_from('<QQ',raw,24)
table,count,entrysize=struct.unpack_from('<QII',raw,72)
if current!=at or count<1 or count>1024 or entrysize!=128:raise ValueError('Unsupported GPT geometry')
return alternate,table,(count*entrysize+511)//512,raw[56:72],raw[80:92]
a=header(primary,1);b=header(backup,sectors-1)
if a[0]!=sectors-1 or b[0]!=1 or a[3:]!=b[3:]:raise ValueError('GPT copies disagree')
front=a[1]+a[2];tail=b[1]
if not (2<=a[1]<front<=4096 and sectors-4096<=tail and tail+b[2]==sectors-1):raise ValueError('GPT backup range is invalid')
return front,tail
def gpt_space(first,last,sectors):
"""Validate both on-disk GPT copies and return aligned, genuinely unallocated ranges."""
primary=first[512:1024];backup=last[-512:]
front,tail=gpt_backup_layout(primary,backup,sectors)
if len(first)!=front*512 or len(last)!=(sectors-tail)*512:
raise ValueError('Incomplete GPT snapshot')
start,end=struct.unpack_from('<QQ',primary,40)
if (start,end)!=struct.unpack_from('<QQ',backup,40) or not front<=start<=end<tail:
raise ValueError('GPT usable bounds disagree or overlap metadata')
table,count,entry=struct.unpack_from('<QII',primary,72)
data=first[table*512:table*512+count*entry]
if data!=last[:count*entry] or zlib.crc32(data)!=struct.unpack_from('<I',primary,88)[0]:
raise ValueError('GPT table checksum/copy mismatch')
parts=[];empty=[]
for i in range(count):
raw=data[i*entry:(i+1)*entry]
if raw[:16]==bytes(16):empty.append(i);continue
a,b=struct.unpack_from('<QQ',raw,32)
name=raw[56:128].decode('utf-16-le').split('\0',1)[0]
if not start<=a<=b<=end:raise ValueError('GPT partition outside usable bounds: '+name)
parts.append({'n':i+1,'start':a,'end':b,'name':name})
at=start;gaps=[]
for part in sorted(parts,key=lambda p:p['start'])+[{'start':end+1,'end':end}]:
if part['start']<at:raise ValueError('Overlapping GPT partitions')
aligned=(at+2047)//2048*2048
limit=(part['start']//2048)*2048
if limit>aligned:gaps.append((aligned,limit-aligned))
at=part['end']+1
return {'front':front,'tail':tail,'parts':parts,'empty':empty,'gaps':gaps,
'largest':max((size for _,size in gaps),default=0) if empty else 0}
def gpt_add_root(first,last,sectors,offset,need,root_name="mu300root"):
info=gpt_space(first,last,sectors)
if any(p['name']==root_name for p in info['parts']):raise ValueError('mu300root already exists')
if not info['empty'] or need<4194304 or offset%2048 or need%2048 or not any(
offset>=a and offset+need<=a+n for a,n in info['gaps']):
raise ValueError('Requested root is not in an aligned GPT free range')
idx=info['empty'][0];entry=bytearray(128)
entry[:16]=uuid.UUID('0fc63daf-8483-4772-8e79-3d69d8477de4').bytes_le
entry[16:32]=uuid.uuid4().bytes_le
struct.pack_into('<QQ',entry,32,offset,offset+need-1)
name=root_name.encode('utf-16-le');entry[56:56+len(name)]=name
copies=[]
for raw,header_offset,table_offset in ((first,512,struct.unpack_from('<Q',first,584)[0]*512),(last,len(last)-512,0)):
new=bytearray(raw);new[table_offset+idx*128:table_offset+(idx+1)*128]=entry
count=struct.unpack_from('<I',new,header_offset+80)[0]
struct.pack_into('<I',new,header_offset+88,zlib.crc32(new[table_offset:table_offset+count*128]))
struct.pack_into('<I',new,header_offset+16,0)
hsize=struct.unpack_from('<I',new,header_offset+12)[0]
struct.pack_into('<I',new,header_offset+16,zlib.crc32(new[header_offset:header_offset+hsize]))
copies.append(bytes(new))
gpt_space(*copies,sectors)
return copies
def free_root_range(info,need):
if not info['empty']:return None
# Old MU300 installs may live outside GPT at this fixed raw offset. Such
# an area is retained even though a partition table calls it unallocated.
gaps=info.get('safe_gaps',info['gaps'])
candidates=[(n,a) for a,n in gaps if n>=need]
return max(candidates)[1] if candidates else None
+44
View File
@@ -0,0 +1,44 @@
"""Content identity permits moved directories and compatible repair releases."""
import json
from pathlib import Path
import re
from .state import sha
def safe_file(root, name):
path = (root / name).resolve()
if not path.is_relative_to(root.resolve()) or not path.is_file():
raise ValueError('Missing or unsafe package file / 安装包文件缺失或路径不安全: ' + name)
return path
def inspect_package(directory):
root = Path(directory).resolve()
mu = root / 'desktop/manifest.json'
if mu.is_file():
manifest = json.loads(mu.read_text(encoding='utf-8'))
checks = {**manifest['magisk'], **manifest['desktop']}
adapter, profile, layout, kernel = 'mu300', 'mu300-family', 'mu300root-container', manifest['kernel']
mapping = manifest.get('magisk_layout', {})
names = [mapping.get(n, n) for n in ('boot-linux.img', 'mu300-openwrt.tar.gz', 'busybox',
'rootfs-critical.sha256', 'rootfs.requirements')]
names += [n for n in checks if n.startswith('desktop/files/boot/repair/')]
else:
profile_data = json.loads(safe_file(root, 'files/device-profile.json').read_text())
adapter, profile, layout, kernel = 'e5', profile_data['profile'], 'e5root-ext4', 'e5-boot-v2'
if profile not in ('e5', 'm8', 't551m'):
raise ValueError('Unsupported device profile / 不支持的机型')
checks = {}
for line in safe_file(root, 'files/SHA256SUMS').read_text().splitlines():
digest, name = line.split(None, 1)
checks[name.strip().removeprefix('*')] = digest
names = ['files/boot.img', 'files/openwrt.ext4.gz', 'files/ext4-tools.tar']
for name, expected in checks.items():
if not re.fullmatch('[a-f0-9]{64}', expected) or sha(safe_file(root, name)) != expected:
raise ValueError('Package checksum mismatch / 安装包校验失败: ' + name)
payloads = {name: sha(safe_file(root, name)) for name in names}
if not (root/'OpenWrt-Installer.py').is_file():
raise ValueError('Missing compatible Python entry / 缺少兼容安装入口')
return {'protocol': 1, 'adapter': adapter, 'profile': profile, 'layout': layout, 'kernel': kernel,
'payloads': payloads, 'path': str(root), 'name': root.name}
+416
View File
@@ -0,0 +1,416 @@
"""NDJSON command server and persistent coordinator. No generic exec command."""
from contextlib import ExitStack
import hashlib
import io
import json
import math
import os
from pathlib import Path
import re
import secrets
import shutil
import sys
import threading
import time
import zipfile
from .adapter import Adapter
from .package import inspect_package
from .state import Cancelled, Context, DeviceLock, Pending, RecoveryRequired, Store, compatible
from .transport import Adb
METHODS = {'tf', 'part', 'reinstall', 'image', 'boot', 'update'}
def plan_install(package, device, choices):
method = choices.get('method')
if method not in METHODS:
raise ValueError('Unknown installation method')
if device.get('readiness') != 'ready':
raise ValueError('Device is not ready / 设备尚未就绪')
if method == 'update':
return {'method': method, 'wipe': False, 'openwrt_bytes': device['capacity'], 'two_stage': False,
'preserves_settings': True, 'host': choices['host']}
size = choices.get('size_gib', 4)
if type(size) not in (float, int) or not math.isfinite(size) or size <= 0:
raise ValueError('Size must be a positive number / 容量必须为正数')
size_bytes = math.ceil(size*1024/4)*4*(1 << 20)
plan = {'method': method, 'wipe': False, 'two_stage': False, 'openwrt_bytes': size_bytes,
'android_bytes': device['userdata_bytes'], 'grow': choices.get('grow', True),
'target': None, 'data_impact': method}
storage = device['storage']
if method == 'boot':
plan.update(openwrt_bytes=0, target='misc', temporary=True)
elif method == 'tf':
if not device.get('tf'):
raise ValueError('No TF card / 未检测到 TF 卡')
plan.update(target=device['tf'], openwrt_bytes=device['tf_bytes'])
plan['target_identity'] = device.get('tf_identity')
if plan['openwrt_bytes'] < 2 << 30:
raise ValueError('TF target is smaller than the system image / TF 分区小于系统镜像')
elif method == 'reinstall':
if not device.get('existing'):
raise ValueError('No existing internal partition / 没有可重装的内置分区')
plan.update(target=storage['ROOT'], openwrt_bytes=storage['ROOT_SIZE']*512)
elif method == 'image':
if device['encrypted']:
raise ValueError('Encrypted userdata cannot boot an image / 加密 userdata 不支持镜像启动')
uploads = sum((Path(package['path'])/name).stat().st_size for name in package['payloads'])
maximum = device['free_bytes'] - (1536 << 20) - uploads - (2 << 30 if package['adapter'] == 'mu300' else 0)
if size_bytes < 2 << 30 or size_bytes > maximum:
raise ValueError(f'Image requires staging space and Android reserve; maximum {max(0,maximum)/(1<<30):.2f} GiB / 镜像大小超出含临时空间与 Android 预留的范围')
plan.update(target='userdata-image', maximum_bytes=maximum, experimental=True)
else:
if device.get('existing'):
raise ValueError('Internal partition exists; choose update or reinstall / 已存在内置分区,请选择更新或重装')
if size_bytes < 2 << 30:
raise ValueError('OpenWrt needs at least 2 GiB / OpenWrt 至少需要 2 GiB')
candidates = [(n, a) for a, n in device['gpt']['safe_gaps'] if n*512 >= size_bytes]
gap = max(candidates)[1] if candidates and device['gpt']['empty'] else None
if gap is not None:
plan.update(gap_start=gap, target='GPT unallocated space', two_stage=package['adapter'] == 'e5')
else:
wipe = device['encrypted'] or bool(choices.get('wipe'))
android = device['userdata_bytes'] - size_bytes
used = device['userdata_bytes'] - device['free_bytes']
if android < (2 << 30) or (not wipe and android < used+(2 << 30)):
raise ValueError('Insufficient Android retained space / Android 保留空间不足')
plan.update(wipe=wipe, two_stage=wipe, android_bytes=android, target='userdata shrink')
plan['offline'] = True
return plan
class Service:
def __init__(self, package_root, store=None, output=None):
self.package_root = str(Path(package_root).resolve())
self.store = store or Store()
self.output = output or sys.stdout
self.write_lock = threading.Lock()
self.active = None
self.worker = None
self.package = None
self.adapters = Adapter
self.stop = threading.Event()
def emit(self, kind, data, request_id=None):
event = {'protocol': 1, 'type': kind, 'data': data}
if request_id is not None:
event['id'] = request_id
with self.write_lock:
self.output.write(json.dumps(event, ensure_ascii=False) + '\n')
self.output.flush()
def adapter(self, package=None, context=None):
return self.adapters(package or self.package, context)
def public(self, record):
return Context(self.store, record, lambda *_: None).snapshot()
def dispatch(self, request):
if request.get('protocol') != 1:
raise ValueError('Protocol version mismatch')
command, p = request.get('command'), request.get('params', {})
if not isinstance(p, dict):
raise ValueError('Parameters must be an object')
if command == 'hello':
return {'protocol': 1, 'app_data': str(self.store.base), 'package_path': self.package_root,
'transactions': [self.public(r) for r in self.store.list()]}
if command == 'snapshot':
return self.active.snapshot() if self.active else None
if command == 'list':
return [self.public(r) for r in self.store.list()]
if command == 'cancel':
if self.active:
self.active.cancel = True
self.active.record['cancel_requested'] = True
self.store.save(self.active.record)
return {'accepted': True, 'deferred': self.active.record['unsafe']}
return {'accepted': False}
if command == 'can_close':
return not self.worker or not self.worker.is_alive()
if self.worker and self.worker.is_alive() and command not in ('export',):
raise ValueError('An operation is active / 任务正在执行')
if command == 'package':
self.package = inspect_package(p.get('path') or self.package_root)
self.package_root = self.package['path']
return self.package
if command == 'devices':
return Adb(self.package_root).devices()
if command == 'probe':
if not self.package:
raise ValueError('Verify a package first / 请先校验安装包')
if not isinstance(p.get('serial'), str) or not p['serial']:
raise ValueError('Select a device / 请选择设备')
return self.adapter().probe(p['serial'], p.get('method', 'part'))
if command == 'probe_update':
return self.probe_update(p)
if command == 'plan':
if not self.package:
raise ValueError('Verify package first')
choices = p['choices']
if choices.get('method') == 'update':
device = self.probe_update(p)
else:
device = self.adapter().probe(p['serial'], choices['method'])
plan = plan_install(self.package, device, choices)
record = self.store.create(self.package, device, choices, plan)
record['data_directory'] = str(self.store.directory(record['id']))
record['secrets'] = {'wifi_key': secrets.token_urlsafe(12)}
self.store.save(record)
return self.public(record)
if command in ('start', 'resume', 'retry'):
record = self.store.load(p['transaction'])
if record['status'] == 'completed':
return self.public(record)
current = inspect_package(p.get('path') or self.package_root)
compatible(record['package'], current)
record['package'] = current
# A final confirmation is bound to this already persisted plan.
if command == 'start' and p.get('confirmed') is not True:
raise ValueError('Confirm the displayed plan / 请确认安装计划')
if command != 'start' and record['status'] == 'ready':
raise ValueError('This plan has not been confirmed / 此计划尚未确认')
self.store.save(record)
context = Context(self.store, record, self.emit)
adapter = self.adapter(current, context)
adapter.password = p.get('password', '')
context.cancel = False
record['cancel_requested'] = False
record['error'] = None
self.active = context
self.worker = threading.Thread(target=self.run, args=(context, adapter), daemon=False)
self.worker.start()
return self.public(record)
if command == 'export':
record = self.store.load(p['transaction'])
directory = self.store.directory(record['id'])
# Export path is selected by native dialog, archive paths are fixed.
target = Path(p['path'])
if target.exists():
raise ValueError('Export destination exists / 导出文件已存在')
with zipfile.ZipFile(target, 'w', zipfile.ZIP_DEFLATED) as archive:
for path in directory.rglob('*'):
if path.is_file():
archive.write(path, path.relative_to(directory).as_posix())
return {'path': str(target)}
if command == 'import':
# Import full directories, never extract arbitrary ZIP paths here.
directory = Path(p['path']).resolve()
record = json.loads((directory/'transaction.json').read_text(encoding='utf-8'))
if record.get('version') != 1:
raise ValueError('Unsupported transaction version')
target = self.store.directory(record['id'])
if target.exists():
raise ValueError('Transaction already exists')
if record.get('legacy'):
relative = Path(record['legacy']).relative_to(Path(record.get('data_directory', directory)))
record['legacy'] = str(target/relative)
record['data_directory'] = str(target)
shutil.copytree(directory, target)
self.store.save(record)
return self.public(record)
raise ValueError('Unsupported command / 不支持的命令')
def probe_update(self, p):
import paramiko
if not self.package:
raise ValueError('Verify package first')
choices = p.get('choices', p)
host = choices.get('host', '')
if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9.-]{0,252}', host):
raise ValueError('Enter an IP address or hostname / 请输入 IP 地址或主机名')
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(host, username='root', password=p.get('password', ''), timeout=12,
auth_timeout=15, look_for_keys=False, allow_agent=False)
key = hashlib.sha256(client.get_transport().get_remote_server_key().asbytes()).hexdigest()
def read(script):
_, out, err = client.exec_command(script, timeout=15)
data = out.read().decode('utf-8', 'replace').strip()
if out.channel.recv_exit_status():
raise ValueError('OpenWrt preflight failed / OpenWrt 预检失败')
return data
if read('id -u') != '0':
raise ValueError('SSH root required')
kind = self.package['adapter']
profile = read('cat /etc/e5/device-profile' if kind == 'e5' else 'cat /run/mu300/device')
if kind == 'e5' and profile != self.package['profile'] or kind == 'mu300' and profile not in ('f50', 'v50', 'u30air'):
raise ValueError('Wrong OpenWrt profile / OpenWrt 机型不匹配')
cid = read('cat /sys/class/block/mmcblk0/device/cid')
if not re.fullmatch('[a-f0-9]{32}', cid):
raise ValueError('Cannot establish OpenWrt eMMC identity')
capacity = int(read("df -Pk / | awk 'END {print $2}'"))*1024
import base64
root_dev = read('cat /run/mu300/disk-dev' if kind == 'mu300' else
"readlink -f $(awk '$2==\"/\" {print $1}' /proc/mounts | tail -1)")
if re.fullmatch(r'/dev/(?:block/)?(?:mmcblk\d+(?:p\d+)?|loop\d+)', root_dev):
raw = base64.b64decode(read(f'dd if={root_dev} bs=1024 skip=1 count=1 2>/dev/null | base64'))
capacity = verify_ext4_capacity(raw, 0)
return dict(serial='ssh:'+key, cid=cid, ssh_key=key, host=host, profile=profile,
model=profile.upper(), system='OpenWrt', slot=read('cat /run/mu300/linux-slot') if kind == 'mu300' else 'B',
root=True, readiness='ready', capacity=capacity)
finally:
client.close()
def run(self, context, adapter):
r = context.record
try:
with ExitStack() as locks:
for identity in sorted({r['device']['serial'], r['device']['cid']}):
locks.enter_context(DeviceLock(self.store.base, identity))
if r['stage'] == 'openwrt_boot':
return self.wait_openwrt(context, adapter)
if r.get('legacy'):
self.wait_android(context, adapter)
else:
if r['choices']['method'] != 'update':
actual = adapter.probe(r['device']['serial'], r['choices']['method'])
if actual.get('cid') != r['device']['cid'] or actual.get('slot') != r['device']['slot']:
raise ValueError('Device identity or Android slot changed since plan / 设备或 Android 槽位与计划不一致')
# Recompute immediately before execution; do not accept stale TF geometry or GPT gaps.
fresh = plan_install(r['package'], actual, r['choices'])
for key in ('wipe', 'target', 'openwrt_bytes', 'android_bytes', 'gap_start', 'target_identity'):
if fresh.get(key) != r['plan'].get(key):
raise ValueError('Installation plan changed; inspect and confirm again / 安装计划发生变化,请重新检查并确认: '+key)
context.stage('prepare')
try:
result = adapter.execute()
except Pending:
self.wait_android(context, adapter)
result = adapter.execute()
if result is not None and getattr(result, 'state', '') == 'pending' and r.get('legacy'):
self.wait_android(context, adapter)
result = adapter.execute()
context.stage('openwrt_boot', 'waiting_device', reboot_manually=True)
self.wait_openwrt(context, adapter)
except Cancelled:
context.stage(r['stage'], 'cancelled')
except BaseException as error:
message = str(error)[:2000] if isinstance(error, (ValueError, RecoveryRequired)) else \
'Operation interrupted; keep backups and retry from the saved record / 操作中断,请保留备份并从记录续装'
for private in (r['device'].get('serial'), r['device'].get('cid'), adapter.password,
r.get('secrets', {}).get('wifi_key')):
if private: message = message.replace(private, '[redacted]')
r['error'] = {'code': 'recovery_required' if isinstance(error, RecoveryRequired) else 'operation_failed',
'message': message,
'retryable': not r['unsafe'] or bool(r.get('legacy'))}
context.stage(r['stage'], 'failed')
def wait_android(self, context, adapter):
r = context.record
# No deadline: initialization, debugging and Magisk are user paced.
while True:
context.boundary()
try:
device = adapter.probe(r['device']['serial'], r['choices']['method'])
readiness = device.get('readiness', 'android_boot')
if readiness == 'ready':
if device.get('cid') != r['device']['cid'] or device.get('profile') != r['device']['profile']:
raise RecoveryRequired('Reconnected device differs / 重连设备身份不一致')
if r['plan'].get('two_stage') and r['device'].get('boot_id') and device.get('boot_id') == r['device']['boot_id']:
context.stage('android_boot', 'waiting_device')
if self.stop.wait(3): raise Cancelled()
continue
context.stage('root_ready')
return
context.stage(readiness, 'waiting_device' if readiness == 'android_boot' else 'waiting_user')
except (ConnectionError, OSError, TimeoutError, __import__('subprocess').TimeoutExpired):
context.stage('android_boot', 'waiting_device')
if self.stop.wait(3):
raise Cancelled()
def wait_openwrt(self, context, adapter):
import paramiko
r = context.record
host = r['choices'].get('host') or ('192.168.9.1' if r['package']['adapter'] == 'e5' else
'192.168.78.1' if r['device']['profile'] == 'u30air' else '192.168.77.1')
# No network/interface changes and no automatic hotspot connection.
while True:
context.boundary()
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(host, username='root', password=adapter.password or 'root', timeout=5,
auth_timeout=5, look_for_keys=False, allow_agent=False)
def read(script):
_, out, _ = client.exec_command(script, timeout=15)
value = out.read().decode().strip()
if out.channel.recv_exit_status():
raise ValueError('Final verification command failed')
return value
cid = read('cat /sys/class/block/mmcblk0/device/cid')
if cid != r['device']['cid']:
raise RecoveryRequired('Management address belongs to another device / 管理地址对应另一台设备')
context.stage('verify_capacity')
# Read superblock via SSH base64; no od/SFTP dependency.
import base64
if r['package']['adapter'] == 'e5':
dev = read("readlink -f $(awk '$2==\"/\" {print $1}' /proc/mounts | tail -1)")
else:
dev = read('cat /run/mu300/disk-dev')
if not re.fullmatch(r'/dev/(?:block/)?(?:mmcblk\d+(?:p\d+)?|loop\d+)', dev):
raise ValueError('Cannot identify installed root block device')
raw = base64.b64decode(read(f'dd if={dev} bs=1024 skip=1 count=1 2>/dev/null | base64'))
capacity = verify_ext4_capacity(raw, r['plan']['openwrt_bytes'] if r['plan'].get('grow', True) else 0)
# Mounted and usable, not just a larger partition entry.
read('test -s /etc/openwrt_release && test -x /sbin/init')
r['result'] = {'filesystem_bytes': capacity, 'url': 'http://'+host,
'backup_directory': str(context.directory/'backup'), 'model': r['device']['model'],
'temporary': r['choices']['method'] == 'boot'}
context.stage('complete', 'completed')
return
except (RecoveryRequired, ValueError):
raise
except (OSError, EOFError, paramiko.SSHException):
context.stage('openwrt_boot', 'waiting_device', host=host, reboot_manually=True)
finally:
client.close()
if self.stop.wait(4):
raise Cancelled()
def verify_ext4_capacity(superblock, expected):
import struct
if len(superblock) < 340 or superblock[56:58] != b'\x53\xef':
raise ValueError('Installed filesystem is not ext4 / 已安装文件系统不是 ext4')
blocks = struct.unpack_from('<I', superblock, 4)[0] | (struct.unpack_from('<I', superblock, 336)[0] << 32)
shift = struct.unpack_from('<I', superblock, 24)[0]
if shift > 6:
raise ValueError('Invalid ext4 block size')
capacity = blocks*(1024 << shift)
if capacity <= 0 or expected and not expected-(4 << 20) <= capacity <= expected:
raise ValueError(f'Filesystem capacity differs from allocation / 文件系统容量与分配不符: {capacity} != {expected}')
return capacity
def main():
import argparse
p = argparse.ArgumentParser()
p.add_argument('--package-root', required=True)
p.add_argument('--data-dir')
a = p.parse_args()
output = sys.stdout
service = Service(a.package_root, Store(a.data_dir), output)
# Legacy prints are suppressed at the source; service replies always use
# this captured protocol stream, even while legacy code redirects stdout.
for line in sys.stdin:
if len(line) > 1024*1024:
continue
request = {}
try:
request = json.loads(line)
value = service.dispatch(request)
service.emit('response', {'ok': True, 'result': value}, request.get('id'))
except Exception as error:
service.emit('response', {'ok': False, 'error': str(error)[:2000]}, request.get('id'))
# EOF requests safe cancellation; never kill a storage operation.
if service.active:
service.active.cancel = True
service.stop.set()
if service.worker:
service.worker.join()
if __name__ == '__main__':
main()
+218
View File
@@ -0,0 +1,218 @@
"""Durable state and cross-process device ownership (protocol version 1)."""
from contextlib import contextmanager
import hashlib
import json
import os
from pathlib import Path
import re
import tempfile
import time
import uuid
VERSION = 1
TERMINAL = {'completed', 'cancelled'}
WAITING = {'waiting_device', 'waiting_user'}
def app_directory():
return Path(os.environ.get('LOCALAPPDATA', Path.home() / '.local/share')) / 'OpenWrt-Installer'
def atomic_json(path, value):
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
# Never truncate the last good checkpoint. Flush before atomic replacement.
fd, temp = tempfile.mkstemp(prefix='.checkpoint-', dir=path.parent)
try:
with os.fdopen(fd, 'w', encoding='utf-8', newline='\n') as stream:
json.dump(value, stream, ensure_ascii=False, indent=2)
stream.flush()
os.fsync(stream.fileno())
os.replace(temp, path)
finally:
if os.path.exists(temp):
os.unlink(temp)
def sha(path):
h = hashlib.sha256()
with open(path, 'rb') as stream:
for chunk in iter(lambda: stream.read(1024 * 1024), b''):
h.update(chunk)
return h.hexdigest()
def compatible(old, new):
reasons = []
for key in ('protocol', 'adapter', 'profile', 'layout', 'kernel'):
if old.get(key) != new.get(key):
reasons.append(f'{key}: {old.get(key)} -> {new.get(key)}')
for name in sorted(set(old.get('payloads', {})) | set(new.get('payloads', {}))):
if old.get('payloads', {}).get(name) != new.get('payloads', {}).get(name):
reasons.append('payload changed: ' + name)
if reasons:
raise ValueError('Incompatible package / 安装包不兼容: ' + '; '.join(reasons))
return True
class DeviceLock:
"""Kernel releases ownership after a crash; files are never used as leases."""
def __init__(self, base, identity):
self.path = Path(base) / 'locks' / (hashlib.sha256(identity.encode()).hexdigest() + '.lock')
self.stream = None
def __enter__(self):
self.path.parent.mkdir(parents=True, exist_ok=True)
self.stream = self.path.open('a+b')
self.stream.seek(0)
self.stream.write(b'\0')
self.stream.flush()
self.stream.seek(0)
try:
if os.name == 'nt':
import msvcrt
msvcrt.locking(self.stream.fileno(), msvcrt.LK_NBLCK, 1)
else:
import fcntl
fcntl.flock(self.stream, fcntl.LOCK_EX | fcntl.LOCK_NB)
except OSError:
self.stream.close()
self.stream = None
raise RuntimeError('Another installer owns this device / 另一个安装器正在操作此设备') from None
return self
def __exit__(self, *_):
if self.stream:
if os.name == 'nt':
import msvcrt
self.stream.seek(0)
msvcrt.locking(self.stream.fileno(), msvcrt.LK_UNLCK, 1)
self.stream.close()
class Store:
def __init__(self, base=None):
self.base = Path(base or app_directory())
self.base.mkdir(parents=True, exist_ok=True)
def directory(self, tid):
if not re.fullmatch('[a-f0-9]{32}', tid):
raise ValueError('Invalid transaction ID')
return self.base / 'transactions' / tid
def save(self, record):
record['updated'] = time.time()
atomic_json(self.directory(record['id']) / 'transaction.json', record)
def load(self, tid):
record = json.loads((self.directory(tid) / 'transaction.json').read_text(encoding='utf-8'))
if record.get('version') != VERSION or record.get('id') != tid:
raise ValueError('Unsupported or damaged transaction / 事务版本不支持或记录损坏')
return record
def list(self):
records = []
for path in (self.base / 'transactions').glob('*/transaction.json'):
try:
records.append(self.load(path.parent.name))
except (OSError, ValueError):
continue
return sorted(records, key=lambda r: r['updated'], reverse=True)
def create(self, package, device, choices, plan):
record = dict(version=VERSION, id=uuid.uuid4().hex, created=time.time(),
status='ready', stage='plan', device=device, package=package,
choices=choices, plan=plan, completed=[], effects={}, legacy=None,
unsafe=False, cancel_requested=False, error=None, result=None)
self.save(record)
return record
class RecoveryRequired(RuntimeError):
pass
class Cancelled(Exception):
pass
class Pending(Exception):
"""Expected device reboot; this is never a failure."""
class Context:
def __init__(self, store, record, emit):
self.store, self.record, self.emit = store, record, emit
self.cancel = False
self.clock = time.monotonic()
@property
def directory(self):
return self.store.directory(self.record['id'])
def snapshot(self):
# Transaction/backup files retain identity; public events mask it.
out = json.loads(json.dumps(self.record))
def redact(value):
if isinstance(value, dict):
for key, item in value.items():
if key.lower() in ('serial', 'cid', 'ssh_key') and isinstance(item, str):
value[key] = '••••' + item[-4:]
else:
redact(item)
elif isinstance(value, list):
for item in value: redact(item)
redact(out)
out.pop('legacy', None)
out.pop('effects', None)
out.pop('secrets', None)
self.emit('transaction', out)
return out
def stage(self, stage, status='running', **details):
self.record.update(stage=stage, status=status, details=details)
self.store.save(self.record)
self.snapshot()
def boundary(self):
if self.cancel or self.record.get('cancel_requested'):
raise Cancelled()
def effect(self, name, operation, *, retry_safe=False):
entry = self.record['effects'].get(name)
if entry and entry['state'] == 'done':
return entry.get('result')
if entry and not retry_safe:
raise RecoveryRequired('Interrupted write requires readback / 写入中断,必须复核: ' + name)
self.boundary()
self.record['effects'][name] = {'state': 'started', 'time': time.time()}
self.record['unsafe'] = not retry_safe
self.store.save(self.record)
self.snapshot()
result = operation()
self.record['effects'][name] = {'state': 'done', 'time': time.time(), 'result': result}
self.record['unsafe'] = False
if name not in self.record['completed']:
self.record['completed'].append(name)
self.store.save(self.record)
self.snapshot()
self.boundary()
return result
def legacy_record(self, path, value):
self.record['legacy'] = str(Path(path).resolve())
self.record['legacy_phase'] = value.get('phase', value.get('state'))
self.store.save(self.record)
def transfer(self, name, done, total, since):
self.emit('transfer', dict(name=name, bytes=done, total=total,
bytes_per_second=done / max(time.monotonic() - since, .001)))
def log(self, message):
# Legacy stdout can contain hotspot credentials, SMS or raw identifiers.
# It is intentionally not forwarded. Only named structured events log.
safe = str(message)
for value in (self.record['device'].get('serial'), self.record['device'].get('cid')):
if value:
safe = safe.replace(value, '[redacted]')
self.emit('log', {'time': time.time(), 'message': safe[:2000]})
+104
View File
@@ -0,0 +1,104 @@
"""Serial-bound ADB operations. Frontend never supplies shell text."""
import base64
import os
from pathlib import Path
import re
import shlex
import shutil
import subprocess
import time
from .state import sha
def hidden_process():
return {'creationflags': subprocess.CREATE_NO_WINDOW} if os.name == 'nt' else {}
class Adb:
def __init__(self, package, serial=None):
self.serial = serial
paths = [Path(package) / 'tools/adb.exe', Path(package) / 'platform-tools/adb.exe']
self.exe = next((str(p) for p in paths if p.is_file()), shutil.which('adb'))
if not self.exe:
raise ValueError('ADB is missing from tools / 安装包缺少 ADB 工具')
self.su = None
def call(self, *args, timeout=20, check=True):
cmd = [self.exe]
if self.serial and args[0] != 'devices':
cmd += ['-s', self.serial]
result = subprocess.run(cmd + list(args), capture_output=True, timeout=timeout, **hidden_process())
if check and result.returncode:
raise ConnectionError('ADB connection interrupted / ADB 连接中断')
return result.stdout.decode('utf-8', 'replace').replace('\r', '')
def devices(self):
result = []
for line in self.call('devices', '-l').splitlines()[1:]:
values = line.split()
if len(values) >= 2:
result.append({'serial': values[0], 'state': values[1],
'label': next((v[6:] for v in values[2:] if v.startswith('model:')), values[0][-4:])})
return result
def shell(self, script, root=False, timeout=20):
if root and self.su is None:
raise ValueError('Root has not been verified / 尚未验证 root')
command = (self.su + ' -c ' if root and self.su else 'sh -c ') + shlex.quote(script)
return self.call('shell', command, timeout=timeout)
def root_status(self):
if self.shell('id -u').strip() == '0':
self.su = ''
return 'ready'
found = False
for name in ('su', '/debug_ramdisk/su', '/sbin/su'):
available = self.shell('command -v ' + name + ' >/dev/null 2>&1; echo $?').strip() == '0'
if not available:
continue
found = True
try:
result = self.shell(name + ' -c id', timeout=8)
if re.search(r'\buid=0\b', result):
self.su = name
return 'ready'
except (ConnectionError, subprocess.TimeoutExpired):
pass
return 'root_permission' if found else 'magisk'
def read(self, script):
encoded = self.shell('set -o pipefail; ' + script + ' | base64', root=True, timeout=120)
return base64.b64decode(''.join(encoded.split()), validate=True)
def properties(self):
names = ('ro.product.model', 'ro.product.device', 'ro.board.platform', 'ro.boot.slot_suffix',
'ro.boot.verifiedbootstate', 'ro.crypto.state', 'ro.crypto.type', 'sys.boot_completed')
result = {}
for name in names:
result[name] = self.shell('getprop ' + name).strip()
return result
def push_chunks(adb_call, shell, local, remote, context):
"""Actual acknowledged bytes, checksum at destination, no terminal parsing."""
import tempfile
total = Path(local).stat().st_size
since = time.monotonic()
shell('rm -f ' + shlex.quote(remote))
done = 0
with open(local, 'rb') as stream, tempfile.TemporaryDirectory() as temp:
chunk_path = Path(temp) / 'chunk'
while chunk := stream.read(8 << 20):
context.boundary()
chunk_path.write_bytes(chunk)
part = remote + '.upload-chunk'
adb_call('push', str(chunk_path), part)
if shell('sha256sum ' + shlex.quote(part)).split()[0] != sha(chunk_path):
raise ValueError('Transfer chunk checksum failed / 传输块校验失败')
shell('cat ' + shlex.quote(part) + ' >> ' + shlex.quote(remote) + ' && rm -f ' + shlex.quote(part))
done += len(chunk)
context.transfer(Path(local).name, done, total, since)
if shell('sha256sum ' + shlex.quote(remote)).split()[0] != sha(local):
raise ValueError('Transfer checksum failed / 传输校验失败')
return remote
+32
View File
@@ -0,0 +1,32 @@
"""Frozen NDJSON entry; no console window is created by the Tauri host."""
import argparse
from pathlib import Path
import runpy
import sys
from backend.service import main
for stream in (sys.stdin, sys.stdout, sys.stderr):
if stream is not None and hasattr(stream, 'reconfigure'):
stream.reconfigure(encoding='utf-8', errors='replace')
if __name__ == '__main__':
if len(sys.argv) > 2 and sys.argv[1] == '--run-tool':
tool = sys.argv[2]
sys.argv = [tool, *sys.argv[3:]]
runpy.run_path(tool, run_name='__main__')
elif '--cli' in sys.argv:
from backend.adapter import load
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('--cli', action='store_true')
parser.add_argument('--package-root', type=Path, required=True)
options, remaining = parser.parse_known_args()
root = options.package_root.resolve()
module = load(root/'OpenWrt-Installer.py', '_compat_cli')
if (root/'desktop/manifest.json').is_file():
module.package_root = lambda: root
sys.exit(module.run_cli(remaining))
module.B, module.F, module.SCRIPTS = str(root), str(root/'files'), str(root/'scripts')
sys.argv = ['OpenWrt-Installer.py', *remaining]
sys.exit(module.run_cli())
else:
main()
+75
View File
@@ -0,0 +1,75 @@
"""Build the portable Tauri release and bundled Python backend on Windows."""
import argparse
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import urllib.request
import zipfile
from package_gui import sources, digest
HERE = Path(__file__).resolve().parent
def run(*args, cwd=HERE):
subprocess.run(list(map(str,args)),cwd=cwd,check=True)
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('--skip-ui', action='store_true')
p.add_argument('--adb-dir', type=Path, help='optional pre-fetched platform-tools directory')
a = p.parse_args()
if os.name != 'nt':
raise SystemExit('Build Windows binaries on Windows (MSVC, Rust 1.90, Node and Python are build dependencies only).')
if not a.skip_ui:
run('npm.cmd','ci','--no-audit','--no-fund','--registry=https://registry.npmjs.org',cwd=HERE/'ui')
run('npm.cmd','run','tauri','--','build','--no-bundle',cwd=HERE/'ui')
before = sources()
work = HERE.parent/'work/installer-backend'
run(sys.executable,'-m','PyInstaller','--noconfirm','--clean','--noupx','--optimize','2','--onedir','--console',
'--name','openwrt-backend','--distpath',work/'dist','--workpath',work/'build','--specpath',work,
'--hidden-import','lz4.block','--hidden-import','xml.etree.ElementTree','--hidden-import','xml.parsers.expat',
'--hidden-import','tarfile','--hidden-import','gzip','--hidden-import','zlib','--hidden-import','lzma',
'--hidden-import','bz2','--hidden-import','http.server','--hidden-import','decimal',
'--collect-all','paramiko',HERE/'backend_entry.py')
artifact = HERE/'artifacts/windows'
artifact.mkdir(parents=True,exist_ok=True)
tools = artifact/'tools'
tools.mkdir(exist_ok=True)
names = ('adb.exe','AdbWinApi.dll','AdbWinUsbApi.dll','NOTICE.txt')
if a.adb_dir:
for name in names:
shutil.copy2(a.adb_dir/name, tools/('ADB-NOTICE.txt' if name=='NOTICE.txt' else name))
else:
dependency = json.loads((HERE/'platform-tools.json').read_text())
cache = HERE.parent/'work/installer-platform-tools/platform-tools-pinned.zip'
cache.parent.mkdir(parents=True,exist_ok=True)
if not cache.is_file() or digest(cache) != dependency['sha256']:
urllib.request.urlretrieve(dependency['url'],cache)
if digest(cache) != dependency['sha256']:
raise ValueError('Platform-tools download checksum mismatch')
with zipfile.ZipFile(cache) as archive:
for name in names:
(tools/('ADB-NOTICE.txt' if name=='NOTICE.txt' else name)).write_bytes(archive.read('platform-tools/'+name))
shutil.copy2(HERE/'ui/src-tauri/target/release/openwrt-installer.exe',artifact/'OpenWrt-Installer.exe')
destination = artifact/'tools/backend'
# Use a clean build directory so removed dependencies cannot survive a rebuild.
if destination.exists():
resolved = destination.resolve()
if not resolved.is_relative_to(artifact.resolve()): raise ValueError('Invalid artifact target')
shutil.rmtree(resolved)
shutil.copytree(work/'dist/openwrt-backend',destination)
subprocess.run([str(tools/'adb.exe'),'version'],check=True,stdout=subprocess.DEVNULL)
if sources() != before:
raise ValueError('Source changed during compilation; rebuild before packaging')
files = {p.relative_to(artifact).as_posix():digest(p) for p in artifact.rglob('*') if p.is_file() and p.name!='build.json'}
(artifact/'build.json').write_text(json.dumps({'protocol':1,'source':before,'files':files},indent=2)+'\n',encoding='utf-8')
print(artifact)
if __name__ == '__main__':
main()
+76
View File
@@ -0,0 +1,76 @@
"""Attach a fingerprinted portable desktop build to an existing package."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import shutil
import zipfile
HERE = Path(__file__).resolve().parent
def digest(path):
h = hashlib.sha256()
with open(path, 'rb') as stream:
for chunk in iter(lambda: stream.read(1 << 20), b''): h.update(chunk)
return h.hexdigest()
def sources():
paths = [HERE/'backend_entry.py', HERE/'package_gui.py', HERE/'platform-tools.json', HERE/'GUIDE.md']
paths += list((HERE/'backend').glob('*.py'))
paths += [p for p in (HERE/'ui/src').rglob('*') if p.is_file()]
paths += [HERE/'ui'/n for n in ('package.json','package-lock.json','vite.config.ts','tailwind.config.js','postcss.config.js','tsconfig.json','index.html','rust-toolchain.toml')]
paths += [HERE/'ui/src-tauri'/n for n in ('Cargo.toml','Cargo.lock','build.rs','tauri.conf.json','src/main.rs','capabilities/default.json','icons/icon.ico')]
return {p.relative_to(HERE).as_posix(): digest(p) for p in sorted(paths)}
def attach(package, artifact=None, required=True):
package = Path(package)
artifact = Path(artifact or os.environ.get('OPENWRT_GUI_ARTIFACT', HERE/'artifacts/windows'))
metadata = artifact/'build.json'
if not metadata.is_file():
if required:
raise ValueError('Portable GUI build missing; run python installer/build.py or set OPENWRT_GUI_ARTIFACT')
return False
build = json.loads(metadata.read_text())
if build['source'] != sources():
raise ValueError('Portable GUI build is stale; rebuild installer/build.py')
for name, wanted in build['files'].items():
path = (artifact/name).resolve()
if not path.is_relative_to(artifact.resolve()) or digest(path) != wanted:
raise ValueError('Portable build checksum mismatch: '+name)
shutil.copy2(artifact/'OpenWrt-Installer.exe', package/'OpenWrt-Installer.exe')
shutil.copytree(artifact/'tools', package/'tools', dirs_exist_ok=True)
docs = package/'docs'
docs.mkdir(exist_ok=True)
shutil.copy2(HERE/'GUIDE.md', docs/'GUI-GUIDE.md')
shutil.copy2(HERE/'PROTOCOL.md', docs/'INSTALLER-PROTOCOL.md')
shutil.copy2(HERE/'README.md', docs/'GUI-BUILD.md')
shutil.copy2(HERE/'VERIFICATION.md', docs/'GUI-VERIFICATION.md')
if (HERE/'screenshots').is_dir():
shutil.copytree(HERE/'screenshots', docs/'screenshots', dirs_exist_ok=True)
(package/'START-HERE.md').write_text((HERE/'GUIDE.md').read_text(encoding='utf-8'),encoding='utf-8',newline='\n')
shutil.copy2(metadata, docs/'GUI-BUILD.json')
return True
def size_report(package, archive=None):
package = Path(package)
gui = package/'OpenWrt-Installer.exe'
tools = sum(p.stat().st_size for name in ('tools','scripts','desktop') for p in (package/name).rglob('*') if p.is_file())
payload_roots = [package/'payload'] if (package/'payload').is_dir() else [package/'files']
payload = sum(p.stat().st_size for root in payload_roots for p in root.rglob('*') if p.is_file())
return {'gui_bytes':gui.stat().st_size if gui.is_file() else 0, 'backend_and_tools_bytes':tools,
'firmware_payload_bytes':payload, 'archive_bytes':Path(archive).stat().st_size if archive else None}
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('package', type=Path)
parser.add_argument('--artifact', type=Path)
parser.add_argument('--archive', type=Path)
a = parser.parse_args()
attach(a.package,a.artifact)
print(json.dumps(size_report(a.package,a.archive),indent=2))
+5
View File
@@ -0,0 +1,5 @@
{
"version": "37.0.1",
"url": "https://dl.google.com/android/repository/platform-tools_r37.0.1-win.zip",
"sha256": "45f4d63113e895ebde0c90f194099a4676b6ac653bd28d54314a9e022bbc1a99"
}
+85
View File
@@ -0,0 +1,85 @@
"""Create a new GUI distribution from an existing validated firmware package."""
import argparse
import json
import os
from pathlib import Path
import runpy
import shutil
import zipfile
from backend.package import inspect_package
from package_gui import attach, digest, size_report
TOP=Path(__file__).resolve().parents[1]
def refresh(package):
package=Path(package)
if (package/'desktop/manifest.json').is_file():
shutil.copy2(TOP/'desktop/installer.py',package/'OpenWrt-Installer.py')
shutil.copy2(TOP/'desktop/installer.py',package/'desktop/installer.py')
for name in ('android-write-part.sh','android-write-free.sh'):
shutil.copy2(TOP/'desktop'/name,package/'desktop'/name)
attach(package)
manifest_path=package/'desktop/manifest.json'
manifest=json.loads(manifest_path.read_text())
manifest['source']={name:digest(TOP/'desktop'/name) for name in ('installer.py','boot_image.py')}
manifest['desktop']={p.relative_to(package).as_posix():digest(p) for p in package.rglob('*')
if p.is_file() and p!=manifest_path and p.relative_to(package).as_posix() not in manifest['magisk']}
manifest_path.write_text(json.dumps(manifest,indent=2)+'\n',encoding='utf-8',newline='\n')
# Existing CLI shortcuts must use the bundled CLI interpreter, not the GUI.
for cmd in (package/'launchers').glob('*.cmd'):
s=cmd.read_text(encoding='utf-8')
s=s.replace('if exist "OpenWrt-Installer.exe" (','if exist "tools\\backend\\openwrt-backend.exe" (').replace(' "OpenWrt-Installer.exe" ',' "tools\\backend\\openwrt-backend.exe" --cli --package-root "%cd%" ')
cmd.write_bytes(s.replace('\r\n','\n').replace('\n','\r\n').encode('utf-8'))
# Launchers changed after attachment, so include their final bytes.
manifest['desktop'].update({p.relative_to(package).as_posix():digest(p) for p in (package/'launchers').glob('*.cmd')})
manifest_path.write_text(json.dumps(manifest,indent=2)+'\n',encoding='utf-8',newline='\n')
else:
runpy.run_path(str(TOP/'openwrt/bundle/install-entrypoints.py'))['assemble'](package)
shutil.copy2(TOP/'tools/e5-update.py',package/'scripts/tools/e5-update.py')
sums=package/'files/SHA256SUMS'
sums.write_text(''.join(digest(p)+' '+p.relative_to(package).as_posix()+'\n' for p in sorted(package.rglob('*')) if p.is_file() and p!=sums and '__pycache__' not in p.parts),encoding='utf-8',newline='\n')
def archive(package, target):
if target.exists(): raise ValueError('Archive exists; choose a new release path')
partial=target.with_suffix('.zip.partial')
with zipfile.ZipFile(partial,'w',zipfile.ZIP_DEFLATED,compresslevel=6) as z:
for p in sorted(package.rglob('*')):
if p.is_file() and '__pycache__' not in p.parts:
z.write(p,p.relative_to(package).as_posix(),compress_type=zipfile.ZIP_STORED if p.suffix=='.gz' else zipfile.ZIP_DEFLATED)
with zipfile.ZipFile(partial) as z:
bad=z.testzip()
if bad:raise ValueError('ZIP CRC failure: '+bad)
roots=[n for n in z.namelist() if n.endswith(('openwrt.ext4.gz','mu300-openwrt.tar.gz'))]
if len(roots)!=1:raise ValueError('Expected exactly one system payload')
partial.replace(target)
def main():
p=argparse.ArgumentParser(description=__doc__)
p.add_argument('source',type=Path);p.add_argument('destination',type=Path)
p.add_argument('--no-zip',action='store_true');p.add_argument('--zip-only',action='store_true')
a=p.parse_args()
if a.zip_only:
package=a.source.resolve();target=a.destination.resolve();archive(package,target)
else:
if a.destination.exists():raise ValueError('Destination exists; never overwrite an existing release')
before=inspect_package(a.source)
shutil.copytree(a.source,a.destination,ignore=shutil.ignore_patterns('__pycache__'))
package=a.destination.resolve();refresh(package)
after=inspect_package(package)
if before['payloads']!=after['payloads']:raise ValueError('Device firmware payload changed')
target=package.with_suffix('.zip')
if a.no_zip:
print(package);return
archive(package,target)
report=size_report(package,target)
report['package']=str(package);report['sha256']=digest(target)
target.with_suffix('.size.json').write_text(json.dumps(report,indent=2)+'\n',encoding='utf-8')
target.with_suffix('.zip.sha256').write_text(report['sha256']+' '+target.name+'\n',encoding='utf-8')
print(json.dumps(report,indent=2))
if __name__=='__main__':main()
+3
View File
@@ -0,0 +1,3 @@
PyInstaller==6.20.0
paramiko==4.0.0
lz4==4.4.5
Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 121 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 71 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 67 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

+29
View File
@@ -0,0 +1,29 @@
"""Update the MU300 vendored shared installer in one direction, with hashes."""
import argparse
import hashlib
import json
from pathlib import Path
import shutil
HERE = Path(__file__).resolve().parent
EXCLUDE = {'node_modules','dist','target','artifacts','__pycache__','.git','tsconfig.tsbuildinfo'}
def main():
p=argparse.ArgumentParser(description=__doc__)
p.add_argument('repository',type=Path)
p.add_argument('--check',action='store_true')
a=p.parse_args(); destination=a.repository.resolve()/'installer'
files={p.relative_to(HERE).as_posix():p for p in HERE.rglob('*') if p.is_file() and not any(x in EXCLUDE for x in p.relative_to(HERE).parts) and p.name!='SHARED-SOURCE.json'}
hashes={name:hashlib.sha256(path.read_bytes()).hexdigest() for name,path in files.items()}
if a.check:
if any(not (destination/name).is_file() or hashlib.sha256((destination/name).read_bytes()).hexdigest()!=h for name,h in hashes.items()):
raise SystemExit('Shared installer differs; run installer/sync.py without --check')
else:
for name,path in files.items():
target=destination/name;target.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(path,target)
(destination/'SHARED-SOURCE.json').write_text(json.dumps({'source':'e5-linux/installer','policy':'Generated mirror. Edit upstream then run sync.py; do not fork UI/protocol.','sha256':hashes},indent=2)+'\n')
print('Shared installer synchronized:',len(files))
if __name__=='__main__':main()
+116
View File
@@ -0,0 +1,116 @@
"""Offline onboarding/help integration checks against the production UI bundle."""
from playwright.sync_api import sync_playwright
from ui_smoke import BRIDGE, ROOT, layout, settle
def bounded_dialog(page):
box=page.get_by_role('dialog').bounding_box()
assert box and box['x']>=0 and box['y']>=0,box
viewport=page.viewport_size
assert box['x']+box['width']<=viewport['width']+.5,box
assert box['y']+box['height']<=viewport['height']+.5,box
assert page.evaluate('scrollY')==0
for _ in range(15):
page.keyboard.press('Tab')
assert page.evaluate("document.querySelector('[role=dialog]').contains(document.activeElement)")
def main():
with sync_playwright() as p:
browser=p.chromium.launch()
context=browser.new_context(viewport={'width':1120,'height':900})
context.add_init_script(BRIDGE)
page=context.new_page();errors=[];remote=[]
page.on('pageerror',lambda error:errors.append(str(error)))
page.on('request',lambda request:remote.append(request.url) if not request.url.startswith('http://127.0.0.1:1420/') else None)
page.goto('http://127.0.0.1:1420')
dialog=page.get_by_role('dialog',name='新手引导')
dialog.wait_for();settle(page);bounded_dialog(page)
assert set(page.evaluate('window.__fixture.requests'))=={'hello'}
page.screenshot(path=str(ROOT/'screenshots/onboarding-light-zh.png'))
dialog.get_by_role('button',name='下一步',exact=True).click();settle(page)
dialog.get_by_role('heading',name='选择适合你的安装方式').wait_for()
dialog.get_by_role('button',name='下一步',exact=True).click();settle(page)
dialog.get_by_text('电脑记录和备份都丢失时',exact=False).wait_for()
dialog.get_by_role('button',name='上一步',exact=True).click();settle(page)
dialog.get_by_role('button',name='下一步',exact=True).click();settle(page)
dialog.get_by_role('button',name='开始使用',exact=True).click()
assert page.evaluate("localStorage.getItem('onboarding-v1')")=='seen'
page.reload();settle(page)
assert page.get_by_role('dialog').count()==0
page.get_by_role('button',name='帮助与使用指南',exact=True).click()
dialog=page.get_by_role('dialog',name='帮助与使用指南');dialog.wait_for();settle(page)
bounded_dialog(page)
dialog.get_by_role('textbox',name='搜索使用指南').fill('没有任何匹配xyz')
dialog.get_by_text('没有找到相关内容',exact=False).wait_for()
dialog.get_by_role('textbox',name='搜索使用指南').fill('Magisk')
assert dialog.locator('.help-topics button').count()>=1
dialog.get_by_role('textbox',name='搜索使用指南').fill('')
dialog.get_by_role('button',name='连接与常见问题',exact=True).click()
dialog.get_by_text('电脑记录和导出备份都丢失时',exact=False).wait_for()
assert dialog.locator('article').evaluate('(el)=>el.scrollHeight>el.clientHeight')
dialog.locator('article').evaluate('(el)=>el.scrollTop=el.scrollHeight')
page.screenshot(path=str(ROOT/'screenshots/help-recovery-light-zh.png'))
page.keyboard.press('Escape');settle(page)
assert page.get_by_role('dialog').count()==0
assert page.get_by_role('button',name='帮助与使用指南',exact=True).evaluate('(el)=>el===document.activeElement')
page.keyboard.press('F1');page.get_by_role('dialog').wait_for()
page.get_by_role('button',name='重新查看新手引导',exact=True).click()
page.get_by_role('dialog',name='新手引导').wait_for()
page.get_by_role('button',name='暂时跳过',exact=True).click();settle(page)
# Help is available during a real coordinator-shaped wait without touching the task.
page.get_by_role('button',name='安装 OpenWrt',exact=False).click()
page.get_by_role('button',name='校验安装包',exact=True).click()
page.get_by_role('button',name='刷新设备',exact=True).click()
page.get_by_label('请选择设备').select_option('fixture-1234')
page.get_by_role('button',name='检查设备',exact=True).click()
page.get_by_role('button',name='查看安装计划',exact=True).click()
page.get_by_role('button',name='确认并开始',exact=True).wait_for();settle(page)
page.get_by_role('checkbox').check()
page.get_by_role('button',name='确认并开始',exact=True).click()
page.get_by_role('heading',name='请完成 Android 初始设置',exact=True).first.wait_for()
before=page.evaluate('window.__fixture.requests.length')
page.get_by_role('button',name='查看当前步骤帮助',exact=True).click()
dialog=page.get_by_role('dialog',name='帮助与使用指南');dialog.wait_for();settle(page)
assert dialog.locator('[aria-current=page]').inner_text()=='Android 重置后续装'
assert page.evaluate('window.__fixture.requests.length')==before
page.keyboard.press('Escape');settle(page)
assert page.evaluate("window.__fixture.tx.status")=='waiting_user'
assert page.get_by_role('button',name='查看当前步骤帮助',exact=True).evaluate('(el)=>el===document.activeElement')
page.get_by_label('语言').select_option('en')
page.get_by_label('Theme').select_option('dark')
page.set_viewport_size({'width':800,'height':650})
page.emulate_media(reduced_motion='reduce')
page.keyboard.press('F1')
dialog=page.get_by_role('dialog',name='Help and user guide');dialog.wait_for();settle(page)
bounded_dialog(page)
dialog.get_by_role('button',name='Connection and troubleshooting',exact=True).click()
dialog.get_by_text('this version cannot reconstruct a record from the device alone',exact=False).wait_for()
page.evaluate("window.__emitFixture({stage:'root_permission',status:'waiting_user'})");settle(page)
assert page.evaluate("!!document.elementFromPoint(600,120).closest('[role=dialog]')"), 'Toast obscures help'
page.screenshot(path=str(ROOT/'screenshots/help-small-dark-en.png'))
dialog.get_by_role('button',name='Replay getting started',exact=True).click()
dialog=page.get_by_role('dialog',name='Getting started');dialog.wait_for();settle(page)
bounded_dialog(page)
page.screenshot(path=str(ROOT/'screenshots/onboarding-small-dark-en.png'))
page.keyboard.press('Escape');settle(page);layout(page)
assert not errors,errors
assert not remote,remote
# A saved transaction suppresses automatic onboarding even on a fresh computer profile.
second=browser.new_context(viewport={'width':800,'height':650})
second.add_init_script(BRIDGE+'window.__fixture.saved=[window.__fixture.tx];')
saved=second.new_page();saved.goto('http://127.0.0.1:1420');settle(saved)
assert saved.get_by_role('dialog').count()==0
assert set(saved.evaluate('window.__fixture.requests'))=={'hello'}
third=browser.new_context(viewport={'width':800,'height':650})
third.add_init_script(BRIDGE)
skipped=third.new_page();skipped.goto('http://127.0.0.1:1420')
skipped.get_by_role('dialog',name='新手引导').wait_for()
skipped.get_by_role('button',name='暂时跳过',exact=True).click()
skipped.reload();settle(skipped)
assert skipped.get_by_role('dialog').count()==0
print('Help smoke passed: first launch/replay/skip/persistence, saved-record suppression, offline search/manual, focus trapping/restore/Escape/F1, contextual help without backend operations, languages/themes and bounded 800x650 dialogs')
browser.close()
if __name__=='__main__':main()
+47
View File
@@ -0,0 +1,47 @@
"""Verify actual Windows distributions without connecting to any device."""
import argparse
import json
from pathlib import Path
import subprocess
import tempfile
def check(package):
package=Path(package).resolve()
backend=package/'tools/backend/openwrt-backend.exe'
mu=(package/'desktop/manifest.json').is_file()
row={'package':package.name,'commands':{}}
for flag in (['--check','--check-boot'] if mu else ['--verify-package']):
result=subprocess.run([str(backend),'--cli','--package-root',str(package),flag,'--no-pause'],capture_output=True,timeout=180)
row['commands'][flag]={'exit':result.returncode,'stdout':result.stdout.decode('utf-8')[-1500:],
'stderr':result.stderr.decode('utf-8')[-1000:]}
if result.returncode:raise RuntimeError(row['commands'][flag])
with tempfile.TemporaryDirectory(prefix='openwrt-smoke-') as directory:
requests=''.join(json.dumps({'protocol':1,'id':i,'command':command,'params':{}})+'\n'
for i,command in enumerate(['hello','package','list','probe']))
result=subprocess.run([str(backend),'--package-root',str(package),'--data-dir',directory],
input=requests.encode('utf-8'),capture_output=True,timeout=180)
events=[json.loads(line) for line in result.stdout.decode('utf-8').splitlines()]
row['protocol_ok']=result.returncode==0 and len(events)==4 and all(e['data']['ok'] for e in events[:3]) and not events[3]['data']['ok']
# The intentional missing-serial error exercises Chinese UTF-8 over the
# real frozen protocol, without issuing even a device probe.
row['utf8_error']=events[-1]['data'].get('error') if events else None
if not row['protocol_ok']:raise RuntimeError(events)
adb=subprocess.run([str(package/'tools/adb.exe'),'version'],capture_output=True,timeout=20)
if adb.returncode:raise RuntimeError('Bundled ADB cannot start')
row['adb_version']=adb.stdout.decode('utf-8')
return row
if __name__=='__main__':
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('packages',type=Path,nargs='+')
parser.add_argument('--report',type=Path)
options=parser.parse_args()
results=[]
for package in options.packages:
results.append(check(package))
print(package.name+': PASS',flush=True)
if options.report:
options.report.parent.mkdir(parents=True,exist_ok=True)
options.report.write_text(json.dumps(results,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
+53
View File
@@ -0,0 +1,53 @@
"""CLI device selection uses simulated ADB; no connected device is accessed."""
from contextlib import ExitStack, redirect_stdout
import importlib.util
import io
from pathlib import Path
import sys
from types import SimpleNamespace
import unittest
from unittest.mock import patch
TOP=Path(__file__).resolve().parents[2]
SOURCE=TOP/'openwrt/bundle/flash.py'
E5=SOURCE.is_file()
if not E5:SOURCE=TOP/'desktop/installer.py'
class LegacyBinding(unittest.TestCase):
def run_selection(self, explicit):
spec=importlib.util.spec_from_file_location('selection_fixture',SOURCE)
module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module)
with ExitStack() as stack:
stack.enter_context(redirect_stdout(io.StringIO()))
stack.enter_context(patch.object(sys.stdin,'isatty',return_value=True))
stack.enter_context(patch('builtins.input',return_value='2'))
listing='List of devices attached\nfirst\tdevice\nsecond\tdevice\n'
if E5:
module.SERIAL='second' if explicit else None
stack.enter_context(patch.object(module,'adb',return_value=listing))
stack.enter_context(patch.object(module,'ask',return_value='2'))
stack.enter_context(patch.object(module,'package_profile',return_value={'profile':'e5','android_models':['E5']}))
stack.enter_context(patch.object(module,'su',return_value='ok'))
stack.enter_context(patch.object(module,'su_checked',return_value=''))
def shell(cmd):
if cmd.endswith('-c id'):return 'uid=0(root)'
return {'getprop ro.product.model':'E5','getprop ro.boot.slot_suffix':'_a',
'getprop ro.boot.verifiedbootstate':'orange'}.get(cmd,'')
stack.enter_context(patch.object(module,'sh',side_effect=shell))
module.android_checks()
self.assertEqual(module.SERIAL,'second')
else:
stack.enter_context(patch.object(module.Android,'call',return_value=listing.encode()))
def shell(_,cmd,**kwargs):
return {'id -u':'0','getprop ro.product.model; getprop ro.product.device':'MU300\nF50',
'getprop ro.board.platform':'ums9620','getprop ro.boot.slot_suffix':'_a'}[cmd]
stack.enter_context(patch.object(module.Android,'shell',shell))
device=module.Android(SimpleNamespace(adb='fake-adb',serial='second' if explicit else None,probe=True))
self.assertEqual(device.serial,'second')
def test_explicit_serial_among_multiple_devices(self):self.run_selection(True)
def test_interactive_selection_among_multiple_devices(self):self.run_selection(False)
if __name__=='__main__':unittest.main()
+144
View File
@@ -0,0 +1,144 @@
"""Exercise the coordinator with real journals and simulated transport/files."""
import io
import json
from pathlib import Path
import struct
import sys
import tempfile
import unittest
from types import SimpleNamespace
from unittest.mock import patch
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
from backend.service import Service, plan_install, verify_ext4_capacity
from backend.state import Context, Pending, Store
from backend.adapter import Adapter, args_for
from test_state import DEVICE, PACKAGE
class Recovery(unittest.TestCase):
def setUp(self):
self.temp=tempfile.TemporaryDirectory()
self.store=Store(self.temp.name)
self.output=io.StringIO()
self.service=Service('.',self.store,self.output)
self.record=self.store.create(PACKAGE,{**DEVICE,'boot_id':'old'}, {'method':'part','size_gib':4}, plan_install(PACKAGE,DEVICE,{'method':'part','size_gib':4}))
self.ctx=Context(self.store,self.record,self.service.emit)
self.prepare_calls=0;self.write_calls=0
def tearDown(self):self.temp.cleanup()
def fake_adapter(self):
owner=self
context=self.ctx
class Adapter:
password=''
reads=0
def probe(self,*_):
self.reads+=1
if owner.record.get('legacy'):
stages=['android_boot','android_setup','debug_authorization','root_permission','ready']
ready=stages[min(self.reads-2,len(stages)-1)]
return {**DEVICE,'boot_id':'new','readiness':ready}
return {**DEVICE,'boot_id':'old'}
def execute(self):
if not owner.record.get('legacy'):
owner.prepare_calls+=1
path=context.directory/'legacy.json'
path.write_text(json.dumps({'token':'trusted','phase':'awaiting-android'}))
context.legacy_record(path,{'phase':'awaiting-android'})
context.stage('android_boot','waiting_device')
raise Pending()
def install():
owner.write_calls+=1
# Disposable file stands in for the grown ext4 superblock.
raw=bytearray(1024);raw[56:58]=b'\x53\xef'
struct.pack_into('<I',raw,24,2);struct.pack_into('<I',raw,4,(4<<30)//4096)
(context.directory/'root.superblock').write_bytes(raw)
context.effect('root-write',install)
return SimpleNamespace(state='success')
return Adapter()
def final_verify(self,ctx,adapter):
raw=(ctx.directory/'root.superblock').read_bytes()
measured=verify_ext4_capacity(raw,ctx.record['plan']['openwrt_bytes'])
ctx.record['result']={'filesystem_bytes':measured}
ctx.stage('complete','completed')
def test_expected_reboot_authorization_then_automatic_resume(self):
with patch.object(self.service.stop,'wait',return_value=False),patch.object(self.service,'wait_openwrt',side_effect=self.final_verify):
self.service.run(self.ctx,self.fake_adapter())
self.assertEqual(self.prepare_calls,1)
self.assertEqual(self.write_calls,1)
self.assertEqual(self.store.load(self.record['id'])['status'],'completed')
events=[json.loads(line) for line in self.output.getvalue().splitlines()]
self.assertIn('waiting_user',[e['data'].get('status') for e in events if e['type']=='transaction'])
def test_app_restart_in_reset_wait_does_not_prepare_again(self):
adapter=self.fake_adapter()
with self.assertRaises(Pending):adapter.execute()
self.ctx.stage('android_setup','waiting_user')
self.record=Store(self.temp.name).load(self.record['id'])
self.ctx=Context(self.store,self.record,self.service.emit)
with patch.object(self.service.stop,'wait',return_value=False),patch.object(self.service,'wait_openwrt',side_effect=self.final_verify):
self.service.run(self.ctx,self.fake_adapter())
self.assertEqual(self.prepare_calls,1)
self.assertEqual(self.write_calls,1)
self.assertEqual(self.record['status'],'completed')
def test_export_import_keeps_relative_legacy_and_backups(self):
adapter=self.fake_adapter()
with self.assertRaises(Pending):adapter.execute()
self.record['data_directory']=str(self.ctx.directory)
self.store.save(self.record)
exported=Path(self.temp.name)/'export.zip'
self.service.dispatch({'protocol':1,'command':'export','params':{'transaction':self.record['id'],'path':str(exported)}})
import zipfile
with tempfile.TemporaryDirectory() as other:
source=Path(other)/'import'
with zipfile.ZipFile(exported) as z:z.extractall(source)
target=Service('.',Store(Path(other)/'app'),io.StringIO())
value=target.dispatch({'protocol':1,'command':'import','params':{'path':str(source)}})
restored=target.store.load(value['id'])
self.assertTrue(Path(restored['legacy']).is_file())
def test_stale_pre_reboot_adb_does_not_advance(self):
states=iter(['old','old','new'])
class Adapter:
def probe(_, *_args):return {**DEVICE,'boot_id':next(states)}
with patch.object(self.service.stop,'wait',return_value=False):
self.service.wait_android(self.ctx,Adapter())
self.assertEqual(self.record['stage'],'root_ready')
def test_two_stage_boot_chain_checkpoints_are_distinct(self):
source=self.ctx.directory/'package'
source.mkdir(parents=True)
(source/'OpenWrt-Installer.py').write_text('GUI=None\n')
adapter=Adapter({**PACKAGE,'path':str(source)},self.ctx)
legacy=self.ctx.directory/'legacy.json'
self.record['legacy']=str(legacy)
calls=[]
legacy.write_text('{"phase":"prepared"}')
adapter.action('bootchain-sync',lambda:calls.append('prepare'))
adapter.action('bootchain-sync',lambda:calls.append('duplicate'))
legacy.write_text('{"phase":"installed"}')
adapter.action('bootchain-sync',lambda:calls.append('final'))
self.assertEqual(calls,['prepare','final'])
def test_backend_cannot_escalate_confirmed_gap_plan_to_android_reset(self):
source=self.ctx.directory/'package';source.mkdir(parents=True)
(source/'OpenWrt-Installer.py').write_text('GUI=None\n')
adapter=Adapter({**PACKAGE,'path':str(source)},self.ctx)
self.record['plan'].update(target='GPT unallocated space',wipe=False,gap_start=90000000)
with self.assertRaisesRegex(ValueError,'confirmed plan'):
adapter.validate_plan('userdata shrink',wipe=True,capacity=4<<30)
adapter.validate_plan('GPT unallocated space',capacity=4<<30,gap_start=90000000)
def test_adapter_uses_confirmed_aligned_allocation(self):
self.record['choices']['size_gib']=4.1
self.record['plan']['openwrt_bytes']=4200*1048576
args=args_for(self.record,self.ctx.directory)
self.assertEqual(float(args.size)*1024,4200)
if __name__=='__main__':unittest.main()
+163
View File
@@ -0,0 +1,163 @@
import io
import json
from pathlib import Path
import struct
import subprocess
import sys
import tempfile
import unittest
from unittest.mock import patch
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from backend.state import Cancelled, Context, DeviceLock, Pending, RecoveryRequired, Store, compatible
from backend.service import Service, plan_install, verify_ext4_capacity
from backend.transport import Adb
PACKAGE = dict(protocol=1, adapter='e5', profile='e5', layout='e5root-ext4', kernel='v2', payloads={'boot':'a'*64}, path='.', name='test')
DEVICE = dict(serial='private-serial', cid='b'*32, profile='e5', model='E5', readiness='ready', slot='_a',
root=True, encrypted=True, existing=False, userdata_bytes=32 << 30, free_bytes=20 << 30,
storage={'ROOT':None, 'SIZE':32*2097152}, gpt={'safe_gaps':[], 'empty':[1]})
class StateTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.store = Store(self.temp.name)
self.record = self.store.create(PACKAGE, DEVICE.copy(), {'method':'part', 'size_gib':4}, plan_install(PACKAGE, DEVICE, {'method':'part','size_gib':4}))
self.events = []
self.ctx = Context(self.store, self.record, lambda kind, data:self.events.append((kind, data)))
def tearDown(self):
self.temp.cleanup()
def test_atomic_restart_and_moved_package(self):
self.ctx.stage('android_setup', 'waiting_user')
other = Store(self.temp.name).load(self.record['id'])
self.assertEqual(other['status'], 'waiting_user')
self.assertTrue(compatible(other['package'], {**PACKAGE, 'path':'D:/moved', 'name':'repair'}))
def test_compatible_repair_excludes_gui_changes(self):
self.assertTrue(compatible(PACKAGE, {**PACKAGE, 'gui':'fixed'}))
for field in ('adapter','profile','layout','kernel','protocol'):
with self.subTest(field=field), self.assertRaisesRegex(ValueError, field):
compatible(PACKAGE, {**PACKAGE, field:'different'})
with self.assertRaisesRegex(ValueError, 'boot'):
compatible(PACKAGE, {**PACKAGE, 'payloads':{'boot':'c'*64}})
def test_completed_effects_are_not_replayed(self):
calls = []
self.ctx.effect('format', lambda:calls.append('once'))
restarted = Context(self.store, self.store.load(self.record['id']), lambda *_:None)
restarted.effect('format', lambda:calls.append('twice'))
self.assertEqual(calls, ['once'])
def test_uncertain_partition_write_stops(self):
with self.assertRaises(ConnectionError):
self.ctx.effect('gpt', lambda: (_ for _ in ()).throw(ConnectionError()))
restarted = Context(self.store, self.store.load(self.record['id']), lambda *_:None)
with self.assertRaises(RecoveryRequired):
restarted.effect('gpt', lambda:self.fail('must never write'))
def test_failed_safe_transfer_can_retry(self):
with self.assertRaises(ConnectionError):
self.ctx.effect('upload', lambda: (_ for _ in ()).throw(ConnectionError()), retry_safe=True)
self.assertEqual(self.ctx.effect('upload', lambda:42, retry_safe=True), 42)
def test_cancel_is_deferred_through_write(self):
def write():
self.assertTrue(self.record['unsafe'])
self.ctx.cancel = True
return 'verified'
with self.assertRaises(Cancelled):
self.ctx.effect('boot', write)
self.assertEqual(self.store.load(self.record['id'])['effects']['boot']['state'], 'done')
def test_cross_process_device_mutex(self):
code = "import sys;sys.path.insert(0,sys.argv[1]);from backend.state import DeviceLock\nwith DeviceLock(sys.argv[2],'same-cid'): pass"
with DeviceLock(self.temp.name, 'same-cid'):
result = subprocess.run([sys.executable,'-c',code,str(Path(__file__).resolve().parents[1]),self.temp.name],capture_output=True)
self.assertNotEqual(result.returncode, 0)
self.assertIn(b'Another installer', result.stderr)
with DeviceLock(self.temp.name, 'same-cid'):
pass
def test_public_events_mask_identity(self):
self.ctx.stage('backup')
serialized = json.dumps(self.events)
self.assertNotIn(DEVICE['serial'], serialized)
self.assertNotIn(DEVICE['cid'], serialized)
def test_gap_avoids_userdata_reset(self):
device = {**DEVICE,'gpt':{'safe_gaps':[(90000000, 10*2097152)], 'empty':[1]}}
plan = plan_install(PACKAGE, device, {'method':'part','size_gib':4})
self.assertFalse(plan['wipe'])
self.assertEqual(plan['android_bytes'], DEVICE['userdata_bytes'])
self.assertEqual(plan['gap_start'], 90000000)
def test_unencrypted_userdata_preserved(self):
plan = plan_install(PACKAGE, {**DEVICE,'encrypted':False}, {'method':'part','size_gib':4})
self.assertFalse(plan['wipe'])
self.assertFalse(plan['two_stage'])
def test_tf_no_capacity_ceiling(self):
plan = plan_install(PACKAGE, {**DEVICE,'tf':'/dev/block/mmcblk1p1','tf_bytes':128 << 30}, {'method':'tf'})
self.assertEqual(plan['openwrt_bytes'], 128 << 30)
def test_real_capacity_validation(self):
raw = bytearray(1024)
raw[56:58] = b'\x53\xef'
struct.pack_into('<I',raw,24,2)
struct.pack_into('<I',raw,4,(10 << 30)//4096)
self.assertEqual(verify_ext4_capacity(raw, 10 << 30), 10 << 30)
struct.pack_into('<I',raw,4,(2 << 30)//4096)
with self.assertRaisesRegex(ValueError,'capacity'):
verify_ext4_capacity(raw, 10 << 30)
def test_multiple_devices_need_selection(self):
service = Service('.', self.store, io.StringIO())
service.package = PACKAGE
with self.assertRaisesRegex(ValueError, 'Select'):
service.dispatch({'protocol':1,'command':'probe','params':{}})
def test_expected_reboot_waits_without_failure_or_deadline(self):
service = Service('.', self.store, io.StringIO())
states = iter(['android_boot', 'debug_authorization', 'android_setup', 'magisk', 'root_permission', 'ready'])
class Adapter:
def probe(_, serial, method):
return {**DEVICE, 'readiness':next(states)}
with patch.object(service.stop, 'wait', return_value=False):
service.wait_android(self.ctx, Adapter())
stages = [event[1]['stage'] for event in self.events]
self.assertEqual(stages, ['android_boot', 'debug_authorization', 'android_setup', 'magisk', 'root_permission', 'root_ready'])
self.assertNotIn('failed',[event[1]['status'] for event in self.events])
def test_wrong_device_after_reset_is_rejected(self):
service = Service('.', self.store, io.StringIO())
class Adapter:
def probe(_, *args): return {**DEVICE,'cid':'c'*32}
with self.assertRaises(RecoveryRequired):
service.wait_android(self.ctx, Adapter())
def test_unknown_commands_cannot_execute_shell(self):
service = Service('.', self.store, io.StringIO())
with self.assertRaises(ValueError):
service.dispatch({'protocol':1,'command':'exec','params':{'command':'format'}})
def test_adb_serial_binding_on_all_operations(self):
with patch('backend.transport.shutil.which',return_value='adb'):
transport = Adb('.', 'chosen')
result = type('Result', (), {'returncode':0,'stdout':b'ok'})()
with patch('backend.transport.subprocess.run',return_value=result) as run:
transport.call('shell','id')
self.assertEqual(run.call_args.args[0][:3], ['adb','-s','chosen'])
def test_authorized_su_is_used_without_installing_magisk(self):
with patch('backend.transport.shutil.which',return_value='adb'):
transport = Adb('.', 'chosen')
with patch.object(transport,'shell',side_effect=['2000','0','uid=0(root)']):
self.assertEqual(transport.root_status(),'ready')
if __name__ == '__main__':
unittest.main()
+186
View File
@@ -0,0 +1,186 @@
"""UI-only test bridge. Never packaged and never opens ADB or SSH."""
import json
from pathlib import Path
from playwright.sync_api import sync_playwright
ROOT=Path(__file__).resolve().parents[1]
BRIDGE=r"""
(() => {
const callbacks = new Map(); let seq = 1;
const device = {serial:'fixture-1234',model:'E5',system:'Android',slot:'_a',root:true,readiness:'ready',encrypted:true,profile:'e5'};
const pkg = {path:'D:/OpenWrt-Package',name:'e5-openwrt-release',adapter:'e5',profile:'e5',kernel:'v2'};
const tx = {id:'a'.repeat(32),status:'ready',stage:'plan',device,package:pkg,choices:{method:'part'},plan:{wipe:true,two_stage:true,offline:true,openwrt_bytes:10737418240,android_bytes:21474836480,target:'userdata shrink',grow:true},completed:[],unsafe:false,updated:Date.now()/1000};
window.__fixture={tx,callbacks,records:[tx],fail:null,requests:[]};
window.__TAURI_EVENT_PLUGIN_INTERNALS__={unregisterListener(){}};
window.__TAURI_INTERNALS__={
transformCallback(fn,once){const id=seq++;callbacks.set(id,fn);return id;},
unregisterCallback(id){callbacks.delete(id);},
invoke:async(cmd,args={})=>{
if(window.__fixture.fail===cmd)throw new Error('Fixture: native operation rejected');
if(cmd==='save_log')return window.__fixture.cancelSave ? null : 'D:/fixture/log.txt';
if(cmd==='plugin:event|listen'){window.__fixture.event=args.handler;return 1;}
if(cmd==='plugin:event|unlisten')return;
if(cmd==='backend_request'){
window.__fixture.requests.push(args.command);
if(window.__fixture.fail===args.command)throw new Error('Fixture: operation rejected');
switch(args.command){
case 'hello':return {package_path:pkg.path,transactions:window.__fixture.saved || []};
case 'package':return pkg;
case 'devices':return [{...device,label:'E5',state:'device'},{serial:'fixture-5678',label:'Other device',state:'unauthorized'}];
case 'probe':return device;
case 'plan':return tx;
case 'list':return window.__fixture.records;
case 'start':tx.stage='android_setup';tx.status='waiting_user';return {...tx};
default:return null;
}
}
return null;
}
};
window.__emitFixture=(change)=>{
Object.assign(tx,change);
callbacks.get(window.__fixture.event)?.({event:'backend',id:1,payload:{type:'transaction',data:JSON.parse(JSON.stringify(tx))}});
};
window.__logFixture=()=>{for(let i=0;i<700;i++)callbacks.get(window.__fixture.event)?.({event:'backend',id:1,payload:{type:'log',data:{message:'Test log line '+i}}});};
})();
"""
def settle(page):
page.wait_for_timeout(450)
def layout(page):
result=page.evaluate('''() => {
const footer=document.querySelector('footer').getBoundingClientRect();
const main=document.querySelector('main').getBoundingClientRect();
const hint=document.querySelector('.sidebar-bottom').getBoundingClientRect();
const aside=document.querySelector('aside').getBoundingClientRect();
return {root:document.documentElement.scrollHeight,height:innerHeight,width:innerWidth,
scroll:scrollY,footer:footer.bottom,main:main.bottom,hint:hint.bottom,aside:aside.bottom,
horizontal:document.documentElement.scrollWidth};
}''')
assert result['root']==result['height'] and result['horizontal']==result['width'],result
assert result['scroll']==0 and result['footer']<=result['height']+.5,result
assert result['aside']-result['hint']<30 and result['hint']<=result['aside'],result
def main():
out=ROOT/'screenshots';out.mkdir(exist_ok=True)
with sync_playwright() as p:
browser=p.chromium.launch()
context=browser.new_context(viewport={'width':1120,'height':900},device_scale_factor=1)
context.add_init_script(BRIDGE+"localStorage.setItem('onboarding-v1','seen');")
page=context.new_page();errors=[]
page.on('pageerror',lambda error:errors.append(str(error)))
page.goto('http://127.0.0.1:1420')
page.get_by_role('heading',name='你想如何使用 OpenWrt?').wait_for()
page.get_by_label('主题').select_option('light')
settle(page);layout(page)
page.screenshot(path=str(out/'home-light-zh.png'),full_page=True)
page.get_by_role('button',name='安装 OpenWrt',exact=False).click()
page.get_by_role('button',name='校验安装包',exact=True).click()
page.get_by_role('button',name='刷新设备',exact=True).click()
assert page.get_by_label('请选择设备').input_value()==''
page.get_by_label('请选择设备').select_option('fixture-1234')
page.get_by_role('button',name='检查设备',exact=True).click()
page.get_by_role('button',name='查看安装计划').click()
assert page.get_by_role('button',name='确认并开始').is_disabled()
settle(page);layout(page)
page.screenshot(path=str(out/'plan-light-zh.png'),full_page=True)
page.get_by_role('checkbox').check()
page.get_by_role('button',name='确认并开始').click()
page.get_by_role('heading',name='请完成 Android 初始设置',exact=True).first.wait_for()
settle(page);layout(page)
page.screenshot(path=str(out/'wait-setup-light-zh.png'),full_page=True)
page.get_by_label('主题').select_option('dark')
page.get_by_label('语言').select_option('en')
page.wait_for_timeout(300)
page.evaluate("window.__emitFixture({stage:'root_permission',status:'waiting_user'})")
page.get_by_role('heading',name='Allow the root request',exact=True).first.wait_for()
settle(page)
assert page.locator('[data-sonner-toast][data-type=info]').filter(has_text='Allow the root request').count()==1
for _ in range(8):page.evaluate("window.__emitFixture({stage:'root_permission',status:'waiting_user'})")
assert page.locator('[data-sonner-toast][data-type=info]').filter(has_text='Allow the root request').count()==1
page.screenshot(path=str(out/'wait-root-dark-en.png'),full_page=True)
page.evaluate("window.__emitFixture({stage:'complete',status:'completed',result:{filesystem_bytes:10737418240,url:'http://192.168.9.1',backup_directory:'fixture'}})")
page.get_by_role('heading',name='OpenWrt installed and verified').wait_for()
settle(page);layout(page)
page.screenshot(path=str(out/'complete-dark-en.png'),full_page=True)
# Smallest supported native window: large list and long log scroll independently.
page.set_viewport_size({'width':800,'height':650})
page.get_by_label('Language').select_option('zh')
page.get_by_label('主题').select_option('light')
page.get_by_role('button',name='开始',exact=True).click()
page.evaluate("window.__fixture.records=Array.from({length:120},(_,i)=>({...window.__fixture.tx,id:String(i).padStart(32,'0'),status:'cancelled',stage:'backup'}))")
page.get_by_role('button',name='继续未完成的安装',exact=False).click()
page.get_by_role('heading',name='继续未完成的安装').wait_for();settle(page)
assert page.evaluate('document.activeElement.tagName')=='H1'
assert page.locator('.record').count()==120
layout(page)
before=page.locator('h1').bounding_box()
page.locator('.records-list').evaluate('(el)=>el.scrollTop=el.scrollHeight')
assert page.locator('h1').bounding_box()==before
assert page.locator('.records-list').evaluate('(el)=>el.scrollTop>0')
page.evaluate('window.__logFixture()')
page.get_by_role('button',name='详细日志',exact=False).click();settle(page);layout(page)
assert page.locator('.records-list').evaluate('(el)=>el.clientHeight>=100')
assert page.locator('.log-panel pre').evaluate('(el)=>el.scrollHeight>el.clientHeight')
assert page.locator('.log-toggle span').inner_text()=='500'
page.screenshot(path=str(out/'resume-small-light-zh.png'),full_page=True)
page.evaluate('window.__fixture.cancelSave=true')
page.get_by_role('button',name='导出日志',exact=True).click();settle(page)
assert page.get_by_text('日志已导出',exact=True).count()==0
page.evaluate('window.__fixture.cancelSave=false')
page.get_by_role('button',name='导出日志',exact=True).click()
page.get_by_text('日志已导出',exact=True).wait_for()
page.evaluate("window.__fixture.fail='write_log'")
page.get_by_role('button',name='导出日志',exact=True).click()
page.get_by_text('Error: Fixture: native operation rejected',exact=True).wait_for()
page.evaluate("window.__fixture.fail='pick_package'")
page.get_by_role('button',name='选择安装包目录',exact=True).click()
assert page.locator('[data-sonner-toast][data-type=error]').count()==1
page.evaluate('window.__fixture.fail=null')
page.evaluate("Object.defineProperty(navigator.clipboard,'writeText',{configurable:true,value:()=>Promise.reject(new Error('Fixture: clipboard denied'))})")
page.get_by_role('button',name='复制',exact=True).click()
page.get_by_text('Error: Fixture: clipboard denied',exact=True).wait_for()
page.get_by_role('button',name='详细日志',exact=False).click();settle(page)
page.get_by_role('button',name='开始',exact=True).click();settle(page)
page.get_by_role('button',name='安装 OpenWrt',exact=False).click();settle(page)
# One notification surface catches backend errors, native dialog rejection and clipboard failure.
page.evaluate("window.__fixture.fail='package'")
page.get_by_role('button',name='校验安装包',exact=True).click()
page.get_by_text('Error: Fixture: operation rejected',exact=True).wait_for()
assert page.locator('[data-sonner-toast][data-type=error]').count()==1
page.evaluate('window.__fixture.fail=null')
page.get_by_role('button',name='校验安装包',exact=True).click()
page.get_by_role('button',name='刷新设备',exact=True).click()
assert page.get_by_label('请选择设备').input_value()=='fixture-1234'
page.get_by_label('请选择设备').select_option('fixture-1234')
page.get_by_role('button',name='检查设备',exact=True).click();settle(page);layout(page)
assert page.locator('.page-scroll').evaluate('(el)=>el.scrollHeight>el.clientHeight')
action=page.get_by_role('button',name='查看安装计划').bounding_box()
page.locator('.page-scroll').evaluate('(el)=>el.scrollTop=el.scrollHeight')
assert page.get_by_role('button',name='查看安装计划').bounding_box()==action
page.screenshot(path=str(out/'install-small-light-zh.png'),full_page=True)
# System theme and reduced motion remain usable after view changes.
page.emulate_media(color_scheme='dark',reduced_motion='reduce')
page.get_by_label('主题').select_option('system')
assert page.locator('html').get_attribute('class')=='dark'
page.get_by_role('button',name='返回',exact=True).click();settle(page);layout(page)
assert page.locator('.purpose').first.evaluate('(el)=>getComputedStyle(el).transform') in ('none','matrix(1, 0, 0, 1, 0, 0)')
page.get_by_label('语言').select_option('en')
page.get_by_role('button',name='Install OpenWrt',exact=False).click();settle(page)
page.get_by_role('button',name='Inspect device',exact=True).click()
page.evaluate("Object.assign(window.__fixture.tx,{status:'ready',stage:'plan'})")
page.get_by_role('button',name='Review installation plan').click();settle(page);layout(page)
confirm=page.get_by_role('button',name='Confirm and start')
assert confirm.is_visible() and confirm.is_disabled()
assert confirm.bounding_box()['y']<page.locator('.log-panel').bounding_box()['y']
page.screenshot(path=str(out/'plan-small-dark-en.png'),full_page=True)
assert not errors, errors
print('UI smoke passed: fixed 800x650/1120x900 layout, 120 records, 500 log cap, independent scrolling, toast errors/status deduplication, multi-device selection, confirmation, waits/completion, themes/languages/reduced motion; no device transport')
browser.close()
if __name__=='__main__':main()
+1
View File
@@ -0,0 +1 @@
{"$schema":"https://ui.shadcn.com/schema.json","style":"new-york","rsc":false,"tsx":true,"tailwind":{"config":"tailwind.config.js","css":"src/style.css","baseColor":"slate","cssVariables":true},"aliases":{"components":"./src/components","utils":"./src/utils"},"iconLibrary":"lucide"}
+1
View File
@@ -0,0 +1 @@
<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width,initial-scale=1"/><title>OpenWrt Installer</title></head><body><div id="root"></div><script type="module" src="/src/main.tsx"></script></body></html>
+5230
View File
File diff suppressed because it is too large. Load diff
+38
View File
@@ -0,0 +1,38 @@
{
"name": "openwrt-installer",
"version": "1.0.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite --host 127.0.0.1",
"build": "tsc -b && vite build",
"tauri": "tauri",
"test": "vitest run"
},
"dependencies": {
"@radix-ui/react-dialog": "^1.3.1",
"@radix-ui/react-slot": "^1.2.3",
"@tauri-apps/api": "^2.8.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"lucide-react": "^0.468.0",
"motion": "^14.2.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-markdown": "^10.1.0",
"sonner": "^2.0.8",
"tailwind-merge": "^2.6.0"
},
"devDependencies": {
"@tauri-apps/cli": "^2.8.0",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"@vitejs/plugin-react": "^4.3.4",
"autoprefixer": "^10.4.20",
"postcss": "^8.4.49",
"tailwindcss": "^3.4.17",
"typescript": "^5.7.2",
"vite": "^6.1.0",
"vitest": "^3.0.5"
}
}
+1
View File
@@ -0,0 +1 @@
export default {plugins: {tailwindcss: {}, autoprefixer: {}}};
+3
View File
@@ -0,0 +1,3 @@
[toolchain]
channel = "1.90.0"
profile = "minimal"
+5076
View File
File diff suppressed because it is too large. Load diff
+23
View File
@@ -0,0 +1,23 @@
[package]
name = "openwrt-installer"
version = "1.0.0"
description = "OpenWrt desktop installer"
edition = "2021"
rust-version = "1.77.2"
[build-dependencies]
tauri-build = { version = "2", features = [] }
[dependencies]
tauri = { version = "2", features = [] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
rfd = "0.15"
tokio = { version = "1", features = ["sync", "time"] }
[profile.release]
opt-level = "s"
lto = true
codegen-units = 1
strip = true
panic = "abort"
+1
View File
@@ -0,0 +1 @@
fn main() { tauri_build::build() }
@@ -0,0 +1 @@
{"identifier":"default","description":"Local installer window; device operations use fixed Rust commands","windows":["main"],"permissions":["core:default"]}
@@ -0,0 +1 @@
{"core":{"default_permission":{"identifier":"default","description":"Default core plugins set.","permissions":["core:path:default","core:event:default","core:window:default","core:webview:default","core:app:default","core:image:default","core:resources:default","core:menu:default","core:tray:default"]},"permissions":{},"permission_sets":{},"global_scope_schema":null},"core:app":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-version","allow-name","allow-tauri-version","allow-identifier","allow-bundle-type","allow-register-listener","allow-remove-listener","allow-supports-multiple-windows"]},"permissions":{"allow-app-hide":{"identifier":"allow-app-hide","description":"Enables the app_hide command without any pre-configured scope.","commands":{"allow":["app_hide"],"deny":[]}},"allow-app-show":{"identifier":"allow-app-show","description":"Enables the app_show command without any pre-configured scope.","commands":{"allow":["app_show"],"deny":[]}},"allow-bundle-type":{"identifier":"allow-bundle-type","description":"Enables the bundle_type command without any pre-configured scope.","commands":{"allow":["bundle_type"],"deny":[]}},"allow-default-window-icon":{"identifier":"allow-default-window-icon","description":"Enables the default_window_icon command without any pre-configured scope.","commands":{"allow":["default_window_icon"],"deny":[]}},"allow-exit":{"identifier":"allow-exit","description":"Enables the exit command without any pre-configured scope.","commands":{"allow":["exit"],"deny":[]}},"allow-fetch-data-store-identifiers":{"identifier":"allow-fetch-data-store-identifiers","description":"Enables the fetch_data_store_identifiers command without any pre-configured scope.","commands":{"allow":["fetch_data_store_identifiers"],"deny":[]}},"allow-identifier":{"identifier":"allow-identifier","description":"Enables the identifier command without any pre-configured scope.","commands":{"allow":["identifier"],"deny":[]}},"allow-name":{"identifier":"allow-name","description":"Enables the name command without any pre-configured scope.","commands":{"allow":["name"],"deny":[]}},"allow-register-listener":{"identifier":"allow-register-listener","description":"Enables the register_listener command without any pre-configured scope.","commands":{"allow":["register_listener"],"deny":[]}},"allow-remove-data-store":{"identifier":"allow-remove-data-store","description":"Enables the remove_data_store command without any pre-configured scope.","commands":{"allow":["remove_data_store"],"deny":[]}},"allow-remove-listener":{"identifier":"allow-remove-listener","description":"Enables the remove_listener command without any pre-configured scope.","commands":{"allow":["remove_listener"],"deny":[]}},"allow-set-app-theme":{"identifier":"allow-set-app-theme","description":"Enables the set_app_theme command without any pre-configured scope.","commands":{"allow":["set_app_theme"],"deny":[]}},"allow-set-dock-visibility":{"identifier":"allow-set-dock-visibility","description":"Enables the set_dock_visibility command without any pre-configured scope.","commands":{"allow":["set_dock_visibility"],"deny":[]}},"allow-supports-multiple-windows":{"identifier":"allow-supports-multiple-windows","description":"Enables the supports_multiple_windows command without any pre-configured scope.","commands":{"allow":["supports_multiple_windows"],"deny":[]}},"allow-tauri-version":{"identifier":"allow-tauri-version","description":"Enables the tauri_version command without any pre-configured scope.","commands":{"allow":["tauri_version"],"deny":[]}},"allow-version":{"identifier":"allow-version","description":"Enables the version command without any pre-configured scope.","commands":{"allow":["version"],"deny":[]}},"deny-app-hide":{"identifier":"deny-app-hide","description":"Denies the app_hide command without any pre-configured scope.","commands":{"allow":[],"deny":["app_hide"]}},"deny-app-show":{"identifier":"deny-app-show","description":"Denies the app_show command without any pre-configured scope.","commands":{"allow":[],"deny":["app_show"]}},"deny-bundle-type":{"identifier":"deny-bundle-type","description":"Denies the bundle_type command without any pre-configured scope.","commands":{"allow":[],"deny":["bundle_type"]}},"deny-default-window-icon":{"identifier":"deny-default-window-icon","description":"Denies the default_window_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["default_window_icon"]}},"deny-exit":{"identifier":"deny-exit","description":"Denies the exit command without any pre-configured scope.","commands":{"allow":[],"deny":["exit"]}},"deny-fetch-data-store-identifiers":{"identifier":"deny-fetch-data-store-identifiers","description":"Denies the fetch_data_store_identifiers command without any pre-configured scope.","commands":{"allow":[],"deny":["fetch_data_store_identifiers"]}},"deny-identifier":{"identifier":"deny-identifier","description":"DenLine truncated
@@ -0,0 +1 @@
{"default":{"identifier":"default","description":"Local installer window; device operations use fixed Rust commands","local":true,"windows":["main"],"permissions":["core:default"]}}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.6 KiB

+132
View File
@@ -0,0 +1,132 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use serde_json::{json, Value};
use std::{collections::HashMap, io::{BufRead, BufReader, Write}, path::PathBuf,
process::{ChildStdin, Command, Stdio}, sync::{Arc, Mutex, atomic::{AtomicBool, AtomicU64, Ordering}}};
use tauri::{Emitter, Manager, State};
use tokio::sync::oneshot;
const COMMANDS: &[&str] = &["hello","snapshot","list","package","devices","probe","probe_update","plan","start","resume","retry","cancel","can_close","export","import"];
struct Bridge {
input: Mutex<Option<ChildStdin>>,
pending: Mutex<HashMap<u64, oneshot::Sender<Result<Value, String>>>>,
sequence: AtomicU64,
busy: AtomicBool,
directory: PathBuf,
export_log: Mutex<Option<PathBuf>>,
}
#[tauri::command]
async fn backend_request(state: State<'_, Arc<Bridge>>, command: String, params: Value) -> Result<Value, String> {
if !COMMANDS.contains(&command.as_str()) || !params.is_object() {return Err("Unsupported installer command".into());}
let id = state.sequence.fetch_add(1, Ordering::SeqCst);
let (send, receive) = oneshot::channel();
state.pending.lock().unwrap().insert(id, send);
let line = json!({"protocol":1,"id":id,"command":command,"params":params}).to_string()+"\n";
let written = {
let mut input = state.input.lock().unwrap();
input.as_mut().ok_or("Backend is unavailable")?.write_all(line.as_bytes()).map_err(|e|e.to_string())
};
if let Err(error) = written {state.pending.lock().unwrap().remove(&id); return Err(error);}
// Verification and large archives can take minutes. No artificial device wait deadline.
receive.await.map_err(|_|"Backend closed the response channel".to_string())?
}
#[tauri::command]
async fn pick_package() -> Option<String> {
tauri::async_runtime::spawn_blocking(|| rfd::FileDialog::new().set_title("OpenWrt package / 安装包目录").pick_folder().map(|p|p.to_string_lossy().to_string())).await.ok().flatten()
}
#[tauri::command]
async fn pick_recovery() -> Option<String> {
tauri::async_runtime::spawn_blocking(|| rfd::FileDialog::new().set_title("Recovery folder / 完整事务与备份目录").pick_folder().map(|p|p.to_string_lossy().to_string())).await.ok().flatten()
}
#[tauri::command]
async fn save_backup() -> Option<String> {
tauri::async_runtime::spawn_blocking(|| rfd::FileDialog::new().set_file_name("OpenWrt-Backup.zip").save_file().map(|p|p.to_string_lossy().to_string())).await.ok().flatten()
}
#[tauri::command]
async fn save_log(state: State<'_, Arc<Bridge>>) -> Result<Option<String>, String> {
let result = tauri::async_runtime::spawn_blocking(|| rfd::FileDialog::new().set_file_name("OpenWrt-Installer.log").save_file()).await.ok().flatten();
*state.export_log.lock().unwrap() = result.clone();
Ok(result.map(|p|p.to_string_lossy().to_string()))
}
#[tauri::command]
fn write_log(state: State<'_, Arc<Bridge>>, path: String, text: String) -> Result<(), String> {
let selected = state.export_log.lock().unwrap().take().ok_or("Select export destination first")?;
if selected != PathBuf::from(path) || text.len() > 2_000_000 {return Err("Invalid log export".into());}
std::fs::write(selected, text).map_err(|e|e.to_string())
}
#[tauri::command]
fn open_data(state: State<'_, Arc<Bridge>>) -> Result<(), String> {
// Fixed directory, never a shell string supplied by the webview.
Command::new("explorer.exe").arg(&state.directory).spawn().map_err(|e|e.to_string())?;
Ok(())
}
fn main() {
let directory = std::env::var_os("LOCALAPPDATA").map(PathBuf::from).unwrap_or_else(std::env::temp_dir).join("OpenWrt-Installer");
let bridge = Arc::new(Bridge {input:Mutex::new(None),pending:Mutex::new(HashMap::new()),sequence:AtomicU64::new(1),busy:AtomicBool::new(false),directory,export_log:Mutex::new(None)});
let setup_state = bridge.clone();
let app = tauri::Builder::default().manage(bridge.clone())
.invoke_handler(tauri::generate_handler![backend_request,pick_package,pick_recovery,save_backup,save_log,write_log,open_data])
.setup(move |app| {
let root = std::env::current_exe()?.parent().ok_or("Executable has no directory")?.to_path_buf();
let mut process = Command::new(root.join("tools/backend/openwrt-backend.exe"));
process.args(["--package-root", &root.to_string_lossy(), "--data-dir", &setup_state.directory.to_string_lossy()]);
process.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null());
#[cfg(windows)] { use std::os::windows::process::CommandExt; process.creation_flags(0x08000000); }
match process.spawn() {
Ok(mut child) => {
*setup_state.input.lock().unwrap() = child.stdin.take();
let output = child.stdout.take().unwrap();
let state = setup_state.clone();
let handle = app.handle().clone();
std::thread::spawn(move || {
for line in BufReader::new(output).lines() {
let Ok(line) = line else {break};
let Ok(event) = serde_json::from_str::<Value>(&line) else {continue};
if event["type"] == "response" {
if let Some(id) = event["id"].as_u64() {
if let Some(sender) = state.pending.lock().unwrap().remove(&id) {
let result = if event["data"]["ok"] == true {Ok(event["data"]["result"].clone())} else {Err(event["data"]["error"].as_str().unwrap_or("Backend error").to_string())};
let _ = sender.send(result);
}
}
} else {
if event["type"] == "transaction" {
let status = event["data"]["status"].as_str().unwrap_or("");
state.busy.store(matches!(status,"running"|"waiting_user"|"waiting_device"),Ordering::SeqCst);
}
let _ = handle.emit("backend", event);
}
}
state.busy.store(false,Ordering::SeqCst);
state.pending.lock().unwrap().clear();
let _ = handle.emit("backend",json!({"type":"backend_exit","data":{}}));
let _ = child.wait();
});
}
Err(_) => {
rfd::MessageDialog::new().set_title("OpenWrt Installer").set_description("Backend is missing. Extract the complete package, including tools/backend.\n后端缺失,请完整解压安装包(含 tools/backend 目录)。").set_level(rfd::MessageLevel::Error).show();
}
}
Ok(())
})
.on_window_event(|window,event| {
if let tauri::WindowEvent::CloseRequested {api,..} = event {
let state = window.state::<Arc<Bridge>>();
if state.busy.load(Ordering::SeqCst) {
api.prevent_close();
let _ = window.emit("backend",json!({"type":"close_blocked","data":{}}));
}
}
}).build(tauri::generate_context!());
match app {
Ok(app) => app.run(move |_, event| {
if matches!(event,tauri::RunEvent::Exit) {bridge.input.lock().unwrap().take();}
}),
Err(error) => {
rfd::MessageDialog::new().set_title("OpenWrt Installer / WebView2").set_description(format!("Cannot start the system WebView2. Install Microsoft Edge WebView2 Evergreen Runtime and reopen the installer.\n无法启动系统 WebView2。请安装 Microsoft Edge WebView2 Evergreen Runtime 后重试。\nhttps://developer.microsoft.com/microsoft-edge/webview2/\n\n{error}")).set_level(rfd::MessageLevel::Error).show();
}
}
}
+12
View File
@@ -0,0 +1,12 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "OpenWrt Installer",
"version": "1.0.0",
"identifier": "org.openwrt.desktop-installer",
"build": {"beforeDevCommand": "npm run dev", "devUrl": "http://127.0.0.1:1420", "beforeBuildCommand": "npm run build", "frontendDist": "../dist"},
"app": {
"windows": [{"label":"main","title":"OpenWrt Installer","width":1120,"height":860,"minWidth":800,"minHeight":650,"center":true}],
"security": {"csp":"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src ipc: http://ipc.localhost"}
},
"bundle": {"active":false,"icon":["icons/icon.ico"],"windows":{"webviewInstallMode":{"type":"skip"}}}
}
@@ -0,0 +1,59 @@
import {useEffect, useMemo, useRef, useState} from 'react';
import Markdown from 'react-markdown';
import {AnimatePresence, m, useReducedMotion} from 'motion/react';
import {ArrowRight, BookOpen, Check, Search, ShieldCheck, Usb} from 'lucide-react';
import {Button} from './ui/button';
import {Dialog, DialogContent, DialogDescription, DialogTitle} from './ui/dialog';
import {helpTopics} from '../help-data';
import {helpStrings} from '../help-i18n';
import type {Language} from '../i18n';
export function HelpCenter({language, open, onOpenChange, initialTopic, onGuide}:
{language:Language; open:boolean; onOpenChange:(open:boolean)=>void; initialTopic:string; onGuide:()=>void}) {
const t = helpStrings[language];
const [search, setSearch] = useState('');
const [selected, setSelected] = useState(initialTopic);
const content = useRef<HTMLElement>(null);
const topics = useMemo(() => helpTopics(language), [language]);
const filtered = topics.filter(topic => `${topic.title}\n${topic.markdown}`.toLocaleLowerCase().includes(search.trim().toLocaleLowerCase()));
const active = filtered.find(topic => topic.id === selected) || filtered[0];
useEffect(() => {if (open) {setSelected(initialTopic); setSearch('');}}, [open, initialTopic]);
useEffect(() => {content.current?.scrollTo({top:0});}, [active?.id, language]);
return <Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent closeLabel={t.close} className="help-dialog">
<div className="dialog-heading"><div className="eyebrow">OPENWRT · HELP</div><DialogTitle>{t.help}</DialogTitle><DialogDescription>{t.helpIntro}</DialogDescription></div>
<div className="help-search"><Search size={17} aria-hidden="true"/><input aria-label={t.search} placeholder={t.searchPlaceholder} value={search} onChange={e => setSearch(e.target.value)}/><span aria-live="polite">{filtered.length} {t.results}</span></div>
<div className="help-layout"><nav className="help-topics scroll-area" aria-label={t.topics}>
{filtered.map(topic => <button key={topic.id} aria-current={active?.id === topic.id ? 'page' : undefined} onClick={() => setSelected(topic.id)}>{topic.title}</button>)}
</nav><article ref={content} className="help-article scroll-area" tabIndex={0} aria-label={active?.title || t.noResults}>
{active ? <><h2>{active.title}</h2><div className="help-markdown"><Markdown skipHtml components={{a:({children,href}) => <span className="help-address" title={href}>{children}</span>}}>{active.markdown}</Markdown></div></> : <p className="empty-state">{t.noResults}</p>}
</article></div>
<div className="dialog-footer"><Button variant="outline" onClick={onGuide}><BookOpen size={16}/>{t.replay}</Button><Button variant="ghost" onClick={() => onOpenChange(false)}>{t.close}</Button></div>
</DialogContent>
</Dialog>;
}
export function GettingStarted({language, open, onOpenChange}:
{language:Language; open:boolean; onOpenChange:(open:boolean)=>void}) {
const t = helpStrings[language];
const [step, setStep] = useState(0);
const reduceMotion = useReducedMotion();
const body = useRef<HTMLDivElement>(null);
useEffect(() => {if (open) setStep(0);}, [open]);
useEffect(() => {body.current?.scrollTo({top:0});}, [step]);
const Icon = [Usb, ShieldCheck, BookOpen][step];
return <Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent closeLabel={t.closeGuide} className="onboarding-dialog">
<div className="dialog-heading"><div className="eyebrow">OPENWRT · {t.guide}</div><DialogTitle>{t.guide}</DialogTitle><DialogDescription>{t.guideIntro}</DialogDescription></div>
<ol className="guide-steps" aria-label={t.guide}>{t.introTitles.map((title,i) => <li key={title} aria-current={step === i ? 'step' : undefined} className={i <= step ? 'reached' : ''}><span>{i < step ? <Check size={13}/> : i+1}</span><div>{title}</div></li>)}</ol>
<div className="onboarding-body scroll-area" ref={body}>
<AnimatePresence mode="wait" initial={false}><m.div key={step} initial={{opacity:reduceMotion ? 1 : 0,x:reduceMotion ? 0 : 6}} animate={{opacity:1,x:0}} exit={{opacity:0}} transition={{duration:reduceMotion ? 0 : .14}}>
<div className="guide-title"><Icon size={25} aria-hidden="true"/><h2>{t.introTitles[step]}</h2></div>
<ul>{t.introBodies[step].map(paragraph => <li key={paragraph}>{paragraph}</li>)}</ul>
</m.div></AnimatePresence>
<p className="guide-no-action"><ShieldCheck size={16}/>{t.noAction}</p>
</div>
<div className="dialog-footer"><Button variant="ghost" onClick={() => onOpenChange(false)}>{t.skip}</Button><span className="guide-count">{t.step} {step+1} {t.of}</span><div className="guide-controls">{step > 0 && <Button variant="outline" onClick={() => setStep(step-1)}>{t.back}</Button>}<Button onClick={() => step < 2 ? setStep(step+1) : onOpenChange(false)}>{step < 2 ? t.next : t.finish}<ArrowRight size={16}/></Button></div></div>
</DialogContent>
</Dialog>;
}
+16
View File
@@ -0,0 +1,16 @@
import * as React from 'react';
import { Slot } from '@radix-ui/react-slot';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '../../utils';
const variants = cva('ui-button inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 h-10 px-4 py-2', {variants: {variant: {
default: 'bg-primary text-primary-foreground hover:opacity-90',
outline: 'border border-border bg-card hover:bg-muted text-foreground',
ghost: 'hover:bg-muted text-foreground',
destructive: 'bg-destructive text-white hover:opacity-90'
}}, defaultVariants: {variant: 'default'}});
export interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement>, VariantProps<typeof variants> {asChild?: boolean}
export const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(({className, variant, asChild = false, ...props}, ref) => {
const Component = asChild ? Slot : 'button';
return <Component ref={ref} className={cn(variants({variant, className}))} {...props}/>;
});
Button.displayName = 'Button';
+26
View File
@@ -0,0 +1,26 @@
import * as React from 'react';
import * as Primitive from '@radix-ui/react-dialog';
import {X} from 'lucide-react';
import {cn} from '../../utils';
export const Dialog = Primitive.Root;
export const DialogTitle = Primitive.Title;
export const DialogDescription = Primitive.Description;
export function DialogContent({children, className, closeLabel, ...props}:
React.ComponentPropsWithoutRef<typeof Primitive.Content> & {closeLabel: string}) {
const previousFocus = React.useRef<HTMLElement | null>(null);
return <Primitive.Portal>
<Primitive.Overlay className="dialog-overlay"/>
<Primitive.Content className={cn('dialog-content', className)}
onOpenAutoFocus={() => {previousFocus.current = document.activeElement as HTMLElement;}}
onCloseAutoFocus={event => {
event.preventDefault();
if (!document.querySelector('[role="dialog"]') && previousFocus.current?.isConnected)
previousFocus.current.focus({preventScroll:true});
}} {...props}>
{children}
<Primitive.Close className="dialog-close" aria-label={closeLabel}><X size={18}/></Primitive.Close>
</Primitive.Content>
</Primitive.Portal>;
}
+12
View File
@@ -0,0 +1,12 @@
import {CheckCircle2, CircleAlert, Info, LoaderCircle} from 'lucide-react';
import {Toaster as Sonner, type ToasterProps} from 'sonner';
/** One accessible notification surface for native, protocol and UI operations. */
export function Toaster(props: ToasterProps) {
return <Sonner position="top-right" closeButton visibleToasts={2} gap={10}
offset={{top: 88, right: 24}} duration={4500}
icons={{success: <CheckCircle2 size={18}/>, error: <CircleAlert size={18}/>,
warning: <CircleAlert size={18}/>, info: <Info size={18}/>, loading: <LoaderCircle size={18} className="spin"/>}}
toastOptions={{classNames: {toast: 'app-toast', description: 'toast-description'}}}
{...props}/>;
}
+20
View File
@@ -0,0 +1,20 @@
import guide from '../../GUIDE.md?raw';
import type {Language} from './i18n';
/** The in-app manual and START-HERE.md use the same checked-in document. */
export function helpTopics(language: Language) {
const localized = language === 'zh' ? guide.split('## 中文')[1]?.split('## English')[0] : guide.split('## English')[1];
const parts = (localized || '').trim().split(/^### (.+)\r?$/m);
const sections = new Map<string, string>();
for (let i=1; i<parts.length; i+=2) sections.set(parts[i].trim(), parts[i+1].trim());
const zh = language === 'zh';
return [
{id:'start', title:zh ? '开始之前' : 'Before you start', markdown:parts[0]},
{id:'purpose', title:zh ? '选择安装方式' : 'Choose your purpose', markdown:sections.get(zh ? '选择用途' : 'Choose your purpose')},
{id:'storage', title:zh ? 'TF 卡与内置容量' : 'TF card and capacity', markdown:zh ? `### TF 卡\n\n${sections.get('TF 卡')}\n\n### 独立内置分区\n\n${sections.get('独立内置分区')}` : sections.get('Storage and capacity')},
{id:'reset', title:zh ? 'Android 重置后续装' : 'Resume after Android reset', markdown:sections.get(zh ? '加密 userdata:重置后自动续装' : 'Encrypted userdata and reset')},
{id:'recovery', title:zh ? '安装记录与失败恢复' : 'Records and recovery', markdown:sections.get(zh ? '暂停、关闭与失败恢复' : 'Recovery and results')},
{id:'faq', title:zh ? '连接与常见问题' : 'Connection and troubleshooting', markdown:sections.get(zh ? '连接与常见问题' : 'Connection and troubleshooting')},
].map(topic => ({...topic, markdown:topic.markdown || ''}));
}
+28
View File
@@ -0,0 +1,28 @@
export const helpStrings = {
zh: {
help:'帮助与使用指南', helpIntro:'离线可用。按主题查阅,也可以搜索型号、授权或续装问题。', close:'关闭帮助', closeGuide:'关闭新手引导',
search:'搜索使用指南', searchPlaceholder:'搜索,例如:USB、Magisk、续装…', topics:'指南主题', noResults:'没有找到相关内容,试试“授权”“安装记录”或“TF”。', results:'个相关主题',
guide:'新手引导', guideIntro:'先了解准备、安装选择和中途等待,再开始操作。', firstTime:'第一次使用?', firstTimeDesc:'先看三个步骤,了解安装前准备和重置后如何继续。',
replay:'重新查看新手引导', skip:'暂时跳过', next:'下一步', back:'上一步', finish:'开始使用', step:'第', of:'步,共 3 步',
introTitles:['准备设备和安装包','选择适合你的安装方式','等待、续装与保留备份'],
introBodies:[
['完整解压安装包,从根目录 OpenWrt-Installer.exe 启动,无需另装 Python、Node 或 Rust。','先备份需要保留的数据,使用可靠的数据线并保持设备供电。','在 Android 开启 USB 调试、允许电脑调试并准备好 root;连接多台设备时,必须明确选择目标设备。'],
['首次安装从“安装 OpenWrt”开始。TF 卡只格式化选定目标,不重新划卡;内置分区会先检查未分配空间。','核对最终计划里的机型、写入目标、Android 保留空间和数据影响。需要重置时,Android 用户数据会被清空。','已装好 OpenWrt 时可选择更新或临时启动;重装和有 F2FS 损坏风险的实验性镜像放在高级选项。'],
['首次离线分区准备可能需要数分钟,之后会自动重启。预期断线、Android 初始化和授权都是等待状态。','重置后完成 Android 初始化、开启 USB 调试并允许授权。已有 root 会直接使用;只有 root 不可用时才需要恢复 Magisk。','安装记录自动保存在电脑。关闭或重启后从“继续未完成的安装”恢复;换电脑前导出完整事务与备份。电脑记录和备份都丢失时,目前无法仅凭设备自动重建续装记录。'],
],
noAction:'本引导只作说明,不会操作设备。最终安装仍需单独确认。', currentHelp:'查看当前步骤帮助',
},
en: {
help:'Help and user guide', helpIntro:'Available offline. Browse a topic or search for connection, authorization or recovery help.', close:'Close help', closeGuide:'Close getting started',
search:'Search the user guide', searchPlaceholder:'Search: USB, Magisk, recovery…', topics:'Guide topics', noResults:'No matches. Try “authorization”, “records” or “TF”.', results:'matching topics',
guide:'Getting started', guideIntro:'Learn what to prepare, which path to choose and what to do while waiting.', firstTime:'First time here?', firstTimeDesc:'Three short steps cover preparation, installation choices and resuming after a reset.',
replay:'Replay getting started', skip:'Skip for now', next:'Next', back:'Previous', finish:'Start using the installer', step:'Step', of:'of 3',
introTitles:['Prepare your device and package','Choose an installation path','Wait, resume and keep backups'],
introBodies:[
['Extract the complete package and run OpenWrt-Installer.exe at its root. No separate Python, Node or Rust is required.','Back up the files you want to keep, use a reliable data cable and keep the device powered.','Enable USB debugging on Android, authorize this computer and have root ready. When several devices are connected, select the intended device explicitly.'],
['Use Install OpenWrt for a first installation. TF installation formats only the selected target without repartitioning the card. Internal installation checks unallocated space first.','Review the model, write target, retained Android space and data impact in the final plan. A required Android reset erases its user data.','For installed OpenWrt, choose update or a one-time boot. Reinstallation and the experimental image option, which can damage F2FS, live under Advanced options.'],
['The first offline preparation may take several minutes and then reboot automatically. Expected USB disconnects, Android setup and authorization are waiting states.','After a reset, complete Android setup, enable USB debugging and grant authorization. Working root is accepted immediately; restore Magisk only if root is unavailable.','Installation records are saved automatically on the computer. After closing or restarting, choose Continue an unfinished installation. Export the full transaction and backups before moving computers. If both records and backups are lost, this version cannot reconstruct a record from the device alone.'],
],
noAction:'This guide does not operate the device. Installation still requires a separate final confirmation.', currentHelp:'Help for this step',
},
};
+56
View File
@@ -0,0 +1,56 @@
export const strings = {
zh: {
copied:'日志已复制', exportedLog:'日志已导出', exportedBackup:'事务与备份已导出', imported:'恢复记录已导入', openedData:'事务目录已打开', inspected:'设备检查完成', refreshed:'设备列表已刷新', noDevices:'未发现设备,请连接 USB 并开启调试。', multipleDevices:'检测到多台设备,请明确选择本次操作的设备。', pauseRequested:'已请求暂停,将在安全边界生效。', dismiss:'关闭提示', notifications:'操作通知', deviceStates:{device:'已连接',unauthorized:'等待调试授权',offline:'离线'},
title:'OpenWrt 安装器', subtitle:'安装、更新与恢复', home:'开始', package:'安装包', choosePackage:'选择安装包目录', verify:'校验安装包', verified:'校验通过',
device:'设备', refresh:'刷新设备', select:'请选择设备', connect:'通过 USB 连接设备,开启调试并允许电脑访问。', inspect:'检查设备',
install:'安装 OpenWrt', installDesc:'选择 TF 卡或独立内置分区,逐步完成安装。', update:'更新 OpenWrt', updateDesc:'保留设置、已有容量和本机固件。',
resume:'继续未完成的安装', resumeDesc:'从电脑上的事务记录恢复,包括 Android 重置后的续装。', boot:'临时启动已安装的 OpenWrt', bootDesc:'仅修改 misc 中的试启动信息。默认启动设置保持原值。',
advanced:'高级选项', advancedDesc:'重装已有分区或使用实验性 userdata 镜像。', tf:'TF 卡', part:'独立内置分区', reinstall:'重装已有内置分区', image:'userdata 镜像',
experimental:'实验性功能:可能损坏 Android F2FS 文件系统。', size:'OpenWrt 分配容量(GiB)', grow:'使用全部已分配的 OpenWrt 分区容量', growHelp:'扩满所选分区。分配大小由上方容量决定。',
theme:'主题', system:'跟随系统', light:'浅色', dark:'深色', language:'语言', model:'实际型号', os:'当前系统', slot:'当前槽位', root:'Root 状态', ready:'已就绪', unavailable:'未就绪', unknown:'尚未读取',
plan:'查看安装计划', review:'确认安装计划', target:'写入目标', android:'Android 保留空间', allocation:'OpenWrt 分配空间', impact:'数据影响',
wipe:'Android 应用、账号、照片和内部存储将全部清空。请先备份个人数据。', preserve:'保留 Android 用户数据。', tfErase:'会格式化所选 TF 目标,卡上该分区的数据会被替换。不会重新划分 TF 卡。',
reinstallErase:'已有 OpenWrt 系统与设置会被替换,Android 用户数据保留。', imageImpact:'创建镜像,保留原有镜像备份。需额外安装临时空间。',
updateImpact:'保留设置、分区容量和本机固件;上传通过 SSH,设备端互斥锁保护提交。', bootImpact:'临时试启动;不挂载、不写入 OpenWrt 根分区。失败时由原启动策略回退。',
firstBoot:'首次启动会进行离线分区准备,可能需要数分钟,完成后设备会自动重启一次。',
accept:'我已核对设备、写入目标和数据影响,并已备份需要保留的文件。', start:'确认并开始', back:'返回', progress:'安装进度',
steps:['检查与计划','准备与备份','设备重启与授权','安装与校验','完成'],
running:'正在执行', waiting_user:'等待用户操作', waiting_device:'等待设备重连', failed:'操作失败', completed:'已完成', cancelled:'已暂停', readyStatus:'等待确认',
stages:{plan:'安装计划已就绪',prepare:'准备安装',backup:'备份 GPT、misc 与启动链',android_boot:'等待 Android 开机',android_setup:'请完成 Android 初始设置',usb_debugging:'请启用 USB 调试',debug_authorization:'请在设备上允许调试',magisk:'请安装或恢复 Magisk',root_permission:'请允许 root 请求',root_ready:'root 已就绪,继续安装',recheck:'复核分区与事务状态',transfer_install:'传输及安装系统',verify_capacity:'扩容与最终容量校验',openwrt_boot:'等待启动 OpenWrt',complete:'安装完成'},
waitingAndroid:'保持设备供电。进入 Android 后完成初始设置、开启开发者选项及 USB 调试,并允许此电脑调试。若 root 仍可用,会直接继续;否则恢复 Magisk 并允许 root 请求。这里没有等待时限。',
waitingOpenwrt:'需要时请手动重启设备。连接设备的 USB 网络或热点后继续验证;安装器不会修改电脑网卡、路由或自动连接热点。请保持此窗口,或暂停后从记录继续。',
pause:'在安全边界暂停', unsafe:'正在写入,请保持供电。暂停将在当前操作完成后生效。', closeBlocked:'任务仍在执行。请先在安全边界暂停,再关闭窗口。',
logs:'详细日志', copy:'复制', exportLog:'导出日志', exportBackup:'导出事务与备份', openData:'打开事务目录', import:'导入恢复目录',
noRecords:'没有可恢复的事务。若电脑记录丢失,请导入完整备份目录;设备标记不足以证明安装计划时,安装器会停止。', continue:'继续安装', retry:'复核并重试',
success:'OpenWrt 已安装并通过校验', successBoot:'OpenWrt 已临时启动', successUpdate:'OpenWrt 已更新并通过校验', actual:'实际文件系统容量', visit:'管理地址', next:'下一步', nextDesc:'打开管理地址,修改管理员与无线密码。备份与事务会保留在电脑上。',
host:'设备管理 IP / 主机名', password:'SSH root 密码(仅在内存中使用)', checkUpdate:'检查 OpenWrt', recommended:'推荐',
noBackend:'无法连接本地后端。请从完整解压后的安装包运行 OpenWrt-Installer.exe。', error:'操作未完成', elapsed:'阶段用时', bytes:'已传输', speed:'速度', packageHint:'请完整解压安装包;载荷校验通过后才能操作设备。',
},
en: {
copied:'Log copied', exportedLog:'Log exported', exportedBackup:'Transaction and backups exported', imported:'Recovery record imported', openedData:'Transaction folder opened', inspected:'Device inspection complete', refreshed:'Device list refreshed', noDevices:'No devices found. Connect USB and enable debugging.', multipleDevices:'Multiple devices found. Select the device for this operation.', pauseRequested:'Pause requested. It will take effect at a safe boundary.', dismiss:'Dismiss notification', notifications:'Operation notifications', deviceStates:{device:'Connected',unauthorized:'Awaiting debugging authorization',offline:'Offline'},
title:'OpenWrt Installer',subtitle:'Install, update and recover',home:'Start',package:'Package',choosePackage:'Choose package folder',verify:'Verify package',verified:'Verified',
device:'Device',refresh:'Refresh devices',select:'Select a device',connect:'Connect by USB, enable debugging and authorize this computer.',inspect:'Inspect device',
install:'Install OpenWrt',installDesc:'Install step by step on a TF card or an independent internal partition.',update:'Update OpenWrt',updateDesc:'Keep settings, existing capacity and device firmware.',
resume:'Continue an unfinished installation',resumeDesc:'Recover from a computer transaction, including after an Android reset.',boot:'Boot installed OpenWrt once',bootDesc:'Change only the trial selection in misc. Keep the existing boot default.',
advanced:'Advanced options',advancedDesc:'Reinstall an internal partition or use an experimental userdata image.',tf:'TF card',part:'Independent internal partition',reinstall:'Reinstall internal partition',image:'Userdata image',
experimental:'Experimental: may damage the Android F2FS filesystem.',size:'OpenWrt allocation (GiB)',grow:'Use all capacity allocated to the OpenWrt partition',growHelp:'Grow to fill the selected partition. The allocation above controls its size.',
theme:'Theme',system:'System',light:'Light',dark:'Dark',language:'Language',model:'Actual model',os:'Current system',slot:'Current slot',root:'Root status',ready:'Ready',unavailable:'Not ready',unknown:'Not read yet',
plan:'Review installation plan',review:'Confirm installation plan',target:'Write target',android:'Android retained space',allocation:'OpenWrt allocation',impact:'Data impact',
wipe:'All Android apps, accounts, photos and internal storage will be erased. Back up personal files first.',preserve:'Preserve Android user data.',tfErase:'Format the selected TF target and replace its data. The card is not repartitioned.',
reinstallErase:'Replace the installed OpenWrt system and settings. Preserve Android user data.',imageImpact:'Create an image and retain the previous image as a backup. Temporary staging space is also required.',
updateImpact:'Preserve settings, partition capacity and local firmware. Upload over SSH; a device upgrade lock protects commit.',bootImpact:'Trial boot only. Do not mount or write the OpenWrt root partition. Existing boot policy handles fallback.',
firstBoot:'The first boot performs offline partition preparation. This may take several minutes; the device will reboot automatically once it finishes.',
accept:'I checked the device, write target and data impact, and backed up the files I need.',start:'Confirm and start',back:'Back',progress:'Installation progress',steps:['Checks and plan','Prepare and back up','Restart and authorize','Install and verify','Complete'],
running:'Running',waiting_user:'Waiting for you',waiting_device:'Waiting for device',failed:'Failed',completed:'Completed',cancelled:'Paused',readyStatus:'Awaiting confirmation',
stages:{plan:'Installation plan ready',prepare:'Preparing installation',backup:'Backing up GPT, misc and boot chain',android_boot:'Waiting for Android to boot',android_setup:'Complete Android initial setup',usb_debugging:'Enable USB debugging',debug_authorization:'Allow debugging on the device',magisk:'Install or restore Magisk',root_permission:'Allow the root request',root_ready:'Root is ready; continuing installation',recheck:'Rechecking partitions and transaction',transfer_install:'Transferring and installing the system',verify_capacity:'Growing and verifying actual capacity',openwrt_boot:'Waiting for OpenWrt to start',complete:'Installation complete'},
waitingAndroid:'Keep power connected. Complete Android setup, enable developer options and USB debugging, then authorize this computer. Existing working root is accepted immediately; otherwise restore Magisk and grant root. There is no waiting deadline.',
waitingOpenwrt:'Reboot the device manually if needed. Connect to its USB network or hotspot for verification. The installer does not change network adapters or routes, or connect to hotspots. Keep this window open, or pause and resume from the record.',
pause:'Pause at a safe boundary',unsafe:'A write is in progress. Keep power connected. Pause takes effect after the current operation finishes.',closeBlocked:'A task is still active. Pause at a safe boundary before closing the window.',
logs:'Detailed log',copy:'Copy',exportLog:'Export log',exportBackup:'Export transaction and backups',openData:'Open transaction folder',import:'Import recovery folder',
noRecords:'No saved transactions. If computer records were lost, import a full backup folder. Insufficient device evidence stops installation.',continue:'Continue installation',retry:'Recheck and retry',
success:'OpenWrt installed and verified',successBoot:'OpenWrt started for this boot',successUpdate:'OpenWrt updated and verified',actual:'Actual filesystem capacity',visit:'Management address',next:'Next steps',nextDesc:'Open the management address and change administrator and wireless passwords. Backups and the transaction remain on this computer.',
host:'Device management IP / hostname',password:'SSH root password (held only in memory)',checkUpdate:'Inspect OpenWrt',recommended:'Recommended',
noBackend:'Cannot connect to the local backend. Run OpenWrt-Installer.exe from a fully extracted package.',error:'Operation incomplete',elapsed:'Stage elapsed',bytes:'Transferred',speed:'Speed',packageHint:'Extract the complete package. Payload verification is required before device operations.',
}
};
export type Language = keyof typeof strings;
+268
View File
@@ -0,0 +1,268 @@
import React, {lazy, Suspense, useCallback, useEffect, useRef, useState} from 'react';
import {createRoot} from 'react-dom/client';
import {invoke} from '@tauri-apps/api/core';
import {AnimatePresence, domAnimation, LazyMotion, m, MotionConfig, useReducedMotion} from 'motion/react';
import {toast} from 'sonner';
import {Toaster} from './components/ui/sonner';
import {ArrowRight, BookOpen, Check, CheckCircle2, ChevronDown, CircleAlert, CircleHelp, Copy, Download, FolderOpen, HardDrive, LoaderCircle, Monitor, Moon, Pause, RefreshCw, RotateCcw, Settings2, ShieldCheck, Smartphone, Sun, Upload, Usb} from 'lucide-react';
import {Button} from './components/ui/button';
import {helpStrings} from './help-i18n';
import {strings, type Language} from './i18n';
import {gib, native, request, stateGroup, subscribe, type Device, type Package, type Transaction, type Transfer} from './protocol';
import './style.css';
const HelpCenter = lazy(() => import('./components/help-center').then(module => ({default:module.HelpCenter})));
const GettingStarted = lazy(() => import('./components/help-center').then(module => ({default:module.GettingStarted})));
type View = 'home' | 'install' | 'update' | 'resume' | 'boot' | 'advanced' | 'plan' | 'progress';
function App() {
const [lang, setLang] = useState<Language>(localStorage.getItem('language') === 'en' ? 'en' : 'zh');
const [theme, setTheme] = useState<'light' | 'dark' | 'system'>(() => {
const saved = localStorage.getItem('theme');
return saved === 'light' || saved === 'dark' ? saved : 'system';
});
const t = strings[lang];
const help = helpStrings[lang];
const [helpOpen, setHelpOpen] = useState(false);
const [guideOpen, setGuideOpen] = useState(false);
const [helpTopic, setHelpTopic] = useState('start');
const [view, setView] = useState<View>('home');
const [pkg, setPkg] = useState<Package>();
const [path, setPath] = useState('');
const [devices, setDevices] = useState<Device[]>([]);
const [serial, setSerial] = useState('');
const [device, setDevice] = useState<Device>();
const [records, setRecords] = useState<Transaction[]>([]);
const [tx, setTx] = useState<Transaction>();
const [transfer, setTransfer] = useState<Transfer>();
const [method, setMethod] = useState('part');
const [size, setSize] = useState('4');
const [grow, setGrow] = useState(true);
const [host, setHost] = useState('192.168.9.1');
const [password, setPassword] = useState('');
const [accepted, setAccepted] = useState(false);
const [busy, setBusy] = useState(false);
const [logs, setLogs] = useState<string[]>([]);
const [logOpen, setLogOpen] = useState(false);
const [elapsed, setElapsed] = useState(0);
const [since, setSince] = useState(Date.now());
const pending = useRef(0);
const lastTransaction = useRef('');
const pageRef = useRef<HTMLDivElement>(null);
const reduceMotion = useReducedMotion();
const append = useCallback((text: string) => setLogs(old => [...old.slice(-499), `${new Date().toLocaleTimeString()} ${text}`]), []);
const reportError = useCallback((message: string) => {
toast.error(t.error, {id: 'operation-error', description: message, duration: Infinity});
append(message);
}, [append, t.error]);
const acceptTransaction = useCallback((next: Transaction, announce = true) => {
const key = `${next.id}:${next.stage}:${next.status}:${next.error?.message || ''}`;
if (key !== lastTransaction.current) {
lastTransaction.current = key;
setSince(Date.now()); setTransfer(undefined);
const label = t.stages[next.stage as keyof typeof t.stages] || next.stage;
append(label);
if (announce) {
const options = {id: 'installation-status', description: next.error?.message ||
(next.status === 'ready' ? t.readyStatus : (t as unknown as Record<string, string>)[next.status]), duration: next.status === 'failed' ? Infinity : 5000};
if (next.status === 'failed') toast.error(label, options);
else if (next.status === 'completed') toast.success(next.choices.method === 'boot' ? t.successBoot : next.choices.method === 'update' ? t.successUpdate : t.success, options);
else if (next.status.startsWith('waiting')) toast.info(label, options);
else toast.message(label, options);
}
}
setTx(next);
}, [append, t]);
const task = async <T,>(fn: () => Promise<T>, success?: string): Promise<T | undefined> => {
pending.current++; setBusy(true);
toast.dismiss('operation-error');
const notice = success ? toast.loading(t.running) : undefined;
try {
const value = await fn();
if (notice !== undefined) {
if (value === false) toast.dismiss(notice);
else toast.success(success, {id:notice});
}
return value;
} catch (e) {if (notice !== undefined) toast.dismiss(notice); reportError(String(e)); return undefined;}
finally {pending.current--; setBusy(pending.current > 0);}
};
useEffect(() => {
const query = matchMedia('(prefers-color-scheme: dark)');
const update = () => document.documentElement.classList.toggle('dark', theme === 'dark' || theme === 'system' && query.matches);
update(); query.addEventListener('change', update); localStorage.setItem('theme', theme);
return () => query.removeEventListener('change', update);
}, [theme]);
useEffect(() => {localStorage.setItem('language', lang); document.documentElement.lang = lang === 'zh' ? 'zh-CN' : 'en';}, [lang]);
useEffect(() => {pageRef.current?.querySelector<HTMLElement>('h1')?.focus({preventScroll: true});}, [view]);
useEffect(() => {
const timer = setInterval(() => setElapsed(Math.floor((Date.now() - since)/1000)), 1000);
return () => clearInterval(timer);
}, [since]);
useEffect(() => {
let dispose: (() => void) | undefined;
let cancelled = false;
subscribe(event => {
if (event.type === 'transaction') {
const next = event.data as Transaction;
acceptTransaction(next);
} else if (event.type === 'transfer') setTransfer(event.data as Transfer);
else if (event.type === 'log') append((event.data as {message: string}).message);
else if (event.type === 'close_blocked') reportError(t.closeBlocked);
else if (event.type === 'backend_exit') reportError(t.noBackend);
}).then(stop => {if (cancelled) stop(); else dispose = stop;}).catch(e => {if (!cancelled) reportError(String(e));});
return () => {cancelled = true; dispose?.();};
}, [append, acceptTransaction, reportError, t]);
useEffect(() => {
task(async () => {
const hello = await request<{package_path: string; transactions: Transaction[]}>('hello');
setPath(hello.package_path); setRecords(hello.transactions);
if (!hello.transactions.length && !localStorage.getItem('onboarding-v1')) setGuideOpen(true);
});
}, []);
const verify = async (folder = path) => {
setPkg(undefined); setDevice(undefined);
const p = await task(() => request<Package>('package', {path: folder}), t.verified);
if (p) {setPkg(p); setPath(p.path); setHost(p.adapter === 'e5' ? '192.168.9.1' : '192.168.77.1'); append(t.verified);}
};
const refresh = async () => {
const values = await task(() => request<Device[]>('devices'));
if (values) {
setDevices(values);
if (values.length === 1) {setSerial(values[0].serial); if (values[0].serial !== serial) setDevice(undefined);}
else if (!values.some(d => d.serial === serial)) {setSerial(''); setDevice(undefined);}
if (!values.length) toast.info(t.noDevices);
else if (values.length > 1) toast.info(t.multipleDevices, {id:'device-selection'});
else toast.success(t.refreshed);
}
};
const inspect = async () => {
setDevice(undefined);
const value = await task(() => request<Device>('probe', {serial, method: view === 'boot' ? 'boot' : method}), t.inspected);
if (value) {setDevice(value); if (value.existing && view === 'install') setMethod('reinstall'); else if (value.tf && view === 'install') setMethod('tf');}
};
const navigate = async (next: View) => {
setView(next); setAccepted(false); setTransfer(undefined); setDevice(undefined);
if (next === 'resume') {const values = await task(() => request<Transaction[]>('list')); if (values) setRecords(values);}
if (['install','advanced','boot'].includes(next)) {if (next === 'boot') setMethod('boot'); else setMethod('part'); if (pkg) await refresh();}
if (next === 'update') setMethod('update');
};
const plan = async () => {
const value = await task(() => request<Transaction>('plan', {serial, choices: {method, size_gib: Number(size), grow, host}, password}));
if (value) {acceptTransaction(value); setView('plan'); setAccepted(false);}
};
const start = async (command: string, record = tx) => {
if (!record) return;
const value = await task(() => request<Transaction>(command, {transaction: record.id, confirmed: command === 'start', password, path: pkg?.path || path}));
if (value) {acceptTransaction(value); setView('progress'); setSince(Date.now()); setTransfer(undefined);}
};
const exportBackup = async () => {
if (!tx) return;
await task(async () => {const target = await native('save_backup');
if (!target) return false;
return request('export', {transaction: tx.id, path: target});
}, t.exportedBackup);
};
const exportLogs = async () => {
await task(async () => {const target = await native('save_log');
if (!target) return false;
return invoke('write_log', {path: target, text: logs.join('\n')});
}, t.exportedLog);
};
const choosePackage = async () => {
const folder = await task(() => native('pick_package'));
if (folder) {setPath(folder); await verify(folder);}
};
const openData = () => task(() => native('open_data'), t.openedData);
const statusLabel = (status: string) => status === 'ready' ? t.readyStatus : (t as unknown as Record<string, string>)[status] || status;
const stageLabel = (stage: string) => t.stages[stage as keyof typeof t.stages] || stage;
const current = stateGroup(['plan','progress'].includes(view) ? tx?.stage || 'plan' : 'plan');
const active = tx && ['running', 'waiting_device', 'waiting_user'].includes(tx.status);
const openHelp = useCallback(() => {
setHelpTopic(view === 'resume' || view === 'progress' && (['failed','completed'].includes(tx?.status || '') || tx?.stage === 'openwrt_boot') ? 'recovery' : view === 'progress' && ['android_boot','android_setup'].includes(tx?.stage || '') ? 'reset' : view === 'progress' && tx?.status.startsWith('waiting') ? 'faq' : view === 'plan' ? 'storage' : view === 'home' ? 'start' : 'purpose');
setGuideOpen(false); setHelpOpen(true);
}, [view, tx?.status, tx?.stage]);
const showGuide = () => {setHelpOpen(false); setGuideOpen(true);};
const changeGuide = (open:boolean) => {
setGuideOpen(open);
if (!open) localStorage.setItem('onboarding-v1','seen');
};
useEffect(() => {
const onKey = (event:KeyboardEvent) => {
if (event.key === 'F1') {event.preventDefault(); if (!guideOpen && !helpOpen) openHelp();}
};
window.addEventListener('keydown',onKey);
return () => window.removeEventListener('keydown',onKey);
}, [openHelp, guideOpen, helpOpen]);
const purposes = [
{id:'install', icon:Download, title:t.install, description:t.installDesc},
{id:'update', icon:RefreshCw, title:t.update, description:t.updateDesc},
{id:'resume', icon:RotateCcw, title:t.resume, description:t.resumeDesc},
{id:'boot', icon:Usb, title:t.boot, description:t.bootDesc},
{id:'advanced', icon:Settings2, title:t.advanced, description:t.advancedDesc},
] as const;
const impact = tx?.plan.wipe ? t.wipe : tx?.choices.method === 'tf' ? t.tfErase : tx?.choices.method === 'reinstall' ? t.reinstallErase : tx?.choices.method === 'image' ? t.imageImpact : tx?.choices.method === 'update' ? t.updateImpact : tx?.choices.method === 'boot' ? t.bootImpact : t.preserve;
return <div className="app-shell">
<header><div className="brand"><div className="brand-icon"><HardDrive size={20}/></div><div><strong>{t.title}</strong><small>{t.subtitle}</small></div></div>
<div className="preferences"><label className="sr-only" htmlFor="language">{t.language}</label><select id="language" value={lang} onChange={e => setLang(e.target.value as Language)}><option value="zh">中文</option><option value="en">English</option></select>
{theme === 'dark' ? <Moon size={16}/> : theme === 'light' ? <Sun size={16}/> : <Monitor size={16}/>}
<label className="sr-only" htmlFor="theme">{t.theme}</label><select id="theme" value={theme} onChange={e => setTheme(e.target.value as typeof theme)}><option value="system">{t.system}</option><option value="light">{t.light}</option><option value="dark">{t.dark}</option></select><Button variant="ghost" className="help-trigger" onClick={openHelp} aria-label={help.help} title={`${help.help} (F1)`}><CircleHelp size={18}/><span>{help.help}</span></Button></div>
</header>
<div className="workspace"><aside><button className="nav-home" disabled={busy || !!active} onClick={() => navigate('home')}><HardDrive size={17}/>{t.home}</button>
<ol className="stepper">{t.steps.map((name, i) => <li key={name} className={current === i ? 'current' : current > i ? 'done' : ''}><span>{current > i ? <Check size={14}/> : i+1}</span><div>{name}</div></li>)}</ol>
<div className="sidebar-bottom"><div className="sidebar-note"><ShieldCheck size={19}/><p>{t.packageHint}</p></div>
<Button variant="ghost" className="data-folder" disabled={busy} onClick={openData}><FolderOpen size={16}/>{t.openData}</Button></div>
</aside><main aria-busy={busy}>
<div className="busy-track" aria-hidden="true">{busy && <m.div animate={{opacity:reduceMotion ? 1 : [.4,1,.4]}} transition={{duration:1.3,repeat:reduceMotion ? 0 : Infinity}}/>}</div>
<AnimatePresence initial={false} mode="wait" onExitComplete={() => requestAnimationFrame(() => pageRef.current?.querySelector<HTMLElement>('h1')?.focus({preventScroll:true}))}>
<m.div key={view} ref={pageRef} className="page" initial={{opacity:0, y:reduceMotion ? 0 : 8}} animate={{opacity:1,y:0}} exit={{opacity:0}} transition={{duration:reduceMotion ? 0 : 0.16, ease:'easeOut'}}>
{view === 'home' && <><div className="eyebrow">OPENWRT · DESKTOP INSTALLER</div><h1 tabIndex={-1}>{lang === 'zh' ? '你想如何使用 OpenWrt?' : 'What would you like to do?'}</h1><p className="intro">{t.connect}</p>
<div className="guide-callout"><BookOpen size={20}/><div><strong>{help.firstTime}</strong><p>{help.firstTimeDesc}</p></div><Button variant="outline" onClick={showGuide}>{help.guide}<ArrowRight size={15}/></Button></div>
<div className="purpose-list scroll-area">{purposes.map(({id, icon:Icon, title, description}, index) => <m.button initial={{opacity:0,y:reduceMotion ? 0 : 6}} animate={{opacity:1,y:0}} transition={{delay:reduceMotion ? 0 : index*0.025,duration:0.18}} whileHover={reduceMotion ? undefined : {x:3}} whileTap={reduceMotion ? undefined : {scale:0.992}} key={id} disabled={busy} onClick={() => navigate(id)} className="purpose"><div className="purpose-icon"><Icon size={21}/></div><div><h2>{title}</h2><p>{description}</p></div><ArrowRight size={18}/></m.button>)}</div>
</>}
{['install','update','boot','advanced'].includes(view) && <><h1 tabIndex={-1}>{purposes.find(p => p.id === view)?.title}</h1><p className="intro">{purposes.find(p => p.id === view)?.description}</p>
<div className="page-scroll scroll-area"><section><div className="section-title"><h2>{t.package}</h2>{pkg && <span className="badge"><Check size={13}/>{t.verified}</span>}</div>
<div className="package-row"><div className="file-path" title={path}>{pkg?.name || path || t.choosePackage}</div><Button variant="outline" disabled={busy} onClick={choosePackage}><FolderOpen size={16}/>{t.choosePackage}</Button><Button disabled={busy || !path} onClick={() => verify()}>{t.verify}</Button></div></section>
{view === 'update' ? <section><h2>{t.device}</h2><div className="form-grid"><label>{t.host}<input disabled={busy} value={host} onChange={e => setHost(e.target.value)} autoComplete="off"/></label><label>{t.password}<input disabled={busy} type="password" value={password} onChange={e => setPassword(e.target.value)} autoComplete="off"/></label></div><Button variant="outline" disabled={busy || !pkg} onClick={async () => {setDevice(undefined); const d = await task(() => request<Device>('probe_update', {host, password}), t.inspected); if (d) setDevice(d);}}>{t.checkUpdate}</Button></section> : <section><div className="section-title"><h2>{t.device}</h2><Button variant="ghost" disabled={!pkg || busy} onClick={refresh}><RefreshCw size={15}/>{t.refresh}</Button></div><div className="device-select"><Smartphone size={18}/><select disabled={busy} aria-label={t.select} value={serial} onChange={e => {setSerial(e.target.value); setDevice(undefined);}}><option value="">{t.select}</option>{devices.map(d => <option key={d.serial} value={d.serial}>{d.label} · ••••{d.serial.slice(-4)} · {t.deviceStates[d.state as keyof typeof t.deviceStates] || d.state}</option>)}</select><Button variant="outline" disabled={!serial || !pkg || busy} onClick={inspect}>{t.inspect}</Button></div></section>}
{view === 'boot' && <section><h2>{t.visit}</h2><div className="form-grid"><label>{t.host}<input disabled={busy} value={host} onChange={e => setHost(e.target.value)} autoComplete="off"/></label><label>{t.password}<input disabled={busy} type="password" value={password} onChange={e => setPassword(e.target.value)} autoComplete="off"/></label></div></section>}
{device && <div className="device-card"><div><small>{t.model}</small><strong>{device.model || t.unknown}</strong></div><div><small>{t.os}</small><strong>{device.system || t.unknown}</strong></div><div><small>{t.slot}</small><strong>{device.slot || t.unknown}</strong></div><div><small>{t.root}</small><strong className={device.root ? 'good-text' : ''}>{device.root ? t.ready : t.unavailable}</strong></div></div>}
{device?.readiness && device.readiness !== 'ready' && <div className="alert"><CircleAlert size={19}/><div><strong>{stageLabel(device.readiness)}</strong><p>{t.waitingAndroid}</p></div></div>}
{view !== 'update' && view !== 'boot' && <section><h2>{t.install}</h2><div className="method-options" role="group" aria-label={t.install}>{(view === 'advanced' ? ['reinstall','image'] : device?.existing ? ['reinstall'] : ['tf','part']).map(m => <button disabled={busy} key={m} aria-pressed={method === m} className={method === m ? 'selected' : ''} onClick={() => setMethod(m)}>{m === 'tf' ? <Usb size={17}/> : <HardDrive size={17}/>}{(t as unknown as Record<string,string>)[m]}{(m === 'tf' && device?.tf || m === 'reinstall' && device?.existing) && <span>{t.recommended}</span>}</button>)}</div>
{method === 'image' && <div className="alert danger"><CircleAlert size={18}/><strong>{t.experimental}</strong></div>}
{['part','image'].includes(method) && <label className="size-field">{t.size}<input disabled={busy} type="number" min="2" step="0.25" value={size} onChange={e => setSize(e.target.value)}/></label>}
{['part','reinstall'].includes(method) && <label className="checkbox-label"><input disabled={busy} type="checkbox" checked={grow} onChange={e => setGrow(e.target.checked)}/><div>{t.grow}<small>{t.growHelp}</small></div></label>}
</section>}
</div><div className="actions"><Button disabled={busy} variant="ghost" onClick={() => navigate('home')}>{t.back}</Button><Button disabled={busy || !pkg || !device?.root} onClick={plan}>{t.plan}<ArrowRight size={16}/></Button></div>
</>}
{view === 'plan' && tx && <><div className="eyebrow">{t.review}</div><h1 tabIndex={-1}>{tx.device.model}</h1><p className="intro">{tx.package.name} · ••••{tx.device.serial.slice(-4)}</p><div className="page-scroll scroll-area"><section><dl className="plan-list"><div><dt>{t.target}</dt><dd>{tx.plan.target}</dd></div><div><dt>{t.android}</dt><dd>{gib(tx.plan.android_bytes)}</dd></div><div><dt>{t.allocation}</dt><dd>{tx.choices.method === 'boot' ? '—' : gib(tx.plan.openwrt_bytes)}</dd></div><div><dt>{t.grow}</dt><dd>{tx.plan.grow ? <Check size={17}/> : '—'}</dd></div></dl></section>
<div className={'alert ' + (tx.plan.wipe || tx.plan.experimental ? 'danger' : '')}><CircleAlert size={20}/><div><strong>{t.impact}</strong><p>{impact}</p>{tx.plan.experimental && <p>{t.experimental}</p>}</div></div>
{(tx.plan.offline || tx.plan.two_stage) && <div className="alert"><RefreshCw size={20}/><p>{t.firstBoot}</p></div>}
</div><label className="checkbox-label confirmation"><input disabled={busy} type="checkbox" checked={accepted} onChange={e => setAccepted(e.target.checked)}/>{t.accept}</label>
<div className="actions"><Button disabled={busy} variant="outline" onClick={() => navigate('install')}>{t.back}</Button><Button variant={tx.plan.wipe ? 'destructive' : 'default'} disabled={!accepted || busy} onClick={() => start('start')}>{t.start}<ArrowRight size={16}/></Button></div>
</>}
{view === 'resume' && <><h1 tabIndex={-1}>{t.resume}</h1><p className="intro">{t.resumeDesc}</p><div className="resume-tools"><Button variant="outline" disabled={busy} onClick={async () => {const folder = await task(() => native('pick_recovery')); if (folder) {const value = await task(() => request<Transaction>('import', {path: folder}), t.imported); if (value) setRecords(old => [value, ...old.filter(r => r.id !== value.id)]);}}}><Upload size={16}/>{t.import}</Button><Button variant="outline" disabled={busy} onClick={choosePackage}><FolderOpen size={16}/>{t.choosePackage}</Button></div>
<label className="resume-password"><span>{t.password}</span><input disabled={busy} type="password" value={password} onChange={e => setPassword(e.target.value)} autoComplete="off"/></label>
<div className="records-list scroll-area">{!records.length && <p className="empty-state">{t.noRecords}</p>}{records.map(r => <section className="record" key={r.id}><div><h2>{r.device.model}</h2><p>{stageLabel(r.stage)} · {statusLabel(r.status)}</p><small>{new Date(r.updated*1000).toLocaleString()} · {r.id.slice(0,8)}</small></div><Button disabled={busy} onClick={() => start('resume', r)}>{t.continue}<ArrowRight size={16}/></Button></section>)}</div>
</>}
{view === 'progress' && tx && <><div className="eyebrow">{t.progress} · {tx.device.model}</div><h1 tabIndex={-1}>{tx.status === 'completed' ? tx.choices.method === 'boot' ? t.successBoot : tx.choices.method === 'update' ? t.successUpdate : t.success : stageLabel(tx.stage)}</h1><div className="status-line"><span className={'status-dot '+tx.status}/><span>{statusLabel(tx.status)}</span><span className="elapsed">{t.elapsed} {elapsed}s</span></div>
<div className="page-scroll scroll-area">{tx.status === 'completed' ? <section className="success-panel"><m.div className="success-icon" initial={{opacity:0,scale:reduceMotion ? 1 : .9}} animate={{opacity:1,scale:1}} transition={{duration:reduceMotion ? 0 : .24}}><CheckCircle2 size={42} className="good-text"/></m.div><dl className="plan-list"><div><dt>{t.actual}</dt><dd>{gib(tx.result?.filesystem_bytes)}</dd></div><div><dt>{t.visit}</dt><dd>{tx.result?.url}</dd></div></dl><h2>{t.next}</h2><p>{t.nextDesc}</p></section> : <>
<section className="activity"><m.div key={tx.stage+tx.status} className="activity-heading" initial={{opacity:reduceMotion ? 1 : 0,y:reduceMotion ? 0 : 4}} animate={{opacity:1,y:0}} transition={{duration:reduceMotion ? 0 : .18}}>{tx.status === 'failed' ? <CircleAlert size={28}/> : tx.status === 'running' ? <LoaderCircle size={28} className="spin"/> : tx.status.startsWith('waiting') ? <Smartphone size={28}/> : <Pause size={28}/>}<div><h2>{stageLabel(tx.stage)}</h2><p>{tx.package.name}</p></div></m.div>
{transfer && tx.status === 'running' && <div className="transfer"><div><span>{transfer.name}</span><span>{Math.floor(transfer.bytes/transfer.total*100)}%</span></div><progress value={transfer.bytes} max={transfer.total}/><small>{t.bytes}: {gib(transfer.bytes)} / {gib(transfer.total)} · {t.speed}: {(transfer.bytes_per_second/1048576).toFixed(1)} MiB/s</small></div>}
{tx.status.startsWith('waiting') && <><p className="waiting-guidance">{tx.stage === 'openwrt_boot' ? t.waitingOpenwrt : t.waitingAndroid}</p><Button variant="ghost" className="context-help" onClick={openHelp}><CircleHelp size={16}/>{help.currentHelp}</Button></>}
{tx.unsafe && <div className="alert danger"><ShieldCheck size={19}/><p>{t.unsafe}</p></div>}
{tx.error && <div className="alert danger"><CircleAlert size={20}/><p>{tx.error.message}</p></div>}
</section></>} </div>{tx.status !== 'completed' && <div className="actions">{active ? <Button variant="outline" disabled={busy} onClick={() => task(() => request('cancel'), t.pauseRequested)}><Pause size={16}/>{t.pause}</Button> : <Button disabled={busy || tx.error?.retryable === false} onClick={() => start('retry')}>{t.retry}<RotateCcw size={16}/></Button>}</div>
}
<div className="backup-actions"><Button disabled={busy} variant="outline" onClick={exportBackup}><Download size={16}/>{t.exportBackup}</Button><Button disabled={busy} variant="ghost" onClick={openData}><FolderOpen size={16}/>{t.openData}</Button></div>
</>}
</m.div></AnimatePresence>
<div className="log-panel"><button className="log-toggle" aria-expanded={logOpen} aria-controls="installation-log" onClick={() => setLogOpen(!logOpen)}><ChevronDown size={14}/>{t.logs}<span>{logs.length}</span></button>
<AnimatePresence initial={false}>{logOpen && <m.div id="installation-log" className="log-content" initial={{height:0,opacity:0}} animate={{height:'auto',opacity:1}} exit={{height:0,opacity:0}} transition={{duration:reduceMotion ? 0 : .18}}><div className="log-inner"><div className="log-actions"><Button variant="ghost" disabled={busy || !logs.length} onClick={() => task(() => navigator.clipboard.writeText(logs.join('\n')), t.copied)}><Copy size={14}/>{t.copy}</Button><Button variant="ghost" disabled={busy || !logs.length} onClick={exportLogs}><Download size={14}/>{t.exportLog}</Button></div><pre tabIndex={0} aria-label={t.logs}>{logs.join('\n') || '—'}</pre></div></m.div>}</AnimatePresence>
</div>
</main></div><footer><span><ShieldCheck size={13}/>OpenWrt Installer · v1.0</span><span>USB / SSH · {pkg?.profile || '—'}</span></footer>
<Suspense fallback={<div className="help-loading" role="status"><LoaderCircle size={17} className="spin"/>{t.running}</div>}>{helpOpen && <HelpCenter language={lang} open={helpOpen} onOpenChange={setHelpOpen} initialTopic={helpTopic} onGuide={showGuide}/>}
{guideOpen && <GettingStarted language={lang} open={guideOpen} onOpenChange={changeGuide}/>}</Suspense>
<Toaster theme={theme} containerAriaLabel={t.notifications} toastOptions={{closeButtonAriaLabel:t.dismiss, classNames:{toast:"app-toast",description:"toast-description"}}}/>
</div>;
}
createRoot(document.getElementById('root')!).render(<React.StrictMode><MotionConfig reducedMotion="user"><LazyMotion features={domAnimation} strict><App/></LazyMotion></MotionConfig></React.StrictMode>);
+24
View File
@@ -0,0 +1,24 @@
import { invoke } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event';
export interface Device {serial: string; model?: string; label?: string; state?: string; system?: string; slot?: string; root?: boolean; readiness?: string; encrypted?: boolean; existing?: boolean; tf?: string; profile?: string; free_bytes?: number; userdata_bytes?: number}
export interface Package {path: string; name: string; adapter: string; profile: string; kernel: string}
export interface Transaction {
id: string; status: string; stage: string; device: Device; package: Package;
choices: {method: string}; plan: {wipe: boolean; two_stage: boolean; offline?: boolean; openwrt_bytes: number; android_bytes?: number; target: string; grow?: boolean; experimental?: boolean; gap_start?: number};
completed: string[]; unsafe: boolean; updated: number;
details?: {host?: string}; error?: {message: string; retryable: boolean; code: string};
result?: {filesystem_bytes: number; url: string; backup_directory: string; temporary: boolean};
}
export interface Transfer {name: string; bytes: number; total: number; bytes_per_second: number}
export interface BackendEvent {type: string; data: unknown}
export const request = <T = unknown>(command: string, params: Record<string, unknown> = {}) => invoke<T>('backend_request', {command, params});
export const subscribe = (handler: (event: BackendEvent) => void) => listen<BackendEvent>('backend', event => handler(event.payload));
export const native = <T = string | null>(command: string) => invoke<T>(command);
export const gib = (bytes = 0) => (bytes / 1073741824).toFixed(2) + ' GiB';
export function stateGroup(stage: string): number {
if (['plan', 'package', 'device', 'environment'].includes(stage)) return 0;
if (['backup', 'prepare'].includes(stage)) return 1;
if (['android_boot', 'android_setup', 'usb_debugging', 'debug_authorization', 'magisk', 'root_permission', 'root_ready', 'recheck'].includes(stage)) return 2;
if (['transfer_install', 'verify_capacity', 'openwrt_boot'].includes(stage)) return 3;
return 4;
}
+264
View File
@@ -0,0 +1,264 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
:root {--background:210 20% 98%;--foreground:222 30% 14%;--card:0 0% 100%;--muted:214 20% 94%;--muted-foreground:215 14% 40%;--border:214 20% 86%;--primary:173 80% 25%;--primary-foreground:0 0% 100%;--destructive:0 70% 40%;color-scheme:light;}
.dark {--background:222 25% 9%;--foreground:210 20% 94%;--card:222 22% 12%;--muted:220 20% 18%;--muted-foreground:215 15% 68%;--border:220 18% 26%;--primary:170 59% 59%;--primary-foreground:222 30% 10%;--destructive:0 68% 42%;color-scheme:dark;}
* {@apply border-border;}
body {@apply bg-background text-foreground; margin:0;font-family:'Segoe UI','Microsoft YaHei',sans-serif;font-size:14px;}
button,input,select{font:inherit;}
button{cursor:pointer;}
button:disabled{cursor:default;}
input:not([type=checkbox]),select{@apply bg-card border rounded-md text-foreground;min-height:38px;padding:7px 10px;}
input:focus-visible,select:focus-visible,summary:focus-visible{outline:2px solid hsl(var(--primary));outline-offset:3px;}
p{line-height:1.75;}
h1{font-size:27px;line-height:1.4;font-weight:650;letter-spacing:-.5px;margin:8px 0;}
h2{font-weight:600;font-size:15px;}
small{@apply text-muted-foreground;}
input[type=checkbox]{width:17px;height:17px;accent-color:hsl(var(--primary));flex-shrink:0;}
}
.app-shell{width:100%;max-width:1440px;height:100dvh;min-height:0;overflow:hidden;margin:auto;display:flex;flex-direction:column;}
header{height:76px;flex-shrink:0;display:flex;align-items:center;justify-content:space-between;padding:0 32px;border-bottom:1px solid hsl(var(--border));background:hsl(var(--card));}
.brand{display:flex;gap:12px;align-items:center;}
.brand-icon{background:hsl(var(--primary));color:hsl(var(--primary-foreground));border-radius:11px;padding:11px;}
.brand strong{font-size:17px;}
.brand small{display:block;font-size:12px;margin-top:3px;}
.preferences{display:flex;gap:8px;align-items:center;}
.preferences select{border:none;font-size:12px;}
.workspace{display:grid;grid-template-columns:224px minmax(0,1fr);flex:1;min-height:0;overflow:hidden;}
aside{padding:24px 18px;min-height:0;border-right:1px solid hsl(var(--border));display:flex;flex-direction:column;gap:20px;}
.nav-home{display:flex;gap:10px;align-items:center;padding:11px 14px;color:hsl(var(--primary));background:hsl(var(--primary)/.08);border-radius:8px;text-align:left;font-weight:600;}
.stepper{display:flex;flex-direction:column;gap:0;margin:0 8px;}
.stepper li{display:flex;gap:12px;align-items:center;position:relative;min-height:50px;color:hsl(var(--muted-foreground));font-size:13px;}
.stepper li>span{width:25px;height:25px;display:flex;align-items:center;justify-content:center;border:1px solid hsl(var(--border));border-radius:50%;background:hsl(var(--background));font-size:11px;z-index:1;}
.stepper li:not(:last-child):after{content:'';position:absolute;top:37px;left:12px;height:26px;border-left:1px solid hsl(var(--border));}
.stepper .current{color:hsl(var(--foreground));font-weight:600;}
.stepper .current>span{border-color:hsl(var(--primary));background:hsl(var(--primary));color:hsl(var(--primary-foreground));}
.stepper .done>span{color:hsl(var(--primary));border-color:hsl(var(--primary));}
.sidebar-note{display:flex;gap:8px;color:hsl(var(--muted-foreground));font-size:12px;margin:0 4px 14px;}
.sidebar-note svg{flex-shrink:0;}
.sidebar-note p{line-height:1.7;}
.data-folder{width:100%;font-size:12px;padding:0 5px;}
main{position:relative;display:flex;flex-direction:column;padding:28px 36px 18px;min-width:0;min-height:0;overflow:hidden;max-width:100%;gap:0;}
.eyebrow{color:hsl(var(--primary));font-size:11px;letter-spacing:1.3px;font-weight:600;}
.intro{flex-shrink:0;color:hsl(var(--muted-foreground));margin:8px 0 22px;max-width:650px;}
.purpose-list{flex:1;min-height:0;border-top:1px solid hsl(var(--border));}
.purpose{display:flex;align-items:center;gap:18px;width:100%;text-align:left;padding:18px 7px;border-bottom:1px solid hsl(var(--border));}
.purpose:hover{background:hsl(var(--muted)/.6);}
.purpose-icon{padding:13px;border-radius:10px;color:hsl(var(--primary));background:hsl(var(--primary)/.08);}
.purpose>div:nth-child(2){flex:1;}
.purpose p{font-size:12px;margin-top:5px;color:hsl(var(--muted-foreground));}
.purpose>svg{color:hsl(var(--muted-foreground));}
.page section{border:1px solid hsl(var(--border));border-radius:12px;background:hsl(var(--card));padding:20px;margin:16px 0;}
.section-title{display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;}
.section-title h2{margin:0;}
.badge{display:flex;align-items:center;gap:5px;background:hsl(var(--primary)/.1);color:hsl(var(--primary));padding:4px 7px;border-radius:5px;font-size:11px;}
.package-row{display:flex;gap:8px;flex-wrap:wrap;align-items:center;}
.file-path{color:hsl(var(--muted-foreground));font-size:12px;flex:1;min-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding-bottom:7px;}
.device-select{display:flex;align-items:center;gap:10px;}
.device-select select{flex:1;min-width:0;}
.device-card{display:grid;grid-template-columns:1.4fr 1fr .7fr 1fr;padding:14px 5px;gap:18px;}
.device-card small,.device-card strong{display:block;}
.device-card small{font-size:11px;margin-bottom:7px;}
.device-card strong{font-size:13px;font-weight:600;}
.good-text{color:hsl(var(--primary));}
.method-options{display:flex;gap:10px;margin:15px 0;flex-wrap:wrap;}
.method-options button{display:flex;align-items:center;gap:8px;border:1px solid hsl(var(--border));padding:12px;border-radius:8px;font-size:12px;}
.method-options button.selected{border-color:hsl(var(--primary));background:hsl(var(--primary)/.06);}
.method-options span{font-size:10px;color:hsl(var(--primary));}
.size-field{display:flex;align-items:center;justify-content:space-between;font-size:13px;margin:21px 0;}
.size-field input{width:120px;}
.checkbox-label{display:flex;gap:10px;align-items:flex-start;font-size:13px;line-height:1.6;margin:20px 0 5px;}
.checkbox-label input{margin-top:2px;}
.checkbox-label small{display:block;font-size:11px;margin-top:4px;}
.confirmation{flex-shrink:0;margin:16px 3px 0;}
.actions{flex-shrink:0;display:flex;align-items:center;justify-content:space-between;margin:0;padding-top:16px;gap:10px;}
.alert{display:flex;align-items:flex-start;gap:12px;border:1px solid hsl(var(--primary)/.25);background:hsl(var(--primary)/.05);border-radius:9px;padding:16px;margin:18px 0;font-size:13px;}
.alert svg{flex-shrink:0;margin-top:2px;color:hsl(var(--primary));}
.alert p{overflow-wrap:anywhere;}
.alert strong{display:block;margin-bottom:3px;}
.alert.danger{border-color:#e8907d66;background:#e8907d0a;}
.alert.danger svg{color:#c05942;}
.dark .alert.danger svg{color:#f3a28f;}
.busy-line{display:flex;align-items:center;gap:8px;font-size:12px;color:hsl(var(--primary));margin-bottom:12px;}
.plan-list>div{display:flex;justify-content:space-between;padding:14px 0;gap:20px;border-bottom:1px solid hsl(var(--border));}
.plan-list>div:last-child{border:none;}
.plan-list dt{color:hsl(var(--muted-foreground));font-size:13px;}
.plan-list dd{font-size:13px;font-weight:600;text-align:right;}
.status-line{display:flex;gap:9px;align-items:center;color:hsl(var(--muted-foreground));margin:17px 0 25px;}
.status-dot{width:8px;height:8px;background:hsl(var(--primary));border-radius:50%;}
.status-dot.failed{background:#c05942;}
.elapsed{margin-left:auto;font-size:12px;}
.activity{min-height:170px;}
.activity-heading{display:flex;align-items:center;gap:16px;padding:8px 0;}
.activity-heading>svg{color:hsl(var(--primary));flex-shrink:0;}
.activity-heading p{font-size:12px;color:hsl(var(--muted-foreground));margin-top:6px;}
.waiting-guidance{font-size:13px;line-height:1.9;margin-top:20px;}
.transfer{margin:25px 0 10px;}
.transfer>div{display:flex;justify-content:space-between;font-size:12px;}
progress{display:block;width:100%;height:7px;margin:13px 0;accent-color:hsl(var(--primary));border-radius:4px;}
.success-icon{margin-bottom:14px;}
.success-panel h2{margin-top:24px;}
.success-panel p{color:hsl(var(--muted-foreground));margin-top:7px;}
.backup-actions,.resume-tools{display:flex;gap:8px;flex-wrap:wrap;margin:16px 0;}
.record{display:flex;gap:16px;align-items:center;justify-content:space-between;}
.record p{font-size:13px;margin:7px 0;}
.empty-state{padding:26px 0;color:hsl(var(--muted-foreground));}
.form-grid{display:grid;gap:18px;margin:20px 0;}
.form-grid label{display:flex;flex-direction:column;gap:8px;font-size:12px;}
.log-panel{flex-shrink:0;border-top:1px solid hsl(var(--border));margin-top:18px;padding-top:12px;min-height:0;}
.log-toggle{display:flex;align-items:center;gap:7px;font-size:12px;color:hsl(var(--muted-foreground));cursor:pointer;list-style:none;}
.log-toggle>span{margin-left:auto;font-size:11px;}
.log-panel pre{min-height:0;flex:1;overflow:auto;overscroll-behavior:contain;scrollbar-gutter:stable;background:hsl(var(--muted));border-radius:6px;padding:14px;font-size:11px;white-space:pre-wrap;overflow-wrap:anywhere;}
.log-actions{display:flex;justify-content:flex-end;margin:10px 0;}
.log-actions button{font-size:11px;height:30px;}
footer{flex-shrink:0;border-top:1px solid hsl(var(--border));padding:12px 30px;display:flex;justify-content:space-between;color:hsl(var(--muted-foreground));font-size:10px;}
footer span{display:flex;align-items:center;gap:6px;}
.spin{animation:spin 1.4s linear infinite;}
@keyframes spin{to{transform:rotate(360deg);}
}
@media(prefers-reduced-motion:reduce){.spin{animation:none;}
}
@media(max-width:850px){.workspace{grid-template-columns:175px minmax(0,1fr);}
main{padding:22px 24px 16px;}
aside{padding:22px 10px;}
.preferences{gap:3px;}
header{padding:0 20px;}
h1{font-size:24px;}
.device-card{gap:8px;}
.stepper li{font-size:12px;}
}
html,body,#root {width:100%;height:100%;overflow:hidden;}
* {box-sizing:border-box;}
.page {display:flex;flex-direction:column;flex:1;min-width:0;min-height:0;overflow:hidden;}
.page>h1,.page>.eyebrow,.page>.status-line,.page>.resume-tools,.page>.form-grid {flex-shrink:0;}
h1:focus {outline:none;}
.page-scroll,.records-list {flex:1;min-height:0;min-width:0;}
.scroll-area {overflow-y:auto;overflow-x:hidden;overscroll-behavior:contain;scrollbar-gutter:stable;padding-right:10px;}
.page-scroll>section:first-child,.records-list>section:first-child {margin-top:0;}
.page-scroll>:last-child,.records-list>:last-child {margin-bottom:0;}
.sidebar-bottom {margin-top:auto;flex-shrink:0;padding-top:12px;}
aside>.nav-home,aside>.stepper {flex-shrink:0;}
.nav-home:disabled {opacity:.5;}
button:focus-visible {outline:2px solid hsl(var(--primary));outline-offset:3px;}
.ui-button,.method-options button,.nav-home {transition:background-color .16s,color .16s,border-color .16s,box-shadow .16s,transform .16s;}
.ui-button:active:not(:disabled),.method-options button:active {transform:translateY(1px);}
.purpose {border-radius:7px;}
.purpose>div:nth-child(2),.record>div {min-width:0;}
.purpose>svg,.record>.ui-button {flex-shrink:0;}
.purpose p,.record p,.plan-list dd,.device-card strong {overflow-wrap:anywhere;}
.purpose>svg {transition:transform .18s,color .18s;}
.purpose:hover>svg {transform:translateX(3px);color:hsl(var(--primary));}
.method-options button:hover {border-color:hsl(var(--primary)/.6);background:hsl(var(--primary)/.04);}
.stepper li,.stepper li>span {transition:background-color .2s,color .2s,border-color .2s;}
input:not([type=checkbox]):hover,select:hover {border-color:hsl(var(--primary)/.5);}
.busy-track {position:absolute;top:0;left:0;right:0;height:2px;pointer-events:none;}
.busy-track>div {height:100%;background:hsl(var(--primary)/.7);transform-origin:left;}
.status-dot.waiting_user,.status-dot.waiting_device {background:#ad7000;}
.dark .status-dot.waiting_user,.dark .status-dot.waiting_device {background:#e8b955;}
.log-toggle {width:100%;text-align:left;}
.log-toggle svg {transition:transform .18s;}
.log-toggle[aria-expanded=true] svg {transform:rotate(180deg);}
.log-content {overflow:hidden;}
.log-inner {height:min(190px,24dvh);display:flex;flex-direction:column;}
.log-panel pre {margin:0;tab-size:2;}
.log-actions {flex-shrink:0;margin:6px 0;}
.backup-actions {flex-shrink:0;margin:14px 0 0;}
.resume-tools {margin:0 0 12px;}
.resume-password {display:flex;flex-shrink:0;align-items:center;gap:12px;margin:0 0 16px;font-size:12px;}
.resume-password span {max-width:52%;}
.resume-password input {flex:1;min-width:0;width:0;}
.record {padding:16px;}
.scroll-area,.log-panel pre {scrollbar-width:thin;scrollbar-color:hsl(var(--border)) transparent;}
.help-trigger {height:36px;padding:0 10px;font-size:12px;}
.help-loading {position:fixed;z-index:61;right:24px;top:88px;display:flex;gap:10px;align-items:center;background:hsl(var(--card));border:1px solid hsl(var(--border));padding:14px 20px;border-radius:9px;}
[data-sonner-toaster] {z-index:50!important;}
.guide-callout {flex-shrink:0;display:flex;align-items:center;gap:12px;margin:0 0 18px;padding:14px;border:1px solid hsl(var(--border));border-radius:10px;background:hsl(var(--card));}
.guide-callout>svg {color:hsl(var(--primary));flex-shrink:0;}
.guide-callout>div {flex:1;min-width:0;}
.guide-callout strong {font-size:13px;font-weight:600;}
.guide-callout p {font-size:12px;color:hsl(var(--muted-foreground));margin-top:3px;}
.context-help {font-size:12px;padding:0;height:32px;margin-top:10px;}
.dialog-overlay {position:fixed;inset:0;background:#0008;z-index:60;animation:dialog-fade .14s ease-out;}
.dialog-content {position:fixed;z-index:61;left:50%;top:50%;transform:translate(-50%,-50%);width:min(940px,calc(100vw - 48px));height:min(740px,calc(100dvh - 48px));background:hsl(var(--card));border:1px solid hsl(var(--border));border-radius:14px;box-shadow:0 22px 70px #0004;display:flex;flex-direction:column;overflow:hidden;outline:none;animation:dialog-fade .16s ease-out;}
.dialog-heading {flex-shrink:0;padding:24px 54px 16px 26px;}
.dialog-heading h2 {font-size:22px;line-height:1.5;margin:5px 0 7px;font-weight:650;}
.dialog-heading p {font-size:13px;color:hsl(var(--muted-foreground));}
.dialog-close {position:absolute;right:18px;top:18px;padding:7px;border-radius:6px;color:hsl(var(--muted-foreground));}
.dialog-close:hover {background:hsl(var(--muted));color:hsl(var(--foreground));}
.dialog-footer {flex-shrink:0;display:flex;align-items:center;justify-content:space-between;gap:12px;padding:16px 24px;border-top:1px solid hsl(var(--border));}
.help-search {flex-shrink:0;display:flex;align-items:center;gap:10px;margin:0 26px 18px;}
.help-search>svg {color:hsl(var(--muted-foreground));flex-shrink:0;}
.help-search input {min-width:0;flex:1;}
.help-search span {font-size:11px;color:hsl(var(--muted-foreground));white-space:nowrap;}
.help-layout {display:grid;grid-template-columns:190px minmax(0,1fr);flex:1;min-height:0;border-top:1px solid hsl(var(--border));}
.help-topics {padding:16px 12px;min-height:0;border-right:1px solid hsl(var(--border));}
.help-topics button {width:100%;text-align:left;font-size:13px;line-height:1.6;padding:11px 12px;border-radius:7px;margin-bottom:4px;transition:background-color .15s,color .15s;}
.help-topics button:hover {background:hsl(var(--muted));}
.help-topics button[aria-current=page] {color:hsl(var(--primary));background:hsl(var(--primary)/.09);font-weight:600;}
.help-article {padding:24px 26px;min-height:0;user-select:text;}
.help-article>h2 {font-size:19px;margin-bottom:18px;}
.help-article:focus-visible {outline:2px solid hsl(var(--primary));outline-offset:-4px;}
.help-markdown {font-size:13px;line-height:1.85;overflow-wrap:anywhere;}
.help-markdown p {margin:12px 0;line-height:1.9;}
.help-markdown h3 {font-size:16px;font-weight:600;margin:24px 0 10px;}
.help-markdown h4 {font-size:14px;font-weight:600;margin:24px 0 9px;}
.help-markdown ul {list-style:disc;padding-left:20px;}
.help-markdown ol {list-style:decimal;padding-left:22px;}
.help-markdown li {padding-left:3px;margin:10px 0;}
.help-markdown code {font-family:Consolas,monospace;background:hsl(var(--muted));font-size:12px;padding:2px 4px;border-radius:4px;}
.help-address {color:hsl(var(--primary));user-select:text;}
.onboarding-dialog {width:min(760px,calc(100vw - 48px));height:min(570px,calc(100dvh - 48px));}
.guide-steps {display:flex;gap:16px;flex-shrink:0;padding:0 26px 20px;border-bottom:1px solid hsl(var(--border));}
.guide-steps li {flex:1;display:flex;align-items:center;gap:9px;font-size:11px;line-height:1.5;color:hsl(var(--muted-foreground));}
.guide-steps li>span {width:25px;height:25px;flex-shrink:0;display:flex;align-items:center;justify-content:center;border:1px solid hsl(var(--border));border-radius:50%;}
.guide-steps .reached {color:hsl(var(--primary));}
.guide-steps .reached>span {border-color:hsl(var(--primary));background:hsl(var(--primary)/.07);}
.guide-steps li[aria-current=step]>span {background:hsl(var(--primary));color:hsl(var(--primary-foreground));}
.onboarding-body {flex:1;min-height:0;padding:24px 30px;}
.guide-title {display:flex;align-items:center;gap:13px;margin-bottom:20px;color:hsl(var(--primary));}
.guide-title h2 {color:hsl(var(--foreground));font-size:19px;}
.onboarding-body ul {list-style:disc;padding-left:19px;font-size:14px;}
.onboarding-body li {line-height:1.9;padding-left:4px;margin:15px 0;}
.guide-no-action {display:flex;align-items:flex-start;gap:8px;color:hsl(var(--muted-foreground));font-size:12px;margin-top:22px;}
.guide-no-action svg {flex-shrink:0;margin-top:3px;}
.guide-count {color:hsl(var(--muted-foreground));font-size:11px;white-space:nowrap;}
.guide-controls {display:flex;gap:8px;}
@keyframes dialog-fade {from{opacity:0;}to{opacity:1;}}
@media(max-width:850px) {
.help-trigger span {display:none;}
.help-layout {grid-template-columns:165px minmax(0,1fr);}
.guide-callout {padding:11px;}
.guide-callout p {display:none;}
.dialog-heading {padding-top:18px;}
.help-article {padding:20px;}
}
.app-toast[data-sonner-toast][data-styled=true] {background:hsl(var(--card));color:hsl(var(--foreground));border:1px solid hsl(var(--border));box-shadow:0 8px 28px #00000018;font-family:inherit;}
.app-toast[data-sonner-toast] .toast-description {color:hsl(var(--muted-foreground));white-space:pre-wrap;overflow-wrap:anywhere;max-height:160px;overflow-y:auto;}
.app-toast[data-type=success] [data-icon] {color:hsl(var(--primary));}
.app-toast[data-type=error] [data-icon] {color:#b13c28;}
.dark .app-toast[data-type=error] [data-icon] {color:#ffae9c;}
.app-toast[data-sonner-toast] [data-close-button] {background:hsl(var(--card));color:hsl(var(--foreground));border-color:hsl(var(--border));}
.app-toast[data-sonner-toast] [data-close-button]:hover {background:hsl(var(--muted));}
@media(max-height:740px) {
header {height:66px;}
aside {padding-top:18px;padding-bottom:16px;gap:14px;}
.stepper li {min-height:43px;}
.stepper li:not(:last-child):after {top:34px;height:22px;}
main {padding-top:20px;}
.intro {margin-bottom:16px;}
.sidebar-bottom {padding-top:8px;}
.purpose {padding-top:14px;padding-bottom:14px;}
.log-panel {margin-top:14px;}
}
@media(prefers-reduced-motion:reduce) {
*,*::before,*::after {animation:none!important;transition:none!important;scroll-behavior:auto!important;}
.purpose:hover>svg,.ui-button:active:not(:disabled),.method-options button:active {transform:none;}
[data-sonner-toast] {transition:none!important;}
}
+3
View File
@@ -0,0 +1,3 @@
import { clsx, type ClassValue } from 'clsx';
import { twMerge } from 'tailwind-merge';
export function cn(...inputs: ClassValue[]) {return twMerge(clsx(inputs));}
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />
+7
View File
@@ -0,0 +1,7 @@
export default {darkMode: 'class', content: ['./index.html', './src/**/*.{ts,tsx}'], theme: {extend: {
colors: {background: 'hsl(var(--background))', foreground: 'hsl(var(--foreground))',
muted: 'hsl(var(--muted))', 'muted-foreground': 'hsl(var(--muted-foreground))',
border: 'hsl(var(--border))', primary: 'hsl(var(--primary))', 'primary-foreground': 'hsl(var(--primary-foreground))',
card: 'hsl(var(--card))', destructive: 'hsl(var(--destructive))'},
borderRadius: {lg: '12px', md: '8px'}
}}, plugins: []};
+9
View File
@@ -0,0 +1,9 @@
{
"compilerOptions": {
"target": "ES2022", "lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext", "moduleResolution": "Bundler", "jsx": "react-jsx",
"strict": true, "skipLibCheck": true, "noEmit": true, "resolveJsonModule": true,
"allowImportingTsExtensions": true, "esModuleInterop": true
},
"include": ["src"]
}
+3
View File
@@ -0,0 +1,3 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({plugins: [react()], server: {port: 1420, strictPort: true}, clearScreen: false});
@@ -0,0 +1,41 @@
[
{
"package": "e5-openwrt-gui-1.0.0",
"commands": {
"--verify-package": {
"exit": 0,
"stdout": "\r\n== 检查刷机包 / checking the package\r\n\r | 校验文件 / verifying the files 0 s \r OK 校验文件 / verifying the files 0 s \r\n e5-openwrt-25.12.5-tf-20261015-030543 (6.18.54-e5-mobile4-g020b970e351e-dirty)\r\nPackage verified / 安装包校验通过,未连接设备。\r\n\r\n============================================================\r\n[SUCCESS / 成功] 0.4 s\r\n============================================================\r\n",
"stderr": ""
}
},
"protocol_ok": true,
"utf8_error": "Select a device / 请选择设备",
"adb_version": "Android Debug Bridge version 1.0.41\r\nVersion 37.0.1-15733141\r\nInstalled as D:\\Git\\e5-linux\\out\\gui-releases\\20261015-guide\\e5-openwrt-gui-1.0.0\\tools\\adb.exe\r\nRunning on Windows 10.0.26100\r\n"
},
{
"package": "m8-openwrt-gui-1.0.0",
"commands": {
"--verify-package": {
"exit": 0,
"stdout": "\r\n== 检查刷机包 / checking the package\r\n\r | 校验文件 / verifying the files 0 s \r OK 校验文件 / verifying the files 0 s \r\n m8-openwrt-25.12.5-tf-20261015-030719 (6.18.54-m8-probe12-g020b970e351e-dirty)\r\nPackage verified / 安装包校验通过,未连接设备。\r\n\r\n============================================================\r\n[SUCCESS / 成功] 0.3 s\r\n============================================================\r\n",
"stderr": ""
}
},
"protocol_ok": true,
"utf8_error": "Select a device / 请选择设备",
"adb_version": "Android Debug Bridge version 1.0.41\r\nVersion 37.0.1-15733141\r\nInstalled as D:\\Git\\e5-linux\\out\\gui-releases\\20261015-guide\\m8-openwrt-gui-1.0.0\\tools\\adb.exe\r\nRunning on Windows 10.0.26100\r\n"
},
{
"package": "t551m-openwrt-gui-1.0.0",
"commands": {
"--verify-package": {
"exit": 0,
"stdout": "\r\n== 检查刷机包 / checking the package\r\n\r | 校验文件 / verifying the files 0 s \r OK 校验文件 / verifying the files 0 s \r\n t551m-openwrt-25.12.5-tf-20261015-030630 (6.18.54-t551m-otg10-g020b970e351e-dirty)\r\nPackage verified / 安装包校验通过,未连接设备。\r\n\r\n============================================================\r\n[SUCCESS / 成功] 0.3 s\r\n============================================================\r\n",
"stderr": ""
}
},
"protocol_ok": true,
"utf8_error": "Select a device / 请选择设备",
"adb_version": "Android Debug Bridge version 1.0.41\r\nVersion 37.0.1-15733141\r\nInstalled as D:\\Git\\e5-linux\\out\\gui-releases\\20261015-guide\\t551m-openwrt-gui-1.0.0\\tools\\adb.exe\r\nRunning on Windows 10.0.26100\r\n"
}
]
+35
View File
@@ -0,0 +1,35 @@
[
{
"gui_bytes": 3513344,
"backend_and_tools_bytes": 43093921,
"firmware_payload_bytes": 241029641,
"archive_bytes": 209446260,
"package": "e5-openwrt-gui-1.0.0",
"archive": "e5-openwrt-gui-1.0.0-windows.zip",
"sha256": "be61aa0e48e88f3c2b17f595942278fb1390e13e1abcd489630dfd38d812500a",
"payloads_unchanged": true,
"gui_sha256": "003d1c588bf5fa65c2004851b4459c1c01485e8f355ef75a0311a26afa5daddb"
},
{
"gui_bytes": 3513344,
"backend_and_tools_bytes": 43093921,
"firmware_payload_bytes": 240108928,
"archive_bytes": 209025138,
"package": "m8-openwrt-gui-1.0.0",
"archive": "m8-openwrt-gui-1.0.0-windows.zip",
"sha256": "843be8e5e518ebf3ec5aa5fae90d19f571c2d42527dbbd72c842724cfa331fe4",
"payloads_unchanged": true,
"gui_sha256": "003d1c588bf5fa65c2004851b4459c1c01485e8f355ef75a0311a26afa5daddb"
},
{
"gui_bytes": 3513344,
"backend_and_tools_bytes": 43093921,
"firmware_payload_bytes": 240960718,
"archive_bytes": 209468918,
"package": "t551m-openwrt-gui-1.0.0",
"archive": "t551m-openwrt-gui-1.0.0-windows.zip",
"sha256": "c4a09663b406bc83fa7088a3825e8b9e7e442a50e362155c3cbbdf2fc97514dd",
"payloads_unchanged": true,
"gui_sha256": "003d1c588bf5fa65c2004851b4459c1c01485e8f355ef75a0311a26afa5daddb"
}
]
@@ -0,0 +1,38 @@
[
{
"package": "mu300-openwrt-6.18.54-gui-1.0.0",
"commands": {
"--check": {
"exit": 0,
"stdout": "MU300 desktop package verified; kernel 6.18\r\n\r\n========================================================\r\n[CHECK PASSED / 校验通过] Package checksums passed / 安装包校验通过。\r\nElapsed / 总耗时: 0 s\r\n",
"stderr": ""
},
"--check-boot": {
"exit": 0,
"stdout": "MU300 desktop package verified; kernel 6.18\r\nDesktop boot build verified: sd Android slot a (no device writes)\r\nDesktop boot build verified: install-part Android slot b (no device writes)\r\n\r\n========================================================\r\n[CHECK PASSED / 校验通过] Desktop boot construction passed / 桌面启动镜像构建检查通过。\r\nElapsed / 总耗时: 1 s\r\n",
"stderr": ""
}
},
"protocol_ok": true,
"utf8_error": "Select a device / 请选择设备",
"adb_version": "Android Debug Bridge version 1.0.41\r\nVersion 37.0.1-15733141\r\nInstalled as D:\\Git\\mu300-linux-clean-tf-7.2\\release\\gui-20261015-guide\\mu300-openwrt-6.18.54-gui-1.0.0\\tools\\adb.exe\r\nRunning on Windows 10.0.26100\r\n"
},
{
"package": "mu300-openwrt-7.2.8-gui-1.0.0",
"commands": {
"--check": {
"exit": 0,
"stdout": "MU300 desktop package verified; kernel 7.2\r\n\r\n========================================================\r\n[CHECK PASSED / 校验通过] Package checksums passed / 安装包校验通过。\r\nElapsed / 总耗时: 0 s\r\n",
"stderr": ""
},
"--check-boot": {
"exit": 0,
"stdout": "MU300 desktop package verified; kernel 7.2\r\nDesktop boot build verified: sd Android slot a (no device writes)\r\nDesktop boot build verified: install-part Android slot b (no device writes)\r\n\r\n========================================================\r\n[CHECK PASSED / 校验通过] Desktop boot construction passed / 桌面启动镜像构建检查通过。\r\nElapsed / 总耗时: 1 s\r\n",
"stderr": ""
}
},
"protocol_ok": true,
"utf8_error": "Select a device / 请选择设备",
"adb_version": "Android Debug Bridge version 1.0.41\r\nVersion 37.0.1-15733141\r\nInstalled as D:\\Git\\mu300-linux-clean-tf-7.2\\release\\gui-20261015-guide\\mu300-openwrt-7.2.8-gui-1.0.0\\tools\\adb.exe\r\nRunning on Windows 10.0.26100\r\n"
}
]
@@ -0,0 +1,24 @@
[
{
"gui_bytes": 3513344,
"backend_and_tools_bytes": 46028208,
"firmware_payload_bytes": 145582695,
"archive_bytes": 119474683,
"package": "mu300-openwrt-6.18.54-gui-1.0.0",
"archive": "mu300-openwrt-6.18.54-gui-1.0.0-windows.zip",
"sha256": "2b3cec26903a97881b971ded34afde2608a22007863706112d06123be3e1c259",
"payloads_unchanged": true,
"gui_sha256": "003d1c588bf5fa65c2004851b4459c1c01485e8f355ef75a0311a26afa5daddb"
},
{
"gui_bytes": 3513344,
"backend_and_tools_bytes": 46028207,
"firmware_payload_bytes": 146076011,
"archive_bytes": 120549204,
"package": "mu300-openwrt-7.2.8-gui-1.0.0",
"archive": "mu300-openwrt-7.2.8-gui-1.0.0-windows.zip",
"sha256": "bb25a178fe463d0c3cc13cda183462001683b4a81fab216985d82273c8b0afef",
"payloads_unchanged": true,
"gui_sha256": "003d1c588bf5fa65c2004851b4459c1c01485e8f355ef75a0311a26afa5daddb"
}
]
+73
View File
@@ -0,0 +1,73 @@
{
"date": "2026-10-15",
"revision": "onboarding-offline-help",
"gui_bytes": 3513344,
"backend_tests": {
"e5": 27,
"mu300": 27
},
"ui_smoke": "passed: fixed layout, long lists/logs, confirmation, waits, device selection, notifications, themes and languages",
"help_smoke": "passed: three-step first launch/replay/finish/skip persistence, saved-record suppression, offline search/no results, zero remote requests, F1/Escape/focus trap and return, current-stage help without backend commands, 800x650 bounded dialogs, reduced motion, notification layer below modal",
"native_launch": "passed: release EXE, actual system WebView2 window with first-run onboarding; screenshots/native-home.png",
"package_smoke": "passed: five frozen backends and CLIs, both MU300 boot builders",
"payload_invariance": "all five match original system/boot/tool payload hashes",
"zip_integrity": "all five CRC checks passed; exactly one rootfs each",
"hardware_writes": "none",
"packages": [
{
"gui_bytes": 3513344,
"backend_and_tools_bytes": 43093921,
"firmware_payload_bytes": 241029641,
"archive_bytes": 209446260,
"package": "e5-openwrt-gui-1.0.0",
"archive": "e5-openwrt-gui-1.0.0-windows.zip",
"sha256": "be61aa0e48e88f3c2b17f595942278fb1390e13e1abcd489630dfd38d812500a",
"payloads_unchanged": true,
"gui_sha256": "003d1c588bf5fa65c2004851b4459c1c01485e8f355ef75a0311a26afa5daddb"
},
{
"gui_bytes": 3513344,
"backend_and_tools_bytes": 43093921,
"firmware_payload_bytes": 240108928,
"archive_bytes": 209025138,
"package": "m8-openwrt-gui-1.0.0",
"archive": "m8-openwrt-gui-1.0.0-windows.zip",
"sha256": "843be8e5e518ebf3ec5aa5fae90d19f571c2d42527dbbd72c842724cfa331fe4",
"payloads_unchanged": true,
"gui_sha256": "003d1c588bf5fa65c2004851b4459c1c01485e8f355ef75a0311a26afa5daddb"
},
{
"gui_bytes": 3513344,
"backend_and_tools_bytes": 43093921,
"firmware_payload_bytes": 240960718,
"archive_bytes": 209468918,
"package": "t551m-openwrt-gui-1.0.0",
"archive": "t551m-openwrt-gui-1.0.0-windows.zip",
"sha256": "c4a09663b406bc83fa7088a3825e8b9e7e442a50e362155c3cbbdf2fc97514dd",
"payloads_unchanged": true,
"gui_sha256": "003d1c588bf5fa65c2004851b4459c1c01485e8f355ef75a0311a26afa5daddb"
},
{
"gui_bytes": 3513344,
"backend_and_tools_bytes": 46028208,
"firmware_payload_bytes": 145582695,
"archive_bytes": 119474683,
"package": "mu300-openwrt-6.18.54-gui-1.0.0",
"archive": "mu300-openwrt-6.18.54-gui-1.0.0-windows.zip",
"sha256": "2b3cec26903a97881b971ded34afde2608a22007863706112d06123be3e1c259",
"payloads_unchanged": true,
"gui_sha256": "003d1c588bf5fa65c2004851b4459c1c01485e8f355ef75a0311a26afa5daddb"
},
{
"gui_bytes": 3513344,
"backend_and_tools_bytes": 46028207,
"firmware_payload_bytes": 146076011,
"archive_bytes": 120549204,
"package": "mu300-openwrt-7.2.8-gui-1.0.0",
"archive": "mu300-openwrt-7.2.8-gui-1.0.0-windows.zip",
"sha256": "bb25a178fe463d0c3cc13cda183462001683b4a81fab216985d82273c8b0afef",
"payloads_unchanged": true,
"gui_sha256": "003d1c588bf5fa65c2004851b4459c1c01485e8f355ef75a0311a26afa5daddb"
}
]
}
@@ -0,0 +1,85 @@
[
{
"package": "e5-openwrt-gui-1.0.0",
"payloads_unchanged": true,
"payloads": {
"files/boot.img": "d5402429236d68ff0b92957088718c5973d66ddff16bb1ee311476fdb3d63d6d",
"files/openwrt.ext4.gz": "6a9818687535ccb72025db6f17742b797f38f73a3c4ecf7012c06d8684089755",
"files/ext4-tools.tar": "52be8553b37ee9afadb29a0245ddc78170c6cf70a7920b9b8e878cc61bea9487"
}
},
{
"package": "m8-openwrt-gui-1.0.0",
"payloads_unchanged": true,
"payloads": {
"files/boot.img": "870f549ab5cba4ad1a0ed41e356417b13ad6b7a76ca6e110399a7ed4fd265584",
"files/openwrt.ext4.gz": "75d2b251687aacea109bb2c0c6e51da3fbe4b4a3cb1969e58992dd7d0e0df75a",
"files/ext4-tools.tar": "93aa8c198e32718a8661d2c0b7e314d6f6a7dc7b8e804335da564ce480deb2d9"
}
},
{
"package": "t551m-openwrt-gui-1.0.0",
"payloads_unchanged": true,
"payloads": {
"files/boot.img": "9574f77085342b586441824997dede4bd73445ec384bc34d88bf3c5dceb04556",
"files/openwrt.ext4.gz": "b744dff418dc034e70b0a3fc0c043c368d599fa6d65408a69f45874c69dfe565",
"files/ext4-tools.tar": "66d5791f2496e6b017fcaa4d24282ce8a65a9304d3ca5c7f372313114cfb028e"
}
},
{
"package": "mu300-openwrt-6.18.54-gui-1.0.0",
"payloads_unchanged": true,
"payloads": {
"payload/boot-linux.img": "c380a570cc574278fde6dc49195921d0ceac1dc107a1c7ce75c38eed173c6728",
"payload/mu300-openwrt.tar.gz": "ed44628a1dacac564198e190cf08672757814aa62bf0804756f2fd4817d37b44",
"payload/busybox": "52151e7f322f926b64049cdaa1410dc3ea6485525e0624b05813791c219ae933",
"payload/rootfs-critical.sha256": "2711a990ee064d311fd3ca00287ce19ef452737499ad1cad3c733439a506bf05",
"payload/rootfs.requirements": "747906ee03d9f4feb60c17da9b6ba9edf5c5bf2a3276f8363045e061fef589f4",
"desktop/files/boot/repair/manifest.json": "b3988894aa88560c73f6e07d9809df8b7fd4815697a5cbb607c7b6fcdcd1bdfc",
"desktop/files/boot/repair/lib/ld-musl-aarch64.so.1": "df69305a63ff7a94dc870e159f9211b725eec8cafb0c4c7428cfbcb5df99b8b2",
"desktop/files/boot/repair/lib/libblkid.so.1": "d52d1747235e121da8cbac21dd820d46e4125d840bfef2bc2f3a2985b0ca3d7d",
"desktop/files/boot/repair/lib/libcom_err.so.0": "5c4348caf3d8c3f4e002c97ff3c0c73480b0f3d954c29c80080c46a14de2a975",
"desktop/files/boot/repair/lib/libe2p.so.2": "37f297f61f049a07a9a8742d91e4d48af4dee44782d7f44c39d60dd87e471fdd",
"desktop/files/boot/repair/lib/libext2fs.so.2": "884f4cc9cb124da051108930e1f1a7871bf0bf88bbd1f353de4b29b611b135cf",
"desktop/files/boot/repair/lib/libf2fs.so.10": "fbc97944a7dfc5b6f066e0986931b99b039f0d2d9c72da82994f449694990271",
"desktop/files/boot/repair/lib/libgcc_s.so.1": "68c85e8a82ada65f434f2295e234ffaf52217067b4929eb4e5a78f413233417b",
"desktop/files/boot/repair/lib/libjson-c.so.5": "b49294d311e719185c395343f7e2668d26ada81c97290d98bd9bb01f4768fb60",
"desktop/files/boot/repair/lib/libucode.so.20230711": "5a208b57ef3915b5903c0d5c85b3bab4b602916c71f234ca03e217b95277d2b0",
"desktop/files/boot/repair/lib/libuuid.so.1": "442a0ae0a8ea86a5e0d1680d1166ad91940952dc63b6ff18be1d9dc558777eb1",
"desktop/files/boot/repair/sbin/fsck.f2fs": "fd88398882fdadad8366e4b213ff7777c421905a1cdbb2c3670a1022ef08d1d8",
"desktop/files/boot/repair/sbin/resize.f2fs": "fd88398882fdadad8366e4b213ff7777c421905a1cdbb2c3670a1022ef08d1d8",
"desktop/files/boot/repair/usr/bin/ucode": "7795b07c1fa1c7dbcd2ae2be51390aff2d1c3af57dba68753f9023aa86777f82",
"desktop/files/boot/repair/usr/sbin/e2fsck": "2e89aa4b601ffe50ff64ef3f8fd755854e91587c05ddd4e59bb137ace8dcff75",
"desktop/files/boot/repair/usr/sbin/resize2fs": "0487b49650eef4e7ff6969cf41eea1c267eb21b29bc531e16ef8b8a379c0ab75",
"desktop/files/boot/repair/usr/lib/ucode/fs.so": "c1c6f840361bfabb65d8e62bc660509d28cf2008ea4db3d96bbb13b71e09d5e5"
}
},
{
"package": "mu300-openwrt-7.2.8-gui-1.0.0",
"payloads_unchanged": true,
"payloads": {
"payload/boot-linux.img": "578d040bbb689df6c29549abaf60b99174103e074f20de2e6d87939ec0650b27",
"payload/mu300-openwrt.tar.gz": "54624febe60444bc8c4662a1993957f3b9caa9844107aad6207040dcf4559d2a",
"payload/busybox": "52151e7f322f926b64049cdaa1410dc3ea6485525e0624b05813791c219ae933",
"payload/rootfs-critical.sha256": "2711a990ee064d311fd3ca00287ce19ef452737499ad1cad3c733439a506bf05",
"payload/rootfs.requirements": "c8e132a520bda2d8e825be722fb5e5bcd630f25b13f3e793f98ee8a2064acf81",
"desktop/files/boot/repair/manifest.json": "b3988894aa88560c73f6e07d9809df8b7fd4815697a5cbb607c7b6fcdcd1bdfc",
"desktop/files/boot/repair/lib/ld-musl-aarch64.so.1": "df69305a63ff7a94dc870e159f9211b725eec8cafb0c4c7428cfbcb5df99b8b2",
"desktop/files/boot/repair/lib/libblkid.so.1": "d52d1747235e121da8cbac21dd820d46e4125d840bfef2bc2f3a2985b0ca3d7d",
"desktop/files/boot/repair/lib/libcom_err.so.0": "5c4348caf3d8c3f4e002c97ff3c0c73480b0f3d954c29c80080c46a14de2a975",
"desktop/files/boot/repair/lib/libe2p.so.2": "37f297f61f049a07a9a8742d91e4d48af4dee44782d7f44c39d60dd87e471fdd",
"desktop/files/boot/repair/lib/libext2fs.so.2": "884f4cc9cb124da051108930e1f1a7871bf0bf88bbd1f353de4b29b611b135cf",
"desktop/files/boot/repair/lib/libf2fs.so.10": "fbc97944a7dfc5b6f066e0986931b99b039f0d2d9c72da82994f449694990271",
"desktop/files/boot/repair/lib/libgcc_s.so.1": "68c85e8a82ada65f434f2295e234ffaf52217067b4929eb4e5a78f413233417b",
"desktop/files/boot/repair/lib/libjson-c.so.5": "b49294d311e719185c395343f7e2668d26ada81c97290d98bd9bb01f4768fb60",
"desktop/files/boot/repair/lib/libucode.so.20230711": "5a208b57ef3915b5903c0d5c85b3bab4b602916c71f234ca03e217b95277d2b0",
"desktop/files/boot/repair/lib/libuuid.so.1": "442a0ae0a8ea86a5e0d1680d1166ad91940952dc63b6ff18be1d9dc558777eb1",
"desktop/files/boot/repair/sbin/fsck.f2fs": "fd88398882fdadad8366e4b213ff7777c421905a1cdbb2c3670a1022ef08d1d8",
"desktop/files/boot/repair/sbin/resize.f2fs": "fd88398882fdadad8366e4b213ff7777c421905a1cdbb2c3670a1022ef08d1d8",
"desktop/files/boot/repair/usr/bin/ucode": "7795b07c1fa1c7dbcd2ae2be51390aff2d1c3af57dba68753f9023aa86777f82",
"desktop/files/boot/repair/usr/sbin/e2fsck": "2e89aa4b601ffe50ff64ef3f8fd755854e91587c05ddd4e59bb137ace8dcff75",
"desktop/files/boot/repair/usr/sbin/resize2fs": "0487b49650eef4e7ff6969cf41eea1c267eb21b29bc531e16ef8b8a379c0ab75",
"desktop/files/boot/repair/usr/lib/ucode/fs.so": "c1c6f840361bfabb65d8e62bc660509d28cf2008ea4db3d96bbb13b71e09d5e5"
}
}
]
@@ -0,0 +1,28 @@
[
{
"package": "e5-openwrt-gui-1.0.0",
"commands": {
"--verify-package": {
"exit": 0,
"stdout": "\r\n== 检查刷机包 / checking the package\r\n\r | 校验文件 / verifying the files 0 s \r OK 校验文件 / verifying the files 0 s \r\n e5-openwrt-25.12.5-tf-20261015-030543 (6.18.54-e5-mobile4-g020b970e351e-dirty)\r\nPackage verified / 安装包校验通过,未连接设备。\r\n\r\n============================================================\r\n[SUCCESS / 成功] 0.4 s\r\n============================================================\r\n",
"stderr": ""
}
},
"protocol_ok": true,
"utf8_error": "Select a device / 请选择设备",
"adb_version": "Android Debug Bridge version 1.0.41\r\nVersion 37.0.1-15733141\r\nInstalled as D:\\Git\\e5-linux\\out\\gui-releases\\20261015-ui2\\e5-openwrt-gui-1.0.0\\tools\\adb.exe\r\nRunning on Windows 10.0.26100\r\n"
},
{
"package": "m8-openwrt-gui-1.0.0",
"commands": {
"--verify-package": {
"exit": 0,
"stdout": "\r\n== 检查刷机包 / checking the package\r\n\r | 校验文件 / verifying the files 0 s \r OK 校验文件 / verifying the files 0 s \r\n m8-openwrt-25.12.5-tf-20261015-030719 (6.18.54-m8-probe12-g020b970e351e-dirty)\r\nPackage verified / 安装包校验通过,未连接设备。\r\n\r\n============================================================\r\n[SUCCESS / 成功] 0.4 s\r\n============================================================\r\n",
"stderr": ""
}
},
"protocol_ok": true,
"utf8_error": "Select a device / 请选择设备",
"adb_version": "Android Debug Bridge version 1.0.41\r\nVersion 37.0.1-15733141\r\nInstalled as D:\\Git\\e5-linux\\out\\gui-releases\\20261015-ui2\\m8-openwrt-gui-1.0.0\\tools\\adb.exe\r\nRunning on Windows 10.0.26100\r\n"
}
]
@@ -0,0 +1,35 @@
[
{
"gui_bytes": 3451904,
"backend_and_tools_bytes": 43093921,
"firmware_payload_bytes": 241029206,
"archive_bytes": 209021355,
"package": "e5-openwrt-gui-1.0.0",
"archive": "e5-openwrt-gui-1.0.0-windows.zip",
"sha256": "a915fde06bbe834004969d452e9de91676d8197f0e83509c3cfda13adcd3d6d9",
"payloads_unchanged": true,
"gui_sha256": "ddcb36d8002c1f575510199db115dd833e9731714ca3c29047ec71acad3ac5ba"
},
{
"gui_bytes": 3451904,
"backend_and_tools_bytes": 43093921,
"firmware_payload_bytes": 240108493,
"archive_bytes": 208600233,
"package": "m8-openwrt-gui-1.0.0",
"archive": "m8-openwrt-gui-1.0.0-windows.zip",
"sha256": "fd4c07c249005b7362acdc20c460b24a71781a87df19b830fd241ce7d5b77f8b",
"payloads_unchanged": true,
"gui_sha256": "ddcb36d8002c1f575510199db115dd833e9731714ca3c29047ec71acad3ac5ba"
},
{
"gui_bytes": 3451904,
"backend_and_tools_bytes": 43093921,
"firmware_payload_bytes": 240960283,
"archive_bytes": 209044021,
"package": "t551m-openwrt-gui-1.0.0",
"archive": "t551m-openwrt-gui-1.0.0-windows.zip",
"sha256": "85d0b076bc6cf1222262575a60b1d59d8615a41e7590535d2d59e64e018ff557",
"payloads_unchanged": true,
"gui_sha256": "ddcb36d8002c1f575510199db115dd833e9731714ca3c29047ec71acad3ac5ba"
}
]
@@ -0,0 +1,38 @@
[
{
"package": "mu300-openwrt-6.18.54-gui-1.0.0",
"commands": {
"--check": {
"exit": 0,
"stdout": "MU300 desktop package verified; kernel 6.18\r\n\r\n========================================================\r\n[CHECK PASSED / 校验通过] Package checksums passed / 安装包校验通过。\r\nElapsed / 总耗时: 0 s\r\n",
"stderr": ""
},
"--check-boot": {
"exit": 0,
"stdout": "MU300 desktop package verified; kernel 6.18\r\nDesktop boot build verified: sd Android slot a (no device writes)\r\nDesktop boot build verified: install-part Android slot b (no device writes)\r\n\r\n========================================================\r\n[CHECK PASSED / 校验通过] Desktop boot construction passed / 桌面启动镜像构建检查通过。\r\nElapsed / 总耗时: 2 s\r\n",
"stderr": ""
}
},
"protocol_ok": true,
"utf8_error": "Select a device / 请选择设备",
"adb_version": "Android Debug Bridge version 1.0.41\r\nVersion 37.0.1-15733141\r\nInstalled as D:\\Git\\mu300-linux-clean-tf-7.2\\release\\gui-20261015-ui2\\mu300-openwrt-6.18.54-gui-1.0.0\\tools\\adb.exe\r\nRunning on Windows 10.0.26100\r\n"
},
{
"package": "mu300-openwrt-7.2.8-gui-1.0.0",
"commands": {
"--check": {
"exit": 0,
"stdout": "MU300 desktop package verified; kernel 7.2\r\n\r\n========================================================\r\n[CHECK PASSED / 校验通过] Package checksums passed / 安装包校验通过。\r\nElapsed / 总耗时: 0 s\r\n",
"stderr": ""
},
"--check-boot": {
"exit": 0,
"stdout": "MU300 desktop package verified; kernel 7.2\r\nDesktop boot build verified: sd Android slot a (no device writes)\r\nDesktop boot build verified: install-part Android slot b (no device writes)\r\n\r\n========================================================\r\n[CHECK PASSED / 校验通过] Desktop boot construction passed / 桌面启动镜像构建检查通过。\r\nElapsed / 总耗时: 2 s\r\n",
"stderr": ""
}
},
"protocol_ok": true,
"utf8_error": "Select a device / 请选择设备",
"adb_version": "Android Debug Bridge version 1.0.41\r\nVersion 37.0.1-15733141\r\nInstalled as D:\\Git\\mu300-linux-clean-tf-7.2\\release\\gui-20261015-ui2\\mu300-openwrt-7.2.8-gui-1.0.0\\tools\\adb.exe\r\nRunning on Windows 10.0.26100\r\n"
}
]
@@ -0,0 +1,24 @@
[
{
"gui_bytes": 3451904,
"backend_and_tools_bytes": 46027737,
"firmware_payload_bytes": 145582695,
"archive_bytes": 119049789,
"package": "mu300-openwrt-6.18.54-gui-1.0.0",
"archive": "mu300-openwrt-6.18.54-gui-1.0.0-windows.zip",
"sha256": "fe07b5181dfbb27204a04a71a1baa1d90f66ec6262c1eed7435b7f2db005c57d",
"payloads_unchanged": true,
"gui_sha256": "ddcb36d8002c1f575510199db115dd833e9731714ca3c29047ec71acad3ac5ba"
},
{
"gui_bytes": 3451904,
"backend_and_tools_bytes": 46027736,
"firmware_payload_bytes": 146076011,
"archive_bytes": 120124313,
"package": "mu300-openwrt-7.2.8-gui-1.0.0",
"archive": "mu300-openwrt-7.2.8-gui-1.0.0-windows.zip",
"sha256": "e34a797863202a857c7f729cdac37c73a8e970e4cac5a84b9ebc34bbb0878d98",
"payloads_unchanged": true,
"gui_sha256": "ddcb36d8002c1f575510199db115dd833e9731714ca3c29047ec71acad3ac5ba"
}
]
@@ -0,0 +1,15 @@
[
{
"package": "t551m-openwrt-gui-1.0.0",
"commands": {
"--verify-package": {
"exit": 0,
"stdout": "\r\n== 检查刷机包 / checking the package\r\n\r | 校验文件 / verifying the files 0 s \r OK 校验文件 / verifying the files 0 s \r\n t551m-openwrt-25.12.5-tf-20261015-030630 (6.18.54-t551m-otg10-g020b970e351e-dirty)\r\nPackage verified / 安装包校验通过,未连接设备。\r\n\r\n============================================================\r\n[SUCCESS / 成功] 0.3 s\r\n============================================================\r\n",
"stderr": ""
}
},
"protocol_ok": true,
"utf8_error": "Select a device / 请选择设备",
"adb_version": "Android Debug Bridge version 1.0.41\r\nVersion 37.0.1-15733141\r\nInstalled as D:\\Git\\e5-linux\\out\\gui-releases\\20261015-ui2\\t551m-openwrt-gui-1.0.0\\tools\\adb.exe\r\nRunning on Windows 10.0.26100\r\n"
}
]
+116
View File
@@ -0,0 +1,116 @@
{
"date": "2026-10-15",
"revision": "ui2",
"gui_bytes": 3451904,
"backend_unit_tests": {
"e5": 27,
"mu300": 27
},
"native_launch": "Passed: actual Tauri release, system WebView2, screenshots/native-home.png",
"ui_smoke": {
"result": "passed",
"viewports": [
"1120x900",
"800x650"
],
"records": 120,
"log_cap": 500,
"checks": [
"independent scrolling and fixed actions/footer",
"sidebar reminder at bottom",
"new page heading keyboard focus",
"explicit multi-device choice and selection preservation",
"final destructive confirmation",
"expected Android/root waits and completion",
"Sonner status deduplication",
"backend/native/clipboard errors",
"export success and cancelled save without false success",
"Chinese/English and light/dark/system themes",
"reduced motion"
]
},
"release_directories": [
"D:/Git/e5-linux/out/gui-releases/20261015-ui2",
"D:/Git/mu300-linux-clean-tf-7.2/release/gui-20261015-ui2"
],
"zip_crc": "All five passed; one system payload per ZIP",
"firmware_payloads": "All five critical payload hash maps match prior validation",
"hardware_writes": "None; no formatting, GPT/misc/boot write, upgrade or hardware installation performed",
"packages": [
{
"package": "e5-openwrt-gui-1.0.0",
"commands": {
"--verify-package": {
"exit": 0,
"stdout": "\r\n== 检查刷机包 / checking the package\r\n\r | 校验文件 / verifying the files 0 s \r OK 校验文件 / verifying the files 0 s \r\n e5-openwrt-25.12.5-tf-20261015-030543 (6.18.54-e5-mobile4-g020b970e351e-dirty)\r\nPackage verified / 安装包校验通过,未连接设备。\r\n\r\n============================================================\r\n[SUCCESS / 成功] 0.4 s\r\n============================================================\r\n",
"stderr": ""
}
},
"protocol_ok": true,
"utf8_error": "Select a device / 请选择设备",
"adb_version": "Android Debug Bridge version 1.0.41\r\nVersion 37.0.1-15733141\r\nInstalled as D:\\Git\\e5-linux\\out\\gui-releases\\20261015-ui2\\e5-openwrt-gui-1.0.0\\tools\\adb.exe\r\nRunning on Windows 10.0.26100\r\n"
},
{
"package": "m8-openwrt-gui-1.0.0",
"commands": {
"--verify-package": {
"exit": 0,
"stdout": "\r\n== 检查刷机包 / checking the package\r\n\r | 校验文件 / verifying the files 0 s \r OK 校验文件 / verifying the files 0 s \r\n m8-openwrt-25.12.5-tf-20261015-030719 (6.18.54-m8-probe12-g020b970e351e-dirty)\r\nPackage verified / 安装包校验通过,未连接设备。\r\n\r\n============================================================\r\n[SUCCESS / 成功] 0.4 s\r\n============================================================\r\n",
"stderr": ""
}
},
"protocol_ok": true,
"utf8_error": "Select a device / 请选择设备",
"adb_version": "Android Debug Bridge version 1.0.41\r\nVersion 37.0.1-15733141\r\nInstalled as D:\\Git\\e5-linux\\out\\gui-releases\\20261015-ui2\\m8-openwrt-gui-1.0.0\\tools\\adb.exe\r\nRunning on Windows 10.0.26100\r\n"
},
{
"package": "t551m-openwrt-gui-1.0.0",
"commands": {
"--verify-package": {
"exit": 0,
"stdout": "\r\n== 检查刷机包 / checking the package\r\n\r | 校验文件 / verifying the files 0 s \r OK 校验文件 / verifying the files 0 s \r\n t551m-openwrt-25.12.5-tf-20261015-030630 (6.18.54-t551m-otg10-g020b970e351e-dirty)\r\nPackage verified / 安装包校验通过,未连接设备。\r\n\r\n============================================================\r\n[SUCCESS / 成功] 0.3 s\r\n============================================================\r\n",
"stderr": ""
}
},
"protocol_ok": true,
"utf8_error": "Select a device / 请选择设备",
"adb_version": "Android Debug Bridge version 1.0.41\r\nVersion 37.0.1-15733141\r\nInstalled as D:\\Git\\e5-linux\\out\\gui-releases\\20261015-ui2\\t551m-openwrt-gui-1.0.0\\tools\\adb.exe\r\nRunning on Windows 10.0.26100\r\n"
},
{
"package": "mu300-openwrt-6.18.54-gui-1.0.0",
"commands": {
"--check": {
"exit": 0,
"stdout": "MU300 desktop package verified; kernel 6.18\r\n\r\n========================================================\r\n[CHECK PASSED / 校验通过] Package checksums passed / 安装包校验通过。\r\nElapsed / 总耗时: 0 s\r\n",
"stderr": ""
},
"--check-boot": {
"exit": 0,
"stdout": "MU300 desktop package verified; kernel 6.18\r\nDesktop boot build verified: sd Android slot a (no device writes)\r\nDesktop boot build verified: install-part Android slot b (no device writes)\r\n\r\n========================================================\r\n[CHECK PASSED / 校验通过] Desktop boot construction passed / 桌面启动镜像构建检查通过。\r\nElapsed / 总耗时: 2 s\r\n",
"stderr": ""
}
},
"protocol_ok": true,
"utf8_error": "Select a device / 请选择设备",
"adb_version": "Android Debug Bridge version 1.0.41\r\nVersion 37.0.1-15733141\r\nInstalled as D:\\Git\\mu300-linux-clean-tf-7.2\\release\\gui-20261015-ui2\\mu300-openwrt-6.18.54-gui-1.0.0\\tools\\adb.exe\r\nRunning on Windows 10.0.26100\r\n"
},
{
"package": "mu300-openwrt-7.2.8-gui-1.0.0",
"commands": {
"--check": {
"exit": 0,
"stdout": "MU300 desktop package verified; kernel 7.2\r\n\r\n========================================================\r\n[CHECK PASSED / 校验通过] Package checksums passed / 安装包校验通过。\r\nElapsed / 总耗时: 0 s\r\n",
"stderr": ""
},
"--check-boot": {
"exit": 0,
"stdout": "MU300 desktop package verified; kernel 7.2\r\nDesktop boot build verified: sd Android slot a (no device writes)\r\nDesktop boot build verified: install-part Android slot b (no device writes)\r\n\r\n========================================================\r\n[CHECK PASSED / 校验通过] Desktop boot construction passed / 桌面启动镜像构建检查通过。\r\nElapsed / 总耗时: 2 s\r\n",
"stderr": ""
}
},
"protocol_ok": true,
"utf8_error": "Select a device / 请选择设备",
"adb_version": "Android Debug Bridge version 1.0.41\r\nVersion 37.0.1-15733141\r\nInstalled as D:\\Git\\mu300-linux-clean-tf-7.2\\release\\gui-20261015-ui2\\mu300-openwrt-7.2.8-gui-1.0.0\\tools\\adb.exe\r\nRunning on Windows 10.0.26100\r\n"
}
]
}
@@ -0,0 +1,77 @@
[
{
"package": "e5-openwrt-gui-1.0.0",
"commands": {
"--verify-package": {
"exit": 0,
"stdout": "\r\n== 检查刷机包 / checking the package\r\n\r | 校验文件 / verifying the files 0 s \r OK 校验文件 / verifying the files 0 s \r\n e5-openwrt-25.12.5-tf-20261015-030543 (6.18.54-e5-mobile4-g020b970e351e-dirty)\r\nPackage verified / 安装包校验通过,未连接设备。\r\n\r\n============================================================\r\n[SUCCESS / 成功] 0.3 s\r\n============================================================\r\n",
"stderr": ""
}
},
"protocol_ok": true,
"utf8_error": "Select a device / 请选择设备",
"adb_version": "Android Debug Bridge version 1.0.41\r\nVersion 37.0.1-15733141\r\nInstalled as D:\\Git\\e5-linux\\out\\gui-releases\\20261015\\e5-openwrt-gui-1.0.0\\tools\\adb.exe\r\nRunning on Windows 10.0.26100\r\n"
},
{
"package": "m8-openwrt-gui-1.0.0",
"commands": {
"--verify-package": {
"exit": 0,
"stdout": "\r\n== 检查刷机包 / checking the package\r\n\r | 校验文件 / verifying the files 0 s \r OK 校验文件 / verifying the files 0 s \r\n m8-openwrt-25.12.5-tf-20261015-030719 (6.18.54-m8-probe12-g020b970e351e-dirty)\r\nPackage verified / 安装包校验通过,未连接设备。\r\n\r\n============================================================\r\n[SUCCESS / 成功] 0.3 s\r\n============================================================\r\n",
"stderr": ""
}
},
"protocol_ok": true,
"utf8_error": "Select a device / 请选择设备",
"adb_version": "Android Debug Bridge version 1.0.41\r\nVersion 37.0.1-15733141\r\nInstalled as D:\\Git\\e5-linux\\out\\gui-releases\\20261015\\m8-openwrt-gui-1.0.0\\tools\\adb.exe\r\nRunning on Windows 10.0.26100\r\n"
},
{
"package": "t551m-openwrt-gui-1.0.0",
"commands": {
"--verify-package": {
"exit": 0,
"stdout": "\r\n== 检查刷机包 / checking the package\r\n\r | 校验文件 / verifying the files 0 s \r OK 校验文件 / verifying the files 0 s \r\n t551m-openwrt-25.12.5-tf-20261015-030630 (6.18.54-t551m-otg10-g020b970e351e-dirty)\r\nPackage verified / 安装包校验通过,未连接设备。\r\n\r\n============================================================\r\n[SUCCESS / 成功] 0.3 s\r\n============================================================\r\n",
"stderr": ""
}
},
"protocol_ok": true,
"utf8_error": "Select a device / 请选择设备",
"adb_version": "Android Debug Bridge version 1.0.41\r\nVersion 37.0.1-15733141\r\nInstalled as D:\\Git\\e5-linux\\out\\gui-releases\\20261015\\t551m-openwrt-gui-1.0.0\\tools\\adb.exe\r\nRunning on Windows 10.0.26100\r\n"
},
{
"package": "mu300-openwrt-6.18.54-gui-1.0.0",
"commands": {
"--check": {
"exit": 0,
"stdout": "MU300 desktop package verified; kernel 6.18\r\n\r\n========================================================\r\n[CHECK PASSED / 校验通过] Package checksums passed / 安装包校验通过。\r\nElapsed / 总耗时: 0 s\r\n",
"stderr": ""
},
"--check-boot": {
"exit": 0,
"stdout": "MU300 desktop package verified; kernel 6.18\r\nDesktop boot build verified: sd Android slot a (no device writes)\r\nDesktop boot build verified: install-part Android slot b (no device writes)\r\n\r\n========================================================\r\n[CHECK PASSED / 校验通过] Desktop boot construction passed / 桌面启动镜像构建检查通过。\r\nElapsed / 总耗时: 1 s\r\n",
"stderr": ""
}
},
"protocol_ok": true,
"utf8_error": "Select a device / 请选择设备",
"adb_version": "Android Debug Bridge version 1.0.41\r\nVersion 37.0.1-15733141\r\nInstalled as D:\\Git\\mu300-linux-clean-tf-7.2\\release\\gui-20261015\\mu300-openwrt-6.18.54-gui-1.0.0\\tools\\adb.exe\r\nRunning on Windows 10.0.26100\r\n"
},
{
"package": "mu300-openwrt-7.2.8-gui-1.0.0",
"commands": {
"--check": {
"exit": 0,
"stdout": "MU300 desktop package verified; kernel 7.2\r\n\r\n========================================================\r\n[CHECK PASSED / 校验通过] Package checksums passed / 安装包校验通过。\r\nElapsed / 总耗时: 0 s\r\n",
"stderr": ""
},
"--check-boot": {
"exit": 0,
"stdout": "MU300 desktop package verified; kernel 7.2\r\nDesktop boot build verified: sd Android slot a (no device writes)\r\nDesktop boot build verified: install-part Android slot b (no device writes)\r\n\r\n========================================================\r\n[CHECK PASSED / 校验通过] Desktop boot construction passed / 桌面启动镜像构建检查通过。\r\nElapsed / 总耗时: 1 s\r\n",
"stderr": ""
}
},
"protocol_ok": true,
"utf8_error": "Select a device / 请选择设备",
"adb_version": "Android Debug Bridge version 1.0.41\r\nVersion 37.0.1-15733141\r\nInstalled as D:\\Git\\mu300-linux-clean-tf-7.2\\release\\gui-20261015\\mu300-openwrt-7.2.8-gui-1.0.0\\tools\\adb.exe\r\nRunning on Windows 10.0.26100\r\n"
}
]
+61
View File
@@ -0,0 +1,61 @@
#!/bin/sh
set -eu
export FORCE_UNSAFE_CONFIGURE=1
cd /build
exec 9>/build/unisoc-hostapd.lock
flock 9
[ -d openwrt/.git ] || git clone -q --depth 1 --branch "v$VER" \
https://git.openwrt.org/openwrt/openwrt.git openwrt
cd openwrt
[ "$(git rev-parse HEAD)" = "$(git rev-parse "v$VER^{commit}")" ] || {
echo 'Unisoc WPA3: build tree differs from the requested release' >&2; exit 1;
}
H=package/network/services/hostapd
W=package/network/config/wifi-scripts
grep -q 'PKG_SOURCE_VERSION:=ca266cc24d8705eb1a2a0857ad326e48b1408b20' "$H/Makefile"
grep -q 'PKG_MIRROR_HASH:=59ac677093f524ff98588abd9f33805a336a6e929d6814222f0d784c854f2343' "$H/Makefile"
# Keep APK upgrades from replacing just one half of the driver/daemon ABI.
sed -i 's/^PKG_RELEASE:=.*/PKG_RELEASE:=1001/' "$H/Makefile" "$W/Makefile"
python3 /src/patch-hostapd-sae.py wifi "$W/files"
python3 /src/patch-hostapd-sae.py reload "$H/files"
# Preserve the rest of an existing cross-build configuration and its feeds.
if [ ! -s .config ]; then
printf '%s\n' 'CONFIG_TARGET_armsr=y' 'CONFIG_TARGET_armsr_armv8=y' 'CONFIG_TARGET_armsr_armv8_DEVICE_generic=y' 'CONFIG_ALL_KMODS=n' 'CONFIG_ALL_NONSHARED=n' > .config
fi
sed -i -E '/^CONFIG_PACKAGE_(wpad[^=]*|hostapd[^=]*)=/d' .config
printf '%s\n' 'CONFIG_PACKAGE_wpad-basic-mbedtls=m' 'CONFIG_PACKAGE_hostapd-common=m' \
'CONFIG_PACKAGE_wifi-scripts=m' 'CONFIG_WIFI_SCRIPTS_UCODE=y' \
'CONFIG_SIGNED_PACKAGES=n' >> .config
make defconfig
# Out-of-tree Unisoc modules do not select OpenWrt kmod-mac80211 options.
# Preserve the official daemon's AC/AX/BE config parser and PHY support.
hostapd_make() {
make CONFIG_DRIVER_11AC_SUPPORT=y CONFIG_DRIVER_11AX_SUPPORT=y \
CONFIG_DRIVER_11BE_SUPPORT=y "$@"
}
hostapd_make "$H/clean"
hostapd_make "$H/prepare" V=s
source_dir=$(find build_dir/target-* -mindepth 2 -maxdepth 2 -type d -path '*/hostapd-wpad-basic-mbedtls/hostapd-*')
[ -n "$source_dir" ] && [ "$(printf '%s\n' "$source_dir" | wc -l)" = 1 ] || {
echo 'Unisoc WPA3: expected one prepared basic-mbedtls source' >&2; exit 1;
}
python3 /src/patch-hostapd-sae.py source "$source_dir"
hostapd_make -j"$JOBS" "$H/compile" V=s
make "$W/clean"
make -j"$JOBS" "$W/compile" V=s
stage=$(mktemp -d /out/.wifi-sae.XXXXXX)
trap 'rm -rf "$stage"' EXIT
for pkg in wpad-basic-mbedtls hostapd-common wifi-scripts; do
apk=$(find bin -type f -name "$pkg-*-r1001.apk")
[ -n "$apk" ] && [ "$(printf '%s\n' "$apk" | wc -l)" = 1 ] || {
echo "Unisoc WPA3: expected exactly one $pkg APK" >&2; exit 1;
}
cp "$apk" "$stage/"
done
(cd "$stage" && sha256sum ./*.apk > SHA256SUMS)
printf '%s\n' "$BUILD_ID" > "$stage/build-id"
printf '%s\n' "OpenWrt $VER" "hostapd ca266cc24d8705eb1a2a0857ad326e48b1408b20" \
'Unisoc SAE: firmware authentication + hostapd four-way handshake' > "$stage/source-info"
cp "$stage/"*.apk "$stage/SHA256SUMS" "$stage/source-info" /out/
# Publish the success marker after every APK and its checksum is in place.
mv "$stage/build-id" /out/build-id
+30
View File
@@ -0,0 +1,30 @@
#!/bin/sh
# Build all three matching APKs: wpad, hostapd-common and wifi-scripts.
set -eu
TOP=$(cd "$(dirname "$0")/.." && pwd)
VER=${UNISOC_WRT_VER:-25.12.5}
[ "$VER" = 25.12.5 ] || {
echo 'Unisoc WPA3: update the pinned source/build checks for this OpenWrt version' >&2
exit 1
}
OUT=${1:-$TOP/work/wifi-sae}
mkdir -p "$OUT"
OUT=$(cd "$OUT" && pwd)
stamp=$(cat "$TOP/openwrt/build-hostapd.sh" "$TOP/openwrt/build-hostapd-inner.sh" \
"$TOP/openwrt/hostapd.Dockerfile" "$TOP/openwrt/patch-hostapd-sae.py" \
"$TOP/openwrt/hostapd-unisoc-sae.h" "$TOP/openwrt/hostapd-unisoc.sh" \
"$TOP/openwrt/hostapd-unisoc.uc" "$TOP/openwrt/wifi-sae-state.py" |
sha256sum | cut -d' ' -f1)
if [ -s "$OUT/build-id" ] && [ "$(cat "$OUT/build-id")" = "$stamp" ] &&
[ -s "$OUT/SHA256SUMS" ] && python3 "$TOP/openwrt/wifi-sae-state.py" "$OUT" >/dev/null; then
echo 'Unisoc WPA3: verified APK cache'
exit 0
fi
docker build --platform linux/amd64 -t unisoc-hostapd-build \
-f "$TOP/openwrt/hostapd.Dockerfile" "$TOP/openwrt"
docker run --rm --platform linux/amd64 \
-v "${UNISOC_WRT_CACHE:-e5-openwrt-src}:/build" \
-v "$TOP/openwrt:/src:ro" -v "$OUT:/out" \
-e "VER=$VER" -e "BUILD_ID=$stamp" -e "JOBS=${UNISOC_JOBS:-4}" \
unisoc-hostapd-build sh /src/build-hostapd-inner.sh
python3 "$TOP/openwrt/wifi-sae-state.py" "$OUT" >/dev/null
+7 -1
View File
@@ -86,6 +86,8 @@ URL=$BASEURL/$VER/targets/armsr/armv8
# Build/install the patched APK before exposing LuCI's Mount Points page.
BLOCK_APK=$TOP/work/block-mount-mu300.apk
sh "$TOP/openwrt/build-block-mount.sh" "$BLOCK_APK"
WIFI_APKS="$TOP/work/wifi-sae"
UNISOC_WRT_VER="$VER" sh "$TOP/openwrt/build-hostapd.sh" "$WIFI_APKS"
cd "$TOP"
if [ ! -f "openwrt/$TARBALL" ]; then
@@ -129,6 +131,7 @@ docker run --rm --platform linux/arm64 \
-v "$THEME_APK":/in/luci-theme-aurora.apk:ro \
-v "$BLOCK_APK":/in/block-mount-mu300.apk:ro \
-v "$BLOCK_APK.build-id":/in/block-mount.build-id:ro \
-v "$WIFI_APKS":/in/wifi-sae:ro \
-v "$TOP/work/luci-app-aurora-config-1.2.5-r20260920.apk":/in/luci-app-aurora-config.apk:ro \
-v "$TOP/work/luci-i18n-aurora-config-zh-cn-26.262.58276.362887a.apk":/in/aurora-config-zh-cn.apk:ro \
-v "$TOP/work/luci-i18n-aurora-config-tr-26.262.58276.362887a.apk":/in/aurora-config-tr.apk:ro \
@@ -145,7 +148,8 @@ apk_retry() {
apk_retry update >/dev/null
# openssl-util: mu300-vpn fetches the VPN server certificate with it to pin, for links that ask for allowInsecure;
# i2c-tools, gpiod-tools: mu300-usb (the charger of the U30 Air) and mu300-nfc (its NFC tag)
apk_retry add wpad-basic-mbedtls wifi-scripts iwinfo wireless-regdb iw bash ip-full coreutils-stty openssl-util curl ca-bundle msmtp ucode ucode-mod-fs ucode-mod-ubus ucode-mod-uci ucode-mod-uloop ucode-mod-socket \
apk_retry add --allow-untrusted /in/wifi-sae/*.apk >/dev/null
apk_retry add iwinfo wireless-regdb iw bash ip-full coreutils-stty openssl-util curl ca-bundle msmtp ucode ucode-mod-fs ucode-mod-ubus ucode-mod-uci ucode-mod-uloop ucode-mod-socket \
i2c-tools gpiod-tools >/dev/null
apk_retry add --allow-untrusted /in/block-mount-mu300.apk >/dev/null
apk_retry add --allow-untrusted /in/luci-theme-aurora.apk >/dev/null
@@ -172,6 +176,8 @@ cp -a /in/opt-mu300 $R/opt/mu300
cp -a /in/overlay/. $R/
mkdir -p $R/etc/mu300
cp /in/block-mount.build-id $R/etc/mu300/block-mount.build-id
cp /in/wifi-sae/build-id $R/etc/mu300/wifi-sae.build-id
cp /in/wifi-sae/source-info $R/etc/mu300/wifi-sae.source-info
for f in sbin/block lib/libblkid-tiny.so etc/init.d/fstab; do
[ -s "$R/$f" ] || { echo "patched block-mount required file missing: $f" >&2; exit 1; }
done
+93
View File
@@ -0,0 +1,93 @@
/* SPDX-License-Identifier: BSD-3-Clause */
/* Recovered from the Unisoc Android hostapd (E5), not an on-air extension.
* The firmware appends dd 34 40 45 da 04 <PMK:32> <PMKID:16> to NEW_STATION.
* Only consume it on explicitly opted-in firmware-SME interfaces. WPA2 and
* other drivers must never accept a peer-supplied IE as an authentication key.
*/
#ifdef CONFIG_SAE
#include "pmksa_cache_auth.h"
static int unisoc_sae_import(struct hostapd_data *hapd, struct sta_info *sta,
const u8 *ies, size_t ies_len)
{
const u8 *rsn, *key_ie, *pmk = NULL, *pmkid = NULL;
struct wpa_ie_data parsed;
struct rsn_pmksa_cache_entry *entry;
struct sae_data *sae;
int i;
if (!hapd->conf->unisoc_sae ||
!(hapd->conf->wpa_key_mgmt & WPA_KEY_MGMT_SAE))
return 0;
if (!(hapd->iface->drv_flags2 & WPA_DRIVER_FLAGS2_SAE_OFFLOAD_AP))
return -1;
rsn = get_ie(ies, ies_len, WLAN_EID_RSN);
if (!rsn || wpa_parse_wpa_ie_rsn(rsn, rsn[1] + 2, &parsed))
return -1;
if (parsed.key_mgmt != WPA_KEY_MGMT_SAE) {
/* A peer may reassociate with WPA2 after previously using SAE. */
if (sta->sae) {
sae_clear_data(sta->sae);
bin_clear_free(sta->sae, sizeof(*sta->sae));
sta->sae = NULL;
}
sta->auth_alg = WLAN_AUTH_OPEN;
wpa_auth_set_auth_alg(sta->wpa_sm, WLAN_AUTH_OPEN);
return 0;
}
if (!(parsed.capabilities & WPA_CAPABILITY_MFPC))
return -1;
key_ie = get_vendor_ie(ies, ies_len, 0x4045da04);
if (key_ie) {
if (key_ie[1] != 4 + SAE_PMK_LEN + PMKID_LEN)
return -1;
if (get_vendor_ie(key_ie + key_ie[1] + 2,
ies + ies_len - (key_ie + key_ie[1] + 2),
0x4045da04))
return -1;
pmk = key_ie + 6;
pmkid = pmk + SAE_PMK_LEN;
} else {
/* A real PMKSA reassociation can omit a fresh firmware key.
* Never substitute the ordinary WPA2 PSK or a stale station key.
*/
for (i = 0; i < parsed.num_pmkid; i++) {
entry = wpa_auth_pmksa_get(hapd->wpa_auth, sta->addr,
parsed.pmkid + i * PMKID_LEN);
if (entry && entry->akmp == WPA_KEY_MGMT_SAE &&
entry->pmk_len == SAE_PMK_LEN) {
pmk = entry->pmk;
pmkid = entry->pmkid;
break;
}
}
if (!pmk)
return -1;
}
sae = os_zalloc(sizeof(*sae));
if (!sae)
return -1;
os_memcpy(sae->pmk, pmk, SAE_PMK_LEN);
os_memcpy(sae->pmkid, pmkid, PMKID_LEN);
sae->pmk_len = SAE_PMK_LEN;
sae->akmp = WPA_KEY_MGMT_SAE;
sae->state = SAE_ACCEPTED;
if (!hapd->conf->disable_pmksa_caching &&
wpa_auth_pmksa_add_sae(hapd->wpa_auth, sta->addr, sae->pmk,
sae->pmk_len, sae->pmkid, WPA_KEY_MGMT_SAE,
false, sta->vlan_id) < 0) {
bin_clear_free(sae, sizeof(*sae));
return -1;
}
if (sta->sae) {
sae_clear_data(sta->sae);
bin_clear_free(sta->sae, sizeof(*sta->sae));
}
sta->sae = sae;
sta->auth_alg = WLAN_AUTH_SAE;
wpa_auth_set_auth_alg(sta->wpa_sm, WLAN_AUTH_SAE);
wpa_auth_add_sae_pmkid(sta->wpa_sm, sae->pmkid);
return 0;
}
#endif
+26
View File
@@ -0,0 +1,26 @@
# SC2355 firmware owns SAE authentication; hostapd owns the four-way handshake.
# Called inside hostapd_set_bss_options(), before encryption defaults are set.
unisoc_sae_bss_options() {
case "$auth_type" in
sae|psk-sae) ;;
*) return 0 ;;
esac
# PMF=0 from an earlier WPA2 profile is invalid for SAE. Normalize the
# generated configuration without rewriting the user's unrelated UCI.
case "$auth_type:$ieee80211w" in
sae:0|sae:1) ieee80211w=2 ;;
psk-sae:0) ieee80211w=1 ;;
esac
local module
module=$(readlink -f "/sys/class/ieee80211/$phy/device/driver/module" 2>/dev/null || true)
case "$module" in
*/sprd_wlan_combo) ;;
*) return 0 ;;
esac
append bss_conf 'unisoc_sae=1' "$N"
# This BSP password-entry ABI has no negotiated H2E mechanism. Leave
# explicit settings intact; the driver rejects unsupported H2E clearly.
set_default sae_pwe 0
# The firmware association event cannot carry RSN Selection to hostapd.
rsn_override=0
}
+19
View File
@@ -0,0 +1,19 @@
// Firmware-SME configuration shared by the OpenWrt ucode AP generator.
export function configure(config, module) {
if (!(config.auth_type in [ 'sae', 'psk-sae' ]))
return;
if (config.auth_type == 'sae')
config.ieee80211w = 2;
else if (!config.ieee80211w)
config.ieee80211w = 1;
if (module != '/sys/module/sprd_wlan_combo')
return;
config.unisoc_sae = 1;
config.sae_pwe ??= 0;
// This legacy SME does not report the RSN Selection extension in its
// association event. Advertising RSN Override then breaks message 2/4.
config.rsn_override = 0;
config.rsn_override_pairwise = null;
config.rsn_override_key_mgmt = null;
config.rsn_override_mfp = null;
};
+6
View File
@@ -0,0 +1,6 @@
FROM debian:trixie
RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
build-essential ca-certificates clang curl file flex bison gawk gettext git \
libncurses-dev libssl-dev patch pkg-config python3 python3-setuptools rsync \
swig unzip wget xz-utils zlib1g-dev zstd util-linux \
&& rm -rf /var/lib/apt/lists/*
Loaded 100 of 111 files, more files were not shown because too many files have changed in this diff. Show more