Fix online shrink preflight and add a verified ADB reboot action

Retain original recovery GPT backups and hand the approved resized layout to the real desktop preflight. Add an explicit restart button with serialized device identity checks, loading and expected-disconnect handling. Add installer-only native refresh for both kernel releases while preserving boot, rootfs and Magisk payloads byte-for-byte.
This commit is contained in:
kanoqwq committed 2026-10-30 04:13:26 +08:00
1 parent c84da8bac4
commit c69be3a32c
18 files changed
+583 -27

No files matched your search

+14
View File
@@ -123,6 +123,20 @@ python3 tools/build-release.py run --workspace /home/kano/openwrt-build --label
工具文件逐项按发布包内 `diff-tool.json` 核验,保留 Mac App 签名内容和可执行权限,
不解压固件、不重新编译;输出 ZIP 与 SHA256,已有目标不覆盖。
## 仅刷新原生安装器和 Diff Studio
GUI/后端变更时,先按 AGENT-BUILD 规范原生重编 Windows 和 Apple Silicon 交付件,然后执行:
```sh
python3 tools/build-release.py refresh-installers --workspace /home/kano/openwrt-build \
--profiles all --source-release /absolute/repo/release/<verified-task> --label native-installer
```
该入口验证原发布及当前原生程序指纹,流式替换两平台安装器、共享后端、Diff Studio 和各层清单,
移除旧运行环境中已淘汰的受管文件;不改 boot、rootfs、Magisk 载荷及系统版本。
新 ZIP 后缀 `-installer-g<提交>` 标记宿主工具修订,原发布不覆盖。
仅有外部 Python 入口变化且原生后端未变时,仍使用下面的轻量入口。
## 仅修复外部安装器 Python 入口
当变更只涉及 `desktop/installer.py` 的外部入口逻辑时,可流式修补已验证发布,
@@ -35,6 +35,23 @@
本次接入的是统一 Tauri GUI 的规划和事务流程。原独立 CLI 脚本仍保留原有
离线安装行为,不宣称所有旧 CLI 也已自动改用在线缩容。
## 2026-10-30:缩容后交接旧桌面入口
F50 的用户诊断显示:在线缩容及 Android 重启核验已成功,8 GiB 已回收,
但随后报告 `GPT changed during preflight; nothing was installed`。
原因是 GUI 的旧入口备份代理将缩容前 GPT 当成当前预检快照交给桌面入口,
与它刚读到的缩容后 GPT 不同;不是这份日志中的缩容失败或未知 GPT 损坏。
代理现在仅在在线缩容状态为 verified、恢复文件哈希与原始备份一致、
候选表精确等于该次 userdata 缩容结果时,向旧入口交付缩容后的 GPT 快照,
并为复制出的文件生成对应校验清单。主备份目录中的原始 GPT 和身份记录不覆盖,
继续供恢复与卸载归还空间使用。旧入口针对实际磁盘变化的预检仍保留。
回归涵盖 eMMC/512、UFS/4K、Android A/B、损坏恢复文件、未完成缩容、
不相干分区改动及原始备份不符。MU300 还执行真实桌面 install 入口:
旧快照可复现报错,新快照能通过交接;真正变化的磁盘快照仍在载荷/写入前停止。
这些为离线回归,没有再次缩容用户设备。修复在冻结后端中,旧 EXE/App 需重编。
## 构建与维护
- 核心:installer/backend/online_shrink.py;两仓库相同协议与实现。
+18 -3
View File
@@ -182,13 +182,28 @@ class Adapter:
mapping.update({f'{name}_{slot}.img':f'{name}_{slot}.bin' for name in ('boot','uboot','sml','teecfg','trustos','vbmeta') for slot in ('a','b')})
if any(name not in sums or sha(source/name)!=sums[name] for name in mapping.values()):
raise ValueError('Verified backup is incomplete or damaged / 已校验备份缺失或损坏')
snapshots = {}
if self.ctx.record.get('online_shrink'):
from .online_shrink import OnlineShrink
names = ('gpt-first.bin', 'gpt-last.bin')
original = tuple((source/name).read_bytes() for name in names)
snapshots = dict(zip(names, OnlineShrink(self).installation_gpt(original)))
directory.mkdir(parents=True,exist_ok=False)
atomic_json(directory/'identity.json',{**storage,'serial':android.serial,'android_slot':android.slot})
copied_sums = {}
for target,name in mapping.items():
self.ctx.boundary()
shutil.copyfile(source/name,directory/target)
if sha(directory/target)!=sums[name]:raise ValueError('Legacy backup copy checksum mismatch')
(directory/'SHA256SUMS').write_text(''.join(sums[name]+' '+target+'\n' for target,name in mapping.items()),encoding='utf-8')
if name in snapshots:
# The legacy preflight needs today's approved GPT; the main
# backup remains the pre-resize recovery/uninstall baseline.
(directory/target).write_bytes(snapshots[name])
expected_sum = hashlib.sha256(snapshots[name]).hexdigest()
else:
shutil.copyfile(source/name,directory/target)
expected_sum = sums[name]
if sha(directory/target)!=expected_sum:raise ValueError('Legacy backup copy checksum mismatch')
copied_sums[target] = expected_sum
(directory/'SHA256SUMS').write_text(''.join(h+' '+target+'\n' for target,h in copied_sums.items()),encoding='utf-8')
self.ctx.log('Reused verified computer backups for the compatible installer; no second device backup',scope='backup')
def wait_android(self, *_):
+19
View File
@@ -142,6 +142,25 @@ class OnlineShrink:
output[name] = path.read_bytes()
return output
def installation_gpt(self, original):
"""Supply the verified post-resize baseline, retaining recovery originals."""
j = self.r['online_shrink']
if j.get('state') != 'verified':
raise RecoveryRequired('Online resize is not verified / 在线缩容尚未校验完成')
files = self.files()
if original != (files['old-first'], files['old-last']):
raise RecoveryRequired('Original GPT backup differs from the resize record / 原始 GPT 备份与缩容记录不符')
s = self.r['device']['storage']
data = partition(gpt.gpt_space(*original, s['DISK_SIZE']), 'userdata')
updated = tuple(candidate(original, s['DISK_SIZE'], s['NODE'],
data['end']-data['start']+1, s['SIZE']))
if (j['sectors'] != s['DISK_SIZE'] or j['new_sectors'] != s['SIZE'] or
self.r['plan'].get('shrink_strategy') != 'online-f2fs' or
self.r['plan'].get('gap_start') != data['start']+s['SIZE'] or
updated != (files['new-first'], files['new-last'])):
raise RecoveryRequired('Installation GPT differs from the verified resize / 安装 GPT 与已校验缩容结果不符')
return updated
def prepare(self):
d = self.r['device']
actual = self.a.probe(d['serial'],'part')
+60 -1
View File
@@ -116,6 +116,7 @@ class Service:
self.stop = threading.Event()
self.verification_lock = threading.Lock()
self.verification_request = None
self.reboot_request = None
self.verification_wake = threading.Event()
from .ota_desktop import Desktop
self.ota = Desktop(self.package_root, self.emit, self.store.base)
@@ -167,6 +168,16 @@ class Service:
return {'accepted': False}
if command == 'can_close':
return not self.worker or not self.worker.is_alive()
if command == 'reboot_device':
context = self.active
if (not context or not self.worker or not self.worker.is_alive() or
p.get('transaction') != context.record['id'] or
not self.can_reboot_device(context.record)):
raise ValueError('Device restart is unavailable at this stage / 当前阶段不能重启设备')
with self.verification_lock:
self.reboot_request = context.record['id']
self.verification_wake.set()
return {'accepted':True}
if command == 'verify_openwrt':
context = self.active
if (not context or not self.worker or not self.worker.is_alive() or
@@ -504,13 +515,60 @@ class Service:
if self.stop.wait(3):
raise Cancelled()
@staticmethod
def can_reboot_device(record):
return (not record.get('unsafe') and not record.get('cancel_requested') and
record.get('stage') == 'openwrt_boot' and
record.get('status') in ('waiting_user','waiting_device') and
record.get('choices',{}).get('method') in ('tf','part','reinstall','image','boot') and
record.get('details',{}).get('reboot_manually') is True and
not record.get('openwrt_confirmed') and not record.get('adb_reboot_requested'))
def process_device_reboot(self, context, adapter):
"""Run on the existing device-owning worker, never during an install write."""
r = context.record
with self.verification_lock:
if self.reboot_request != r['id']:
return
submitted = False
try:
context.boundary()
if not self.can_reboot_device(r):
raise ValueError('Device restart is no longer available / 当前阶段已不能重启设备')
actual = adapter.probe(r['device']['serial'],'boot')
if (actual.get('readiness') != 'ready' or actual.get('system') != 'Android' or
any(actual.get(k) != r['device'].get(k) for k in ('serial','cid','profile','slot'))):
raise ValueError('The recorded Android device is unavailable; if already restarting, wait, otherwise restart it manually / 无法确认原 Android 设备;若已重启请等待,否则请手动重启')
context.boundary()
r['adb_reboot_requested'] = True
self.openwrt_wait_stage(context)
context.log('Requesting ADB reboot of the verified installation device / 正在请求已核验设备通过 ADB 重启',scope='reboot')
submitted = True
adapter.adb.call('reboot',timeout=15)
except Cancelled:
raise
except Exception as error:
import subprocess
lost = submitted and (isinstance(error,(EOFError,subprocess.TimeoutExpired)) or
isinstance(error,ConnectionError) and any(word in str(error).lower()
for word in ('closed','offline','not found','no devices','reset','eof','disconnected')))
if lost:
context.log('ADB disconnected after the reboot request; waiting for OpenWrt / 重启请求后 ADB 已断开,等待 OpenWrt',scope='reboot')
else:
r['adb_reboot_requested'] = False
self.openwrt_wait_stage(context,str(error))
finally:
with self.verification_lock:
if self.reboot_request == r['id']:
self.reboot_request = None
def openwrt_wait_stage(self, context, error=None, connection_state=None):
r = context.record
# These entrypoints send their own reboot request. The other install
# paths finish after verified writes and explicitly leave reboot to the user.
manual = r['choices']['method'] != 'update' and not (
r['package']['adapter'] == 'e5' and r['choices']['method'] == 'boot')
manual = manual and not r.get('openwrt_confirmed',False)
manual = manual and not r.get('openwrt_confirmed',False) and not r.get('adb_reboot_requested',False)
host = r['choices'].get('host') or ('192.168.9.1' if r['package']['adapter'] == 'e5' else
'192.168.77.1')
context.stage('openwrt_boot', 'waiting_user' if manual or error else 'waiting_device',
@@ -525,6 +583,7 @@ class Service:
# No network/interface changes and no automatic hotspot connection.
while True:
context.boundary()
self.process_device_reboot(context,adapter)
with self.verification_lock:
pending = self.verification_request
self.verification_request = None
+47
View File
@@ -0,0 +1,47 @@
"""Installation reboot button: bound request, loading, failure recovery and i18n."""
from playwright.sync_api import sync_playwright
from ui_smoke import fixture_context,BRIDGE,ROOT,layout,settle
def main():
with sync_playwright() as p:
browser=p.chromium.launch()
context=fixture_context(browser,viewport={'width':800,'height':650})
context.add_init_script(BRIDGE+"localStorage.setItem('onboarding-v1','seen');")
page=context.new_page();errors=[]
page.on('pageerror',lambda e:errors.append(str(e)))
page.goto('http://127.0.0.1:1420')
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('checkbox').check()
page.get_by_role('button',name='确认并开始').click();settle(page)
assert page.get_by_role('button',name='重启设备',exact=True).count()==0
page.evaluate("window.__emitFixture({stage:'openwrt_boot',status:'waiting_user',revision:10,details:{host:'192.168.9.1',reboot_manually:true}})")
settle(page);layout(page)
restart=page.get_by_role('button',name='重启设备',exact=True)
assert restart.is_enabled()
restart.click();settle(page)
assert page.get_by_role('button',name='正在请求重启…',exact=True).is_disabled()
assert page.evaluate("window.__fixture.calls.filter(x=>x.command==='reboot_device').map(x=>x.params)")==[{'transaction':'a'*32}]
page.evaluate("window.__emitFixture({stage:'openwrt_boot',status:'waiting_device',revision:11,details:{host:'192.168.9.1',reboot_manually:false}})")
settle(page);layout(page)
assert page.get_by_role('button',name='重启设备',exact=True).count()==0
page.evaluate("window.__emitFixture({stage:'openwrt_boot',status:'waiting_user',revision:12,details:{host:'192.168.9.1',reboot_manually:true,verification_error:'ADB unavailable / ADB 不可用'}})")
settle(page)
assert page.get_by_role('button',name='重启设备',exact=True).is_enabled()
page.evaluate("window.__fixture.fail='reboot_device'")
page.get_by_role('button',name='重启设备',exact=True).click();settle(page)
assert page.get_by_role('button',name='重启设备',exact=True).is_enabled()
page.get_by_role('button',name='关闭',exact=True).click() if page.get_by_role('button',name='关闭',exact=True).count() else None
page.get_by_label('语言').select_option('en');page.get_by_label('Theme').select_option('dark')
settle(page);layout(page)
assert page.get_by_role('button',name='Restart device',exact=True).is_enabled()
page.evaluate("window.__emitFixture({stage:'transfer_install',status:'running',revision:13,details:{}})")
settle(page)
assert page.get_by_role('button',name='Restart device',exact=True).count()==0
assert not errors,errors
browser.close()
print('Device reboot UI passed: transaction binding, loading, no automatic request, expected disconnect view, retry and bilingual layout')
if __name__=='__main__':main()
+2 -2
View File
@@ -60,7 +60,7 @@ def main():
page.screenshot(path=str(ROOT/'screenshots/install-activity-debug-zh.png'))
page.evaluate("window.__emitFixture({stage:'openwrt_boot',status:'waiting_user',revision:13,details:{host:'192.168.9.1',reboot_manually:true}})")
settle(page);layout(page)
assert page.locator('h1').inner_text()=='请现在手动重启设备'
assert page.locator('h1').inner_text()=='准备进入 OpenWrt'
assert '用户名 root,默认密码 root' in page.locator('.login-hint').inner_text()
guidance=page.locator('.boot-guidance')
assert '已开始重启或已进入 OpenWrt' in guidance.inner_text()
@@ -74,7 +74,7 @@ def main():
page.screenshot(path=str(ROOT/'screenshots/manual-restart-log-zh.png'))
confirm.click();settle(page)
assert page.evaluate("window.__fixture.calls.filter(c=>c.command==='verify_openwrt').at(-1).params")=={'transaction':'a'*32,'host':'192.168.9.22','password':'fixture-private'}
assert page.locator('h1').inner_text()=='请现在手动重启设备'
assert page.locator('h1').inner_text()=='准备进入 OpenWrt'
page.evaluate("window.__emitFixture({stage:'openwrt_boot',status:'waiting_user',revision:14,details:{host:'192.168.9.22',boot_confirmed:true,reboot_manually:false,verification_error:'Management address belongs to another device / 管理地址对应另一台设备'}})")
settle(page);layout(page)
assert '另一台设备' in page.locator('.verification-error').inner_text()
+1 -1
View File
@@ -9,7 +9,7 @@ import time
from urllib.request import urlopen
ROOT=Path(__file__).resolve().parents[1]
CHECKS=('ui_smoke','help_smoke','refresh_smoke','method_smoke','ordering_smoke','diagnostics_smoke','update_smoke','support_smoke','wireless_smoke','uninstall_smoke','mtp_smoke','online_shrink_smoke')
CHECKS=('ui_smoke','help_smoke','refresh_smoke','method_smoke','ordering_smoke','diagnostics_smoke','device_reboot_smoke','update_smoke','support_smoke','wireless_smoke','uninstall_smoke','mtp_smoke','online_shrink_smoke')
def main():
+114 -1
View File
@@ -12,7 +12,7 @@ from unittest.mock import Mock, patch
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
from backend.binary_io import pull_binary
from backend.adapter import Adapter
from backend.state import Context, Store, sha
from backend.state import Context, RecoveryRequired, Store, sha
from backend.transport import Adb
@@ -105,6 +105,119 @@ class LegacyGUI(unittest.TestCase):
self.assertTrue((target/'SHA256SUMS').is_file())
self.adapter.adb.read.assert_called_once_with('bounded read')
def online_backup_fixture(self, block=512, slot='a'):
from test_online_shrink import device
from backend.online_shrink import candidate
from backend.service import plan_install
d, original, total = device(block)
d.update(serial='selected', slot='_'+slot)
d['storage']['NODE'] = 'mmcblk0p2' if block == 512 else 'sdb2'
plan = plan_install({'adapter':'mu300'}, d, {'method':'part','size_gib':4})
updated = tuple(candidate(original,total,d['storage']['NODE'],d['storage']['SIZE'],plan['new_sectors']))
source = self.ctx.directory/'backup'
(source/'identity.json').write_text(json.dumps(d))
for name,raw in zip(('gpt-first.bin','gpt-last.bin'),original):
(source/name).write_bytes(raw)
sums = {p.name:sha(p) for p in source.iterdir() if p.name != 'checksums.json'}
(source/'checksums.json').write_text(json.dumps(sums))
folder = self.ctx.directory/'online-shrink'
folder.mkdir(exist_ok=True)
files = dict(zip(('old-first','old-last','new-first','new-last'),(*original,*updated)))
for name,raw in files.items():(folder/name).write_bytes(raw)
self.record['online_shrink'] = dict(state='verified',sectors=total,new_sectors=plan['new_sectors'],
files={name:sha(folder/name) for name in files})
d['storage']['SIZE'] = plan['new_sectors']
d['userdata_bytes'] = plan['android_bytes']
plan.update(target='GPT unallocated space',two_stage=False,offline=False)
self.record.update(device=d,plan=plan)
self.storage = d['storage']
self.android.slot = slot
return original, updated
def test_online_resize_handoff_preserves_originals_and_uses_verified_new_gpt(self):
for block in (512,4096):
for slot in ('a','b'):
with self.subTest(block=block,slot=slot):
original, updated = self.online_backup_fixture(block,slot)
source = self.ctx.directory/'backup'
before = {p.name:p.read_bytes() for p in source.iterdir()}
target = self.ctx.directory/f'legacy-backups/online-{block}-{slot}'
self.android.backup(target,self.storage)
self.assertEqual(tuple((target/n).read_bytes() for n in ('gpt-first.bin','gpt-last.bin')),updated)
self.assertNotEqual(original,updated)
self.assertEqual({p.name:p.read_bytes() for p in source.iterdir()},before)
for line in (target/'SHA256SUMS').read_text().splitlines():
digest,name = line.split()
self.assertEqual(sha(target/name),digest)
self.assertEqual((target/'boot_a.img').read_bytes(),before['boot_a.bin'])
self.adapter.adb.read.assert_not_called()
def test_online_handoff_refuses_pending_corrupt_or_unrelated_gpt_changes(self):
from backend.uninstall import table,with_table
for failure in ('pending','corrupt','unrelated','wrong-size','wrong-original'):
with self.subTest(failure=failure):
self.online_backup_fixture()
folder = self.ctx.directory/'online-shrink'
j = self.record['online_shrink']
if failure == 'pending':j['state']='gpt-committed'
elif failure == 'corrupt':(folder/'new-first').write_bytes(b'bad')
elif failure == 'wrong-size':j['new_sectors']-=2048
else:
names = ('new-first','new-last') if failure == 'unrelated' else ('old-first','old-last')
pair = tuple((folder/n).read_bytes() for n in names)
rows = bytearray(table(pair[0]));rows[48] ^= 1
changed = with_table(pair,rows,self.storage['DISK_SIZE'])
if failure == 'unrelated':
for name,raw in zip(names,changed):
(folder/name).write_bytes(raw);j['files'][name]=sha(folder/name)
else:
source = self.ctx.directory/'backup'
for name,raw in zip(('gpt-first.bin','gpt-last.bin'),changed):(source/name).write_bytes(raw)
sums = json.loads((source/'checksums.json').read_text())
for name in ('gpt-first.bin','gpt-last.bin'):sums[name]=sha(source/name)
(source/'checksums.json').write_text(json.dumps(sums))
target = self.ctx.directory/('legacy-backups/reject-'+failure)
with self.assertRaises(RecoveryRequired):self.android.backup(target,self.storage)
self.assertFalse(target.exists())
self.adapter.adb.read.assert_not_called()
def test_actual_desktop_preflight_after_online_resize(self):
import importlib.util
from backend import gpt
from backend.online_shrink import OnlineShrink
original,updated = self.online_backup_fixture(slot='b')
entry = Path(__file__).resolve().parents[2]/'desktop/installer.py'
spec = importlib.util.spec_from_file_location('handoff_desktop',entry)
desktop = importlib.util.module_from_spec(spec);spec.loader.exec_module(desktop)
space = gpt.gpt_space(*updated,self.storage['DISK_SIZE'])
space.update(first=updated[0],last=updated[1])
android = SimpleNamespace(model='F50',slot='b',linux='a',serial='selected',
storage=lambda:self.storage,gpt=lambda _:space,
backup=lambda path,storage:self.adapter.backup_legacy(android,path,storage),prepare_payload=Mock())
args = SimpleNamespace(boot_openwrt=False,tf=False,resume=False,reinstall_part=False,
data=False,size='4',format_userdata=False,backup_dir=str(self.ctx.directory/'legacy-backups/reproduce'))
with patch.object(desktop,'Android',return_value=android),patch.object(desktop,'module'),\
patch.object(desktop,'GUI',self.adapter),patch.object(desktop,'free_write',return_value='verified') as writer:
# Reproduce the reported error through the real comparison, rather
# than a fake installer which never reads its backup GPT.
with patch.object(OnlineShrink,'installation_gpt',return_value=original):
with self.assertRaisesRegex(ValueError,'GPT changed during preflight'):
desktop.install(args,self.root,{'kernel':'7.2'})
android.prepare_payload.assert_not_called();writer.assert_not_called()
args.backup_dir=str(self.ctx.directory/'legacy-backups/fixed')
self.assertEqual(desktop.install(args,self.root,{'kernel':'7.2'}),'verified')
android.prepare_payload.assert_called_once();writer.assert_called_once()
self.assertEqual(tuple((self.ctx.directory/'backup'/n).read_bytes()
for n in ('gpt-first.bin','gpt-last.bin')),original)
# A real on-disk GPT change must still stop before payload/write.
android.prepare_payload.reset_mock();writer.reset_mock()
space['first']=original[0];space['last']=original[1]
args.backup_dir=str(self.ctx.directory/'legacy-backups/changed')
with self.assertRaisesRegex(ValueError,'GPT changed during preflight'):
desktop.install(args,self.root,{'kernel':'7.2'})
android.prepare_payload.assert_not_called();writer.assert_not_called()
def test_wrong_device_layout_or_corrupted_cache_stops(self):
target=self.ctx.directory/'legacy-backups/fixture'
with self.assertRaises(ValueError):self.android.backup(target,{**self.storage,'START':4096})
+85
View File
@@ -0,0 +1,85 @@
"""Explicit ADB reboot after installation; no device writes or real transports."""
import io
from pathlib import Path
import sys
import tempfile
import unittest
from unittest.mock import Mock
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
from backend.service import Service
from backend.state import Context,Store
class DeviceReboot(unittest.TestCase):
def setUp(self):
temporary=tempfile.TemporaryDirectory();self.addCleanup(temporary.cleanup)
store=Store(temporary.name);self.service=Service('.',store,io.StringIO())
self.device=dict(serial='chosen',cid='a'*32,profile='f50',slot='_b',system='Android',readiness='ready')
self.record=store.create({'adapter':'mu300'},dict(self.device),{'method':'part'}, {})
self.ctx=Context(store,self.record,self.service.emit)
self.service.active=self.ctx;self.service.worker=Mock()
self.service.worker.is_alive.return_value=True
self.service.openwrt_wait_stage(self.ctx)
self.adapter=Mock();self.adapter.probe.return_value=dict(self.device)
def request(self, transaction=None):
return self.service.dispatch({'protocol':1,'command':'reboot_device',
'params':{'transaction':transaction or self.record['id']}})
def test_queue_uses_device_owner_and_repeated_clicks_send_only_one_reboot(self):
self.assertTrue(self.request()['accepted']);self.request()
self.adapter.adb.call.assert_not_called()
self.service.process_device_reboot(self.ctx,self.adapter)
self.service.process_device_reboot(self.ctx,self.adapter)
self.adapter.probe.assert_called_once_with('chosen','boot')
self.adapter.adb.call.assert_called_once_with('reboot',timeout=15)
self.assertFalse(self.record['details']['reboot_manually'])
self.assertTrue(self.record['adb_reboot_requested'])
with self.assertRaises(ValueError):self.request()
def test_different_device_or_unavailable_adb_does_not_reboot(self):
for change in ({'serial':'other'},{'cid':'b'*32},{'profile':'v50'},{'slot':'_a'},
{'readiness':'android_boot'},{'system':'OpenWrt'}):
with self.subTest(change=change):
self.adapter.probe.return_value={**self.device,**change}
self.request();self.service.process_device_reboot(self.ctx,self.adapter)
self.adapter.adb.call.assert_not_called()
self.assertTrue(self.record['details']['reboot_manually'])
self.assertIn('原 Android',self.record['details']['verification_error'])
def test_writes_completion_confirmation_and_other_transactions_are_rejected(self):
original=dict(self.record)
for change in ({'unsafe':True},{'stage':'transfer_install'},{'status':'running'},
{'openwrt_confirmed':True},{'cancel_requested':True},
{'choices':{'method':'update'}},{'choices':{'method':'uninstall'}}):
with self.subTest(change=change):
self.record.clear();self.record.update(original);self.record.update(change)
with self.assertRaises(ValueError):self.request()
self.record.clear();self.record.update(original)
with self.assertRaises(ValueError):self.request('another-transaction')
self.adapter.probe.assert_not_called();self.adapter.adb.call.assert_not_called()
def test_boundary_is_rechecked_before_processing(self):
self.request();self.record['unsafe']=True
self.service.process_device_reboot(self.ctx,self.adapter)
self.adapter.probe.assert_not_called();self.adapter.adb.call.assert_not_called()
def test_disconnect_is_expected_and_not_automatically_retried(self):
self.adapter.adb.call.side_effect=ConnectionError('ADB: device offline')
self.request();self.service.process_device_reboot(self.ctx,self.adapter)
self.assertTrue(self.record['adb_reboot_requested'])
self.assertFalse(self.record['details'].get('verification_error'))
self.assertFalse(self.record['details']['reboot_manually'])
self.service.process_device_reboot(self.ctx,self.adapter)
self.adapter.adb.call.assert_called_once()
def test_rejected_command_restores_the_control(self):
self.adapter.adb.call.side_effect=ConnectionError('ADB: permission denied')
self.request();self.service.process_device_reboot(self.ctx,self.adapter)
self.assertFalse(self.record['adb_reboot_requested'])
self.assertTrue(self.record['details']['reboot_manually'])
self.assertIn('permission denied',self.record['details']['verification_error'])
self.assertTrue(self.request()['accepted'])
if __name__=='__main__':unittest.main()
+1
View File
@@ -41,6 +41,7 @@ BRIDGE=r"""
case 'start':if(window.__fixture.startRace){const older={...tx,stage:'android_setup',status:'waiting_user',revision:1};window.__emitFixture({stage:'complete',status:'completed',revision:2,result:{filesystem_bytes:10737418240,url:'http://192.168.9.1'}});return older;}tx.stage='android_setup';tx.status='waiting_user';return {...tx};
case 'cancel':return {accepted:window.__fixture.cancelAccepted ?? true,deferred:false};
case 'verify_openwrt':return {accepted:true};
case 'reboot_device':return {accepted:true};
case 'diagnostics':return {text:'DEBUG fixture diagnostics: commands, traceback and verified bytes (redacted)'};
default:return null;
}
+1 -1
View File
@@ -8,7 +8,7 @@ use std::{collections::HashMap, io::{BufRead, BufReader, Write}, path::PathBuf,
use tauri::{Emitter, Manager, State};
use tokio::sync::oneshot;
const COMMANDS: &[&str] = &["hello","snapshot","list","package","devices","adb_connect","adb_disconnect","probe","probe_update","plan","start","resume","retry","cancel","can_close","export","import","diagnostics","verify_openwrt","online_fallback","ota_analyze","ota_export","ota_export_index","ota_package","ota_probe","ota_apply","ota_status","ota_reboot"];
const COMMANDS: &[&str] = &["hello","snapshot","list","package","devices","adb_connect","adb_disconnect","probe","probe_update","plan","start","resume","retry","cancel","can_close","export","import","diagnostics","verify_openwrt","reboot_device","online_fallback","ota_analyze","ota_export","ota_export_index","ota_package","ota_probe","ota_apply","ota_status","ota_reboot"];
struct Bridge {
input: Mutex<Option<ChildStdin>>,
pending: Mutex<HashMap<u64, oneshot::Sender<Result<Value, String>>>>,
+4 -2
View File
@@ -56,7 +56,8 @@ export const strings = {
running:'正在执行', waiting_user:'等待用户操作', waiting_device:'等待设备重连', failed:'操作失败', completed:'已完成', cancelled:'已暂停', readyStatus:'等待确认',
stages:{online_shrink:'在线缩容并校验 GPT(请勿断电)',online_fallback:'等待选择缩容后备方案',uninstall_prepare:'准备离线卸载',uninstall_restore_boot:'恢复 Android 启动',uninstall_offline:'等待离线卸载及 Android 返回',verify_android:'验证 Android 恢复容量',firmware_extract:'提取本机固件',firmware_convert:'转换本机音频与蓝牙固件',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 请求。这里没有等待时限。',
rebootNow:'请现在手动重启设备', rebootManual:'设备端安装操作已结束。请使用设备的正常重启功能进入 OpenWrt;已开始重启或已进入 OpenWrt 时,无需重复重启。',
rebootNow:'准备进入 OpenWrt', rebootManual:'安装写入已完成。点击“重启设备”通过 ADB 进入 OpenWrt;ADB 不可用时也可手动重启。已开始重启或已进入 OpenWrt 时,无需重复重启。',
rebootDevice:'重启设备', rebootSending:'正在请求重启…', rebootQueued:'重启请求已提交,正在核对设备',
rebootAutomatic:'已发送自动重启请求,请等待设备开机。若设备仍停留在原系统且未开始重启,请使用设备的正常重启功能。',
waitingOpenwrt:'进入 OpenWrt 后,请将电脑连接到设备的 USB 网络或热点,安装器会自动通过 SSH 校验。同一设备的身份与实际容量校验通过后才会完成。请保持此窗口,或暂停后从记录继续。',
newestFirst:'最新记录在上',
@@ -125,7 +126,8 @@ export const strings = {
running:'Running',waiting_user:'Waiting for you',waiting_device:'Waiting for device',failed:'Failed',completed:'Completed',cancelled:'Paused',readyStatus:'Awaiting confirmation',
stages:{online_shrink:'Resizing online and verifying GPT — keep power connected',online_fallback:'Waiting for resize fallback choice',uninstall_prepare:'Preparing offline removal',uninstall_restore_boot:'Restoring Android boot',uninstall_offline:'Waiting for offline removal and Android',verify_android:'Verifying restored Android capacity',firmware_extract:'Extracting this device’s firmware',firmware_convert:'Converting device audio and Bluetooth firmware',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.',
rebootNow:'Restart the device now', rebootManual:'Device installation operations have finished. Use the device’s normal restart control to enter OpenWrt. If it is already restarting or running OpenWrt, do not restart it again.',
rebootNow:'Ready to start OpenWrt', rebootManual:'Installation writes are complete. Click “Restart device” to enter OpenWrt over ADB, or restart manually if ADB is unavailable. If it is already restarting or running OpenWrt, do not restart it again.',
rebootDevice:'Restart device', rebootSending:'Requesting restart…', rebootQueued:'Restart requested; checking the device',
rebootAutomatic:'An automatic restart was requested. Wait for the device to boot. If it stays in the previous system without restarting, use its normal restart control.',
waitingOpenwrt:'Once OpenWrt starts, connect this computer to the device’s USB network or hotspot. The installer will verify its identity and actual capacity over SSH before completing. Keep this window open, or pause and resume from the record.',
newestFirst:'Newest entries first',
+10 -1
View File
@@ -56,6 +56,7 @@ function App() {
useEffect(() => {setOnlineInput('');setOnlineDismissed(false);}, [tx?.online_fallback?.nonce]);
const [resetPrompt, setResetPrompt] = useState<ResetPrompt>();
const [busy, setBusy] = useState(false);
const [restartPending, setRestartPending] = useState(false);
const [logs, setLogs] = useState<string[]>([]);
const [logOpen, setLogOpen] = useState(false);
const [clock, setClock] = useState(Date.now());
@@ -79,6 +80,7 @@ function App() {
if (next.revision < (revisions.current.get(next.id) ?? -1)) return;
revisions.current.set(next.id, next.revision);
}
if (next.details?.reboot_manually === false || next.details?.verification_error || ['completed','failed','cancelled'].includes(next.status)) setRestartPending(false);
const key = `${next.id}:${next.stage}:${next.status}:${next.details?.tool || ''}:${next.details?.connection_state || ''}:${next.details?.verification_error || ''}:${next.error?.message || ''}`;
if (key !== lastTransaction.current) {
lastTransaction.current = key;
@@ -117,6 +119,13 @@ function App() {
} catch (e) {if (notice !== undefined) toast.dismiss(notice); reportError(String(e)); return undefined;}
finally {pending.current--; setBusy(pending.current > 0);}
};
const rebootDevice = async () => {
if (!tx || restartPending) return;
setRestartPending(true);
const accepted = await task(async () => (await request<{accepted:boolean}>('reboot_device', {transaction:tx.id})).accepted, t.rebootQueued);
if (!accepted) setRestartPending(false);
};
useEffect(() => {setRestartPending(false);}, [tx?.id]);
useEffect(() => {
const query = matchMedia('(prefers-color-scheme: dark)');
const update = () => document.documentElement.classList.toggle('dark', theme === 'dark' || theme === 'system' && query.matches);
@@ -383,7 +392,7 @@ function App() {
</section>}</>} </div>
{waitingForOpenwrt && <div className="verification-controls"><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>{tx.choices.method !== 'uninstall' && <p className="device-hint login-hint">{['update','boot'].includes(tx.choices.method) ? t.existingLogin : t.defaultLogin}</p>}{tx.details?.verification_error && <p className="verification-error" role="status">{tx.details.verification_error}</p>}</div>}
{waitingOnline && <Button variant="outline" onClick={() => {setOnlineDismissed(false);setOnlineInput('');}}>{t.onlineFallbackTitle}</Button>}
{tx.status !== 'completed' && !waitingOnline && <div className="actions">{waitingForOpenwrt && <Button disabled={busy || !host.trim()} onClick={() => task(async () => (await request<{accepted:boolean}>('verify_openwrt', {transaction:tx.id, host:host.trim(), password})).accepted, t.verificationRequested)}><CheckCircle2 size={16}/>{t.confirmOpenwrt}</Button>}{active ? <Button variant="outline" disabled={busy} onClick={() => task(async () => (await request<{accepted:boolean}>('cancel')).accepted, 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>
{tx.status !== 'completed' && !waitingOnline && <div className="actions">{manualRestart && <Button disabled={busy || restartPending} onClick={rebootDevice}>{restartPending ? <LoaderCircle size={16} className="spin"/> : <RefreshCw size={16}/>} {restartPending ? t.rebootSending : t.rebootDevice}</Button>}{waitingForOpenwrt && <Button variant={manualRestart ? "outline" : "default"} disabled={busy || restartPending || !host.trim()} onClick={() => task(async () => (await request<{accepted:boolean}>('verify_openwrt', {transaction:tx.id, host:host.trim(), password})).accepted, t.verificationRequested)}><CheckCircle2 size={16}/>{t.confirmOpenwrt}</Button>}{active ? <Button variant="outline" disabled={busy} onClick={() => task(async () => (await request<{accepted:boolean}>('cancel')).accepted, 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>
</>}
+7 -7
View File
@@ -350,7 +350,7 @@ def publish_completed(task, common, rows, source):
print('Verified release: '+str(destination))
def add_diff(task,rows,source,repair_installer=False):
def add_diff(task,rows,source,repair_installer=False,refresh_native=False):
if source is None:raise ValueError('Supply --source-release')
source=source.resolve()
if source.parent!=(TOP/'release').resolve() or source.name.startswith('.'):
@@ -367,16 +367,16 @@ def add_diff(task,rows,source,repair_installer=False):
if stage_path(task.workspace,profile).exists():raise ValueError('Prior staging retained: '+profile)
identify=runpy.run_path(str(TOP/'tools/release-identity.py'))['identify']
before=identify(TOP,'mu300','7.2.8');parent=TOP/'release';pending=parent/('.building-'+task.id);pending.mkdir()
task.save(pending_output=str(pending),build_type='installer-entry-repair' if repair_installer else 'diff-tools-only',base_release=str(source))
task.save(pending_output=str(pending),build_type='native-installer-refresh' if refresh_native else 'installer-entry-repair' if repair_installer else 'diff-tools-only',base_release=str(source))
repack=runpy.run_path(str(TOP/'tools/repack-with-diff.py'))['repack'];assets=[]
for profile,path in selected.items():
stage=stage_path(task.workspace,profile);stage.mkdir(parents=True)
write_json(stage/'.build-owner.json',{'owner':OWNER,'profile':profile})
studio=stage/'assembly'
task.run(profile+'-diff',[sys.executable,TOP/'tools/package-diff-studio.py','--prepare','--package',studio])
tag='-installer-fix-g' if repair_installer else '-tools-g'
tag='-installer-g' if refresh_native else '-installer-fix-g' if repair_installer else '-tools-g'
target=pending/(path.stem+tag+before['source_commit'][:8]+'.zip')
repack(path,target,studio,before,repair_installer=repair_installer);verify_archive(target,require_diff=True)
repack(path,target,studio,before,repair_installer=repair_installer,refresh_native=refresh_native);verify_archive(target,require_diff=True)
checksum=digest(target);(pending/(target.name+'.sha256')).write_text(checksum+' '+target.name+'\n')
assets.append({'profile':profile,'file':target.name,'bytes':target.stat().st_size,'sha256':checksum})
clean_stage(task.workspace,profile);task.save(assets=assets)
@@ -389,7 +389,7 @@ def add_diff(task,rows,source,repair_installer=False):
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('action', choices=('plan', 'check', 'package', 'publish-completed', 'add-diff', 'repair-installer', 'run', 'status', 'clean-staging'))
parser.add_argument('action', choices=('plan', 'check', 'package', 'publish-completed', 'add-diff', 'repair-installer', 'refresh-installers', 'run', 'status', 'clean-staging'))
parser.add_argument('--profiles', nargs='+', choices=('all', *PROFILES), default=['all'])
parser.add_argument('--workspace', type=Path, default=Path.home() / 'openwrt-build')
parser.add_argument('--config', type=Path, default=TOP / 'tools/build-layout.json')
@@ -422,8 +422,8 @@ def main():
task.run('command', command); task.save(state='complete')
elif args.action == 'publish-completed':
publish_completed(task,common,rows,args.source_release)
elif args.action in ('add-diff','repair-installer'):
add_diff(task,rows,args.source_release,repair_installer=args.action=='repair-installer')
elif args.action in ('add-diff','repair-installer','refresh-installers'):
add_diff(task,rows,args.source_release,repair_installer=args.action=='repair-installer',refresh_native=args.action=='refresh-installers')
else:
package(task, common, rows)
except BaseException as error:
+64
View File
@@ -0,0 +1,64 @@
"""Refresh native installer/Diff Studio files without touching firmware payloads."""
import hashlib
import json
from pathlib import Path, PurePosixPath
import shutil
def digest(value):
if isinstance(value,bytes):
return hashlib.sha256(value).hexdigest()
h=hashlib.sha256()
with Path(value).open('rb') as stream:
for block in iter(lambda:stream.read(1<<20),b''):h.update(block)
return h.hexdigest()
def write(destination,value):
if isinstance(value,bytes):destination.write(value)
else:
with Path(value).open('rb') as stream:shutil.copyfileobj(stream,destination,1<<20)
def native_name(name):
path=PurePosixPath(name)
return (not path.is_absolute() and '..' not in path.parts and '\\' not in name and
(name in ('OpenWrt-Installer.exe','OpenWrt-Diff-Studio.exe','OpenWrt-Diff-Studio.py') or
name.startswith(('tools/','backend/','OpenWrt-Installer.app/','OpenWrt-Diff-Studio.app/'))))
def replacements(original,studio):
studio=Path(studio).resolve()
documents=('docs/GUI-BUILD.json','docs/GUI-BUILD-macos.json','diff-tool.json')
previous=set();current=set();source=None
for name in documents:
old=json.loads(original.read(name));new=json.loads((studio/name).read_text())
if new.get('protocol')!=1 or not isinstance(new.get('files'),dict):
raise ValueError('Invalid native installer inventory: '+name)
if source is not None and new.get('source')!=source:
raise ValueError('Native installer and Diff Studio sources disagree')
source=new['source']
previous.update(old['files']);current.update(new['files'])
if not all(native_name(name) for name in previous|current):
raise ValueError('Native inventory contains a non-installer path')
required={'OpenWrt-Installer.exe','OpenWrt-Diff-Studio.exe',
'tools/backend/openwrt-backend.exe','tools/macos/backend/openwrt-backend',
'OpenWrt-Installer.app/Contents/MacOS/openwrt-installer',
'OpenWrt-Diff-Studio.app/Contents/MacOS/openwrt-installer'}
if not required.issubset(current):
raise ValueError('Native installer refresh requires both platforms and Diff Studio')
docs={'START-HERE.md','docs/GUI-GUIDE.md','docs/INSTALLER-PROTOCOL.md',
'docs/GUI-BUILD.md','docs/GUI-VERIFICATION.md','docs/DIFF-STUDIO.md',*documents}
patches={}
for name in sorted(current|docs):
path=(studio/name).resolve()
if not path.is_relative_to(studio) or not path.is_file():
raise ValueError('Native refresh input is missing or outside staging: '+name)
patches[name]=path
return patches,previous-current
def mode(name):
return 0o100755 if (name.startswith(('OpenWrt-Installer.app/Contents/MacOS/',
'OpenWrt-Diff-Studio.app/Contents/MacOS/')) or
name in ('tools/macos/adb','tools/macos/backend/openwrt-backend')) else 0o100644
+14 -8
View File
@@ -10,19 +10,24 @@ import zipfile
TOP=Path(__file__).resolve().parents[1]
def repack(source,target,studio,revision,repair_installer=False):
def repack(source,target,studio,revision,repair_installer=False,refresh_native=False):
if target.exists():raise ValueError('Target release already exists')
tool=json.loads((studio/'diff-tool.json').read_text())
patches={}
with zipfile.ZipFile(source) as old:
native=runpy.run_path(str(TOP/'tools/refresh-native-installers.py'))
removed=set()
if refresh_native:
patches,removed=native['replacements'](old,studio)
manifest=json.loads(old.read('desktop/manifest.json'))
checks={**manifest['magisk'],**manifest['desktop']}
for name,wanted in tool['files'].items():
if refresh_native:continue
if name in checks:
if checks[name]!=wanted:raise ValueError('Existing native runtime differs: '+name)
else:patches[name]=(studio/name).read_bytes()
for name in ('diff-tool.json','docs/DIFF-STUDIO.md'):patches[name]=(studio/name).read_bytes()
patches['START-HERE.md']=old.read('START-HERE.md')+(
if not refresh_native:patches['START-HERE.md']=old.read('START-HERE.md')+(
'\n## Diff Studio / 差异更新工具\n\n'
'Windows: **OpenWrt-Diff-Studio.exe**. Apple Silicon: **OpenWrt-Diff-Studio.app**.\n\n'
'完整解压后打开;与安装器共用 tools 目录,请勿单独移动程序。'
@@ -38,22 +43,23 @@ def repack(source,target,studio,revision,repair_installer=False):
patches[name]=entry
manifest['source']['installer.py']=hashlib.sha256(entry).hexdigest()
payload={n:checks[n] for n in manifest['magisk_layout'].values()}
patches['desktop/TOOLS-REVISION.json']=(json.dumps({'format':1,'kind':'installer-entry-repair' if repair_installer else 'tools-only',
patches['desktop/TOOLS-REVISION.json']=(json.dumps({'format':1,'kind':'native-installer-refresh' if refresh_native else 'installer-entry-repair' if repair_installer else 'tools-only',
'source_commit':revision['source_commit'],'source_fingerprint':revision['source_fingerprint'],
'firmware_unchanged':payload,'base_archive':source.name},indent=2)+'\n').encode()
manifest['desktop'].update({n:hashlib.sha256(v).hexdigest() for n,v in patches.items()})
for name in removed:manifest['desktop'].pop(name,None)
manifest['desktop'].update({n:native['digest'](v) for n,v in patches.items()})
patches['desktop/manifest.json']=(json.dumps(manifest,indent=2)+'\n').encode()
with zipfile.ZipFile(target,'x') as output:
for member in old.infolist():
if member.filename in removed:continue
with output.open(copy.copy(member),'w',force_zip64=True) as dst:
if member.filename in patches:dst.write(patches[member.filename])
if member.filename in patches:native['write'](dst,patches[member.filename])
else:
with old.open(member) as src:
for block in iter(lambda:src.read(1<<20),b''):dst.write(block)
for name,data in patches.items():
if name in old.namelist():continue
info=zipfile.ZipInfo(name);info.create_system=3
mode=0o755 if name.startswith('OpenWrt-Diff-Studio.app/Contents/MacOS/') else 0o644
info.external_attr=(0o100000|mode)<<16;info.compress_type=zipfile.ZIP_DEFLATED
output.writestr(info,data)
info.external_attr=native['mode'](name)<<16;info.compress_type=zipfile.ZIP_DEFLATED
with output.open(info,'w',force_zip64=True) as dst:native['write'](dst,data)
return payload
+105
View File
@@ -0,0 +1,105 @@
"""Native refresh replaces both hosts, drops only obsolete owned files, preserves firmware."""
import hashlib
import io
import json
from pathlib import Path
import runpy
import tarfile
import tempfile
import unittest
import zipfile
TOP=Path(__file__).resolve().parents[2]
native=runpy.run_path(str(TOP/'tools/refresh-native-installers.py'))
def sha(raw):return hashlib.sha256(raw).hexdigest()
def tar(files):
out=io.BytesIO()
with tarfile.open(fileobj=out,mode='w') as z:
for n,v in files.items():
info=tarfile.TarInfo(n);info.size=len(v);z.addfile(info,io.BytesIO(v))
return out.getvalue()
def studio(root):
groups={
'windows-x64':{'OpenWrt-Installer.exe':b'new Windows GUI',
'tools/backend/openwrt-backend.exe':b'new Windows backend','tools/backend/new.dll':b'new dependency'},
'macos-arm64':{'OpenWrt-Installer.app/Contents/MacOS/openwrt-installer':b'new Mac GUI',
'tools/macos/backend/openwrt-backend':b'new Mac backend'},
}
diff={'OpenWrt-Diff-Studio.exe':groups['windows-x64']['OpenWrt-Installer.exe'],
'OpenWrt-Diff-Studio.app/Contents/MacOS/openwrt-installer':groups['macos-arm64']['OpenWrt-Installer.app/Contents/MacOS/openwrt-installer'],
'OpenWrt-Diff-Studio.py':b'new diff entry','backend/ota_engine.py':b'new support',
'tools/backend/openwrt-backend.exe':groups['windows-x64']['tools/backend/openwrt-backend.exe'],
'tools/macos/backend/openwrt-backend':groups['macos-arm64']['tools/macos/backend/openwrt-backend']}
files={**groups['windows-x64'],**groups['macos-arm64'],**diff}
for label,platform in [('docs/GUI-BUILD.json','windows-x64'),('docs/GUI-BUILD-macos.json','macos-arm64')]:
files[label]=json.dumps({'protocol':1,'platform':platform,'source':{'revision':'new'},
'files':{n:sha(v) for n,v in groups[platform].items()}}).encode()
files['diff-tool.json']=json.dumps({'protocol':1,'source':{'revision':'new'},'files':{n:sha(v) for n,v in diff.items()}}).encode()
for n in ('START-HERE.md','docs/GUI-GUIDE.md','docs/INSTALLER-PROTOCOL.md','docs/GUI-BUILD.md','docs/GUI-VERIFICATION.md','docs/DIFF-STUDIO.md'):files[n]=b'new guide'
for n,v in files.items():
p=root/n;p.parent.mkdir(parents=True,exist_ok=True);p.write_bytes(v)
return files
class RefreshNative(unittest.TestCase):
def test_actual_archive_refresh_and_checksums_without_firmware_or_duplicate_runtime(self):
with tempfile.TemporaryDirectory() as temporary:
root=Path(temporary);fresh=studio(root/'studio');old=root/'old.zip';new=root/'new.zip'
files={n:v.replace(b'new ',b'old ') for n,v in fresh.items()}
obsolete='tools/backend/obsolete.dll';files[obsolete]=b'old dependency'
metadata=json.loads(files['docs/GUI-BUILD.json'])
metadata['files'][obsolete]=sha(files[obsolete])
files['docs/GUI-BUILD.json']=json.dumps(metadata).encode()
files['tools/keep-unowned.txt']=b'not owned by a GUI inventory'
mu=(TOP/'desktop/installer.py').is_file()
if mu:
payload={'payload/boot-linux.img':b'unchanged boot','payload/mu300-openwrt.tar.gz':b'unchanged root'}
files.update(payload)
files['desktop/manifest.json']=json.dumps({'format':2,'kernel':'7.2',
'magisk_layout':{'boot-linux.img':'payload/boot-linux.img','mu300-openwrt.tar.gz':'payload/mu300-openwrt.tar.gz'},
'magisk':{n:sha(v) for n,v in payload.items()},
'desktop':{n:sha(v) for n,v in files.items() if n not in payload}}).encode()
else:
payload={'files/boot.img':b'unchanged boot','files/openwrt.ext4.gz':b'unchanged root','files/ext4-tools.tar':tar({'lib/base.so':b'ABI'})}
files.update(payload)
files['files/SHA256SUMS']=''.join(sha(v)+' '+n+'\n' for n,v in files.items()).encode()
with zipfile.ZipFile(old,'w') as z:
for n,v in files.items():z.writestr(n,v)
revision={'source_commit':'a'*40,'source_fingerprint':'b'*64}
if mu:
runpy.run_path(str(TOP/'tools/repack-with-diff.py'))['repack'](old,new,root/'studio',revision,refresh_native=True)
else:
tools=root/'tools.tar';tools.write_bytes(tar({'lib/base.so':b'ABI','usr/bin/flock':b'lock'}))
runpy.run_path(str(TOP/'tools/refresh-release-installers.py'))['refresh'](old,new,tools,revision,native=root/'studio')
with zipfile.ZipFile(new) as z:
self.assertIsNone(z.testzip());self.assertEqual(len(z.namelist()),len(set(z.namelist())))
self.assertNotIn(obsolete,z.namelist());self.assertEqual(z.read('tools/keep-unowned.txt'),files['tools/keep-unowned.txt'])
for n,v in payload.items():self.assertEqual(z.read(n),v)
for n in ('OpenWrt-Installer.exe','tools/backend/openwrt-backend.exe','tools/macos/backend/openwrt-backend','OpenWrt-Diff-Studio.exe'):
self.assertEqual(z.read(n),fresh[n])
if mu:sums=json.loads(z.read('desktop/manifest.json'))['desktop']
else:sums={n:h for line in z.read('files/SHA256SUMS').decode().splitlines() for h,n in [line.split(None,1)]}
self.assertNotIn(obsolete,sums)
for n,h in sums.items():self.assertEqual(sha(z.read(n)),h,n)
for name in ('docs/GUI-BUILD.json','docs/GUI-BUILD-macos.json','diff-tool.json'):
for n,h in json.loads(z.read(name))['files'].items():self.assertEqual(sha(z.read(n)),h)
self.assertTrue(z.getinfo('tools/backend/new.dll').external_attr>>16&0o444)
def test_inventory_cannot_replace_firmware(self):
with tempfile.TemporaryDirectory() as temporary:
root=Path(temporary);files=studio(root/'studio');old=root/'old.zip'
info=json.loads(files['docs/GUI-BUILD.json']);info['files']['files/boot.img']='0'*64
files['docs/GUI-BUILD.json']=json.dumps(info).encode()
with zipfile.ZipFile(old,'w') as z:
for n,v in files.items():z.writestr(n,v)
with zipfile.ZipFile(old) as z,self.assertRaisesRegex(ValueError,'non-installer'):
native['replacements'](z,root/'studio')
if __name__=='__main__':unittest.main()