#!/usr/bin/env python3 """Offline test suite for Geminux flash-mtk GPT builder, safety guards, and firmware extractor.""" import os import re import shutil import struct import subprocess import sys import tempfile import uuid BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SCRIPTS_DIR = os.path.join(BASE_DIR, "scripts") FLASH_DEPS = os.path.join(BASE_DIR, ".flash-deps") if os.path.isdir(FLASH_DEPS): sys.path.insert(0, FLASH_DEPS) sys.path.insert(0, BASE_DIR) sys.path.insert(0, SCRIPTS_DIR) from geminux_accounts import ( customize_ext4_accounts, rewrite_account_tables, sha512_crypt, validate_username, ) from geminux_gpt import ( BASIC_DATA_TYPE_GUID, GPT_ARRAY_SECTORS, GPT_ENTRY_COUNT, GPT_ENTRY_SIZE, LINUX_FS_TYPE_GUID, PROTECTED_END_LBA, SECTOR_SIZE, GptEntry, GptHeader, build_geminux_gpts, parse_primary_gpt, verify_gpt_crcs, ) import importlib.util def _load_mod(name, path): sp = importlib.util.spec_from_file_location(name, path) mod = importlib.util.module_from_spec(sp) sp.loader.exec_module(mod) return mod extract_firmware = _load_mod( "extract_vendor_fw", os.path.join(SCRIPTS_DIR, "extract-vendor-fw.py") ).extract_firmware flash_mtk = _load_mod("flash_mtk", os.path.join(BASE_DIR, "flash-mtk.py")) def make_synthetic_gemini_pgpt(total_sectors): # Replicate Planet Computers Gemini x27 SYS1..SYS34 partitions parts_spec = [ ("recovery", 0x8000, 0x1000000), ("para", 0x1008000, 0x80000), ("expdb", 0x1088000, 0xa00000), ("frp", 0x1a88000, 0x100000), ("nvcfg", 0x1b88000, 0x800000), ("nvdata", 0x2388000, 0x2000000), ("metadata", 0x4388000, 0x2000000), ("protect1", 0x6388000, 0x800000), ("protect2", 0x6b88000, 0xc78000), ("seccfg", 0x7800000, 0x800000), ("oemkeystore", 0x8000000, 0x200000), ("proinfo", 0x8200000, 0x300000), ("md1img", 0x8500000, 0x1800000), ("md1dsp", 0x9d00000, 0x400000), ("md1arm7", 0xa100000, 0x300000), ("md3img", 0xa400000, 0x500000), ("scp1", 0xa900000, 0x100000), ("scp2", 0xaa00000, 0x100000), ("nvram", 0xab00000, 0x500000), ("lk", 0xb000000, 0x80000), ("lk2", 0xb080000, 0x80000), ("boot", 0xb100000, 0x1000000), ("logo", 0xc100000, 0x800000), ("tee1", 0xc900000, 0x500000), ("tee2", 0xce00000, 0x500000), ("keystore", 0xd300000, 0xd00000), ("system", 0xe000000, 0xa0000000), ("cache", 0xae000000, 0x1b000000), ("userdata", 0xc9000000, (total_sectors - 32768 - 64) * SECTOR_SIZE - 0xc9000000), ] entries = [] for name, start_b, size_b in parts_spec: first_lba = start_b // SECTOR_SIZE last_lba = (start_b + size_b) // SECTOR_SIZE - 1 entries.append(GptEntry( BASIC_DATA_TYPE_GUID, uuid.uuid4().bytes_le, first_lba, last_lba, 0, name, )) flashinfo_sectors = 0x1000000 // SECTOR_SIZE flashinfo_first = total_sectors - 34 - flashinfo_sectors entries.append(GptEntry( BASIC_DATA_TYPE_GUID, uuid.uuid4().bytes_le, flashinfo_first, flashinfo_first + flashinfo_sectors - 1, 0, "flashinfo", )) part_array = bytearray(GPT_ENTRY_COUNT * GPT_ENTRY_SIZE) for i, e in enumerate(entries): part_array[i * GPT_ENTRY_SIZE:(i + 1) * GPT_ENTRY_SIZE] = e.to_bytes() raw_hdr = struct.pack( "<8sIIIIQQQQ16sQIII", b"EFI PART", 0x00010000, 92, 0, 0, 1, total_sectors - 1, 34, total_sectors - 34, uuid.uuid4().bytes_le, 2, GPT_ENTRY_COUNT, GPT_ENTRY_SIZE, 0, ).ljust(SECTOR_SIZE, b"\x00") hdr = GptHeader(raw_hdr) hdr_bytes = hdr.pack_with_crcs(bytes(part_array)) mbr = bytearray(SECTOR_SIZE) mbr[510:512] = b"\x55\xAA" return bytes(mbr) + hdr_bytes + bytes(part_array) def test_gpt_repartition(): # ~64 GB eMMC sector count total_sectors = 122142720 orig_pgpt = make_synthetic_gemini_pgpt(total_sectors) _, orig_hdr, orig_entries = parse_primary_gpt(orig_pgpt) new_pgpt, new_sgpt, new_entries = build_geminux_gpts(orig_pgpt, total_sectors) assert len(new_pgpt) == 34 * SECTOR_SIZE assert len(new_sgpt) == 33 * SECTOR_SIZE _, pri_hdr, parsed_entries = parse_primary_gpt(new_pgpt) verify_gpt_crcs(pri_hdr, new_pgpt[2 * SECTOR_SIZE:]) # Verify backup GPT CRCs as well bak_entries_bytes = new_sgpt[:GPT_ARRAY_SECTORS * SECTOR_SIZE] bak_hdr = GptHeader(new_sgpt[GPT_ARRAY_SECTORS * SECTOR_SIZE:]) verify_gpt_crcs(bak_hdr, bak_entries_bytes) assert bak_hdr.current_lba == total_sectors - 1 assert bak_hdr.backup_lba == 1 assert bak_hdr.part_entry_start_lba == total_sectors - 1 - GPT_ARRAY_SECTORS # Check every pre-0x0E000000 partition is preserved byte-for-byte orig_pre = [e for e in orig_entries if e.last_lba < PROTECTED_END_LBA] new_pre = [e for e in parsed_entries if e.last_lba < PROTECTED_END_LBA] assert len(orig_pre) == len(new_pre) == 26 for a, b in zip(orig_pre, new_pre): assert a.to_bytes() == b.to_bytes(), f"Mismatch in preserved partition {a.name}" names = [e.name for e in parsed_entries] assert "system" not in names assert "cache" not in names assert "userdata" not in names assert "linux" in names assert "boot2" in names assert "flashinfo" in names linux_p = next(e for e in parsed_entries if e.name == "linux") boot2_p = next(e for e in parsed_entries if e.name == "boot2") flash_p = next(e for e in parsed_entries if e.name == "flashinfo") assert linux_p.type_guid == LINUX_FS_TYPE_GUID assert linux_p.first_lba == PROTECTED_END_LBA assert linux_p.last_lba == boot2_p.first_lba - 1 linux_gib = (linux_p.sectors * SECTOR_SIZE) / (1024 ** 3) assert linux_gib > 57.5, f"Expected >57.5 GiB linux partition, got {linux_gib:.2f}" assert boot2_p.sectors * SECTOR_SIZE == 0x1000000 assert boot2_p.last_lba < flash_p.first_lba print(f"[PASS] GPT repartitioning verified (linux={linux_gib:.2f} GiB, 26 protected partitions intact)") def test_write_safety(): for protected in ("preloader", "nvram", "proinfo", "protect1", "protect2", "lk", "tee1", "md1img"): blocked = False try: flash_mtk.enforce_write_safety(protected, allow_protected=False) except PermissionError: blocked = True assert blocked, f"Protected partition {protected} was NOT blocked!" flash_mtk.enforce_write_safety(protected, allow_protected=True) for allowed in ("boot", "recovery", "boot2", "linux"): flash_mtk.enforce_write_safety(allowed, allow_protected=False) print("[PASS] Protected partition write-denylist verified") def test_firmware_extraction(): if shutil.which("mke2fs") is None or shutil.which("debugfs") is None: print("[SKIP] mke2fs/debugfs not available on host for ext4 extraction test") return with tempfile.TemporaryDirectory(prefix="geminux-fwtest-") as tmp: src_tree = os.path.join(tmp, "sysroot", "vendor", "firmware") os.makedirs(src_tree, exist_ok=True) expected = { "ROMv3_patch_1_0_hdr.bin": b"ROMV3_0" * 64, "ROMv3_patch_1_1_hdr.bin": b"ROMV3_1" * 64, "WIFI_RAM_CODE_6797": b"WIFI_FW" * 128, "WMT_SOC.cfg": b"coex=1\n", "pcm_suspend.bin": b"PCM_SUSPEND" * 16, } for name, data in expected.items(): with open(os.path.join(src_tree, name), "wb") as f: f.write(data) sys_img = os.path.join(tmp, "system.img") subprocess.run( ["mke2fs", "-t", "ext4", "-F", "-q", "-d", os.path.join(tmp, "sysroot"), sys_img, "4M"], check=True, ) out_dir = os.path.join(tmp, "fw-out") found, missing = extract_firmware(sys_img, out_dir) assert not missing, f"Missing firmware blobs: {missing}" assert set(found.keys()) == set(expected.keys()) for name, data in expected.items(): with open(os.path.join(out_dir, name), "rb") as f: assert f.read() == data assert os.path.isfile(os.path.join(out_dir, "MANIFEST.sha256")) print("[PASS] Stock system.img firmware extraction verified") def test_mtkclient_gpt_settings(): from types import SimpleNamespace vendor_mtk = os.path.join(BASE_DIR, "vendor", "mtkclient") if vendor_mtk not in sys.path: sys.path.insert(0, vendor_mtk) from mtkclient.Library.partition import Partition cfg = flash_mtk.create_mtk_config() assert cfg.gpt_settings is not None, "create_mtk_config() left cfg.gpt_settings as None" assert cfg.gpt_settings.gpt_num_part_entries == 0 total_sectors = 122142720 pgpt = make_synthetic_gemini_pgpt(total_sectors) # Ensure protective MBR has EFI partition entry matching hardware GPT pgpt_arr = bytearray(pgpt) pgpt_arr[0x1BE:0x1CE] = struct.pack("> 127) else 0)) & ((1 << 128) - 1) df.write(out) def test_luks2_encryption_offline(): import pty if not all(shutil.which(cmd) for cmd in ("mke2fs", "debugfs", "e2fsck", "cryptsetup")): print("[SKIP] mke2fs/debugfs/e2fsck/cryptsetup not available for LUKS2 offline test") return with tempfile.TemporaryDirectory(prefix="geminux-luks-test-") as tmp: sysroot = os.path.join(tmp, "sysroot") os.makedirs(os.path.join(sysroot, "etc"), exist_ok=True) os.makedirs(os.path.join(sysroot, "home", "user"), exist_ok=True) with open(os.path.join(sysroot, "etc", "passwd"), "w", encoding="utf-8") as f: f.write("root:x:0:0:root:/root:/bin/bash\nuser:x:10000:10000::/home/user:/bin/bash\n") with open(os.path.join(sysroot, "etc", "group"), "w", encoding="utf-8") as f: f.write("root:x:0:root\nwheel:x:10:root,user\nuser:x:10000:\n") with open(os.path.join(sysroot, "etc", "shadow"), "w", encoding="utf-8") as f: f.write("root:$6$oldsalt$old:::::::\nuser:$6$oldsalt$old:::::::\n") with open(os.path.join(sysroot, "home", "user", ".gitconfig"), "w", encoding="utf-8") as f: f.write("[pull]\n\trebase = false\n") img_dir = os.path.join(tmp, "images") os.makedirs(img_dir, exist_ok=True) orig_img = os.path.join(img_dir, "geminux-rootfs.img") enc_out = os.path.join(tmp, "enc-rootfs.img") subprocess.run( ["mke2fs", "-t", "ext4", "-F", "-q", "-d", sysroot, orig_img, "8M"], check=True, ) orig_sha = flash_mtk.sha256_file(orig_img) orig_bytes = os.path.getsize(orig_img) res = subprocess.run( [ os.path.join(BASE_DIR, "flash-mtk.sh"), "--customize-rootfs", enc_out, "--images-dir", img_dir, "--username", "luksuser", "--user-password", "uPw!77", "--root-password", "rPw!77", "--luks-password", "DiskPass#2026", ], capture_output=True, text=True, check=False, ) assert res.returncode == 0, f"encrypted customize-rootfs failed: {res.stdout}\n{res.stderr}" assert flash_mtk.sha256_file(orig_img) == orig_sha, "Source rootfs image was mutated!" assert subprocess.run(["cryptsetup", "isLuks", "--disable-locks", enc_out]).returncode == 0 assert subprocess.run( ["cryptsetup", "open", "--test-passphrase", "--disable-locks", "--key-file", "-", enc_out], input=b"DiskPass#2026", ).returncode == 0 assert subprocess.run( ["cryptsetup", "open", "--test-passphrase", "--disable-locks", "--key-file", "-", enc_out], input=b"WrongPass", ).returncode != 0 # Verify interactive PTY unlock (simulating PID 1 initramfs prompt on /dev/tty1) mfd, sfd = pty.openpty() pty_proc = subprocess.Popen( ["cryptsetup", "open", "--test-passphrase", "--disable-locks", enc_out], stdin=sfd, stdout=sfd, stderr=sfd, close_fds=True, start_new_session=True, ) os.close(sfd) prompt_buf = b"" while b":" not in prompt_buf: prompt_buf += os.read(mfd, 256) os.write(mfd, b"DiskPass#2026\n") pty_rc = pty_proc.wait(timeout=10) os.close(mfd) assert pty_rc == 0, f"Interactive PTY passphrase check failed rc={pty_rc}" vk_file = os.path.join(tmp, "vk.bin") dump = subprocess.check_output( [ "cryptsetup", "luksDump", "--disable-locks", "--dump-volume-key", "--volume-key-file", vk_file, "--batch-mode", "--key-file", "-", enc_out, ], input="DiskPass#2026".encode("utf-8"), text=False, ).decode("utf-8") m_off = re.search(r"Payload offset:\s*(\d+)", dump) assert m_off, dump payload_offset = int(m_off.group(1)) * 512 assert os.path.getsize(enc_out) >= payload_offset + orig_bytes with open(vk_file, "rb") as vf: vk64 = vf.read() dec_img = os.path.join(tmp, "dec-rootfs.img") _xts_decrypt_ext4(enc_out, vk64, payload_offset, orig_bytes, dec_img) e2 = subprocess.run(["e2fsck", "-fn", dec_img], capture_output=True, text=True) assert e2.returncode == 0, f"Decrypted ext4 failed e2fsck: {e2.stdout}\n{e2.stderr}" pw_txt = subprocess.check_output(["debugfs", "-R", "cat /etc/passwd", dec_img], text=True) assert "luksuser:x:10000:10000::/home/luksuser:/bin/bash" in pw_txt, pw_txt st = subprocess.run( ["debugfs", "-R", "stat /home/luksuser/.gitconfig", dec_img], capture_output=True, text=True, check=True, ) assert "Type: regular" in st.stdout, st.stdout print("[PASS] Offline LUKS2 encryption, PTY passphrase unlock, and XTS-256 ext4 decryption verified") def test_firmware_injection_ext4(): if not all(shutil.which(cmd) for cmd in ("mke2fs", "debugfs", "e2fsck")): print("[SKIP] mke2fs/debugfs/e2fsck not available for firmware injection test") return fw_mod = flash_mtk.load_firmware_module() with tempfile.TemporaryDirectory(prefix="geminux-fwinj-test-") as tmp: sysroot = os.path.join(tmp, "sysroot") os.makedirs(os.path.join(sysroot, "etc"), exist_ok=True) os.makedirs(os.path.join(sysroot, "home", "user"), exist_ok=True) with open(os.path.join(sysroot, "etc", "passwd"), "w", encoding="utf-8") as f: f.write("root:x:0:0:root:/root:/bin/bash\nuser:x:10000:10000::/home/user:/bin/bash\n") with open(os.path.join(sysroot, "etc", "group"), "w", encoding="utf-8") as f: f.write("root:x:0:root\nuser:x:10000:\n") with open(os.path.join(sysroot, "etc", "shadow"), "w", encoding="utf-8") as f: f.write("root:*:::::::\nuser:*:::::::\n") fw_dir = os.path.join(tmp, "fw") os.makedirs(fw_dir, exist_ok=True) expected_blobs = { "WIFI_RAM_CODE_6797": b"WIFI_FW_HDR" * 100, "WMT_SOC.cfg": b"cfg=1\n", "ROMv3_patch_1_0_hdr.bin": b"ROM10", "pcm_suspend.bin": b"PCM_SUSPEND", } for name, data in expected_blobs.items(): with open(os.path.join(fw_dir, name), "wb") as bf: bf.write(data) with open(os.path.join(fw_dir, "ignored.txt"), "w", encoding="utf-8") as uf: uf.write("ignore-me\n") img_dir = os.path.join(tmp, "images") os.makedirs(img_dir, exist_ok=True) orig_img = os.path.join(img_dir, "geminux-rootfs.img") out_img = os.path.join(tmp, "out-rootfs.img") subprocess.run( ["mke2fs", "-t", "ext4", "-F", "-q", "-d", sysroot, orig_img, "8M"], check=True, ) orig_sha = flash_mtk.sha256_file(orig_img) res = subprocess.run( [ os.path.join(BASE_DIR, "flash-mtk.sh"), "--customize-rootfs", out_img, "--images-dir", img_dir, "--firmware-dir", fw_dir, "--use-default-credentials", ], capture_output=True, text=True, check=False, ) assert res.returncode == 0, f"customize-rootfs fw inject failed: {res.stdout}\n{res.stderr}" assert flash_mtk.sha256_file(orig_img) == orig_sha, "Source rootfs image was mutated!" e2 = subprocess.run(["e2fsck", "-fn", out_img], capture_output=True, text=True) assert e2.returncode == 0, f"e2fsck failed after fw inject: {e2.stdout}\n{e2.stderr}" ls_entries = fw_mod.debugfs_ls(out_img, "lib/firmware/mediatek/mt6797") assert set(ls_entries) == set(expected_blobs.keys()), ls_entries for name, expected in expected_blobs.items(): dump_p = os.path.join(tmp, f"dump-{name}") assert fw_mod.debugfs_dump(out_img, f"lib/firmware/mediatek/mt6797/{name}", dump_p) with open(dump_p, "rb") as df: assert df.read() == expected st = subprocess.run( ["debugfs", "-R", f"stat /lib/firmware/mediatek/mt6797/{name}", out_img], capture_output=True, text=True, check=True, ) assert re.search(r"Mode:\s*0644\b", st.stdout), st.stdout # Verify --skip-firmware-inject skips injection out_skip = os.path.join(tmp, "out-skip.img") res_skip = subprocess.run( [ os.path.join(BASE_DIR, "flash-mtk.sh"), "--customize-rootfs", out_skip, "--images-dir", img_dir, "--firmware-dir", fw_dir, "--skip-firmware-inject", "--use-default-credentials", ], capture_output=True, text=True, check=False, ) assert res_skip.returncode == 0, res_skip.stderr assert fw_mod.debugfs_ls(out_skip, "lib/firmware/mediatek/mt6797") == [] print("[PASS] Offline MT6797 firmware ext4 injection verified") def test_release_zip_packager(): import zipfile if not all(shutil.which(cmd) for cmd in ("mke2fs", "debugfs", "e2fsck")): print("[SKIP] mke2fs/debugfs/e2fsck not available for release ZIP packager test") return pkg_mod = _load_mod( "package_release_zip", os.path.join(SCRIPTS_DIR, "package-release-zip.py") ) with tempfile.TemporaryDirectory(prefix="geminux-zip-test-") as tmp: sysroot = os.path.join(tmp, "sysroot") os.makedirs(os.path.join(sysroot, "etc", "ssh"), exist_ok=True) os.makedirs(os.path.join(sysroot, "root", ".ssh"), exist_ok=True) os.makedirs(os.path.join(sysroot, "home", "user", ".ssh"), exist_ok=True) os.makedirs(os.path.join(sysroot, "lib", "firmware", "mediatek", "mt6797"), exist_ok=True) with open(os.path.join(sysroot, "etc", "passwd"), "w", encoding="utf-8") as f: f.write("root:x:0:0:root:/root:/bin/bash\nuser:x:10000:10000::/home/user:/bin/bash\n") with open(os.path.join(sysroot, "etc", "ssh", "sshd_config"), "w", encoding="utf-8") as f: f.write("Port 22\n") with open(os.path.join(sysroot, "etc", "ssh", "ssh_host_ed25519_key"), "w", encoding="utf-8") as f: f.write("PRIVATE HOST KEY\n") with open(os.path.join(sysroot, "etc", "ssh", "ssh_host_ed25519_key.pub"), "w", encoding="utf-8") as f: f.write("ssh-ed25519 AAAAC3...\n") with open(os.path.join(sysroot, "root", ".ssh", "authorized_keys"), "w", encoding="utf-8") as f: f.write("ssh-ed25519 AAAA_USER_KEY\n") with open(os.path.join(sysroot, "home", "user", ".ssh", "authorized_keys"), "w", encoding="utf-8") as f: f.write("ssh-ed25519 AAAA_USER_KEY\n") with open(os.path.join(sysroot, "lib", "firmware", "mediatek", "mt6797", "WIFI_RAM_CODE_6797"), "wb") as f: f.write(b"PROPRIETARY_WIFI_BLOB") with open(os.path.join(sysroot, "lib", "firmware", "mediatek", "mt6797", "MANIFEST.sha256"), "w", encoding="utf-8") as f: f.write("abc WIFI_RAM_CODE_6797\n") img_dir = os.path.join(tmp, "images") os.makedirs(img_dir, exist_ok=True) with open(os.path.join(img_dir, "boot-geminux.img"), "wb") as f: f.write(b"ANDROID!" + b"\x00" * 4088) with open(os.path.join(img_dir, "recovery-geminux.img"), "wb") as f: f.write(b"ANDROID!" + b"\x11" * 4088) root_img = os.path.join(img_dir, "geminux-rootfs.img") subprocess.run( ["mke2fs", "-t", "ext4", "-F", "-q", "-d", sysroot, root_img, "8M"], check=True, ) orig_root_sha = flash_mtk.sha256_file(root_img) out_zip = os.path.join(tmp, "geminux-0.1.0-helio-gemini-x27.zip") res = subprocess.run( [ os.path.join(BASE_DIR, "package-image.sh"), "--images-dir", img_dir, "--output", out_zip, "--version", "0.1.0", "--codename", "helio", ], capture_output=True, text=True, check=False, ) assert res.returncode == 0, f"package-image.sh failed:\n{res.stdout}\n{res.stderr}" assert flash_mtk.sha256_file(root_img) == orig_root_sha, "Source rootfs image was mutated!" assert os.path.isfile(out_zip) and os.path.isfile(out_zip + ".sha256") top = "geminux-0.1.0-helio-gemini-x27" with zipfile.ZipFile(out_zip, "r") as zf: assert zf.testzip() is None names = set(zf.namelist()) for req in ( f"{top}/FLASH-INSTRUCTIONS.txt", f"{top}/SHA256SUMS.txt", f"{top}/flash-mtk.sh", f"{top}/flash-mtk.py", f"{top}/images/boot-geminux.img", f"{top}/images/recovery-geminux.img", f"{top}/images/geminux-rootfs.img", f"{top}/scripts/bootstrap-flash-deps.sh", f"{top}/scripts/extract-vendor-fw.py", f"{top}/scripts/geminux_accounts.py", f"{top}/scripts/geminux_gpt.py", f"{top}/scripts/geminux_luks.py", f"{top}/vendor/mtkclient/mtkclient/Loader/MTK_DA_V5_MT6797.bin", ): assert req in names, f"ZIP missing {req}" assert not any("__pycache__" in n or n.endswith((".pyc", ".pyo")) for n in names), "Found bytecode in ZIP" sh_info = zf.getinfo(f"{top}/flash-mtk.sh") assert ((sh_info.external_attr >> 16) & 0o111) == 0o111, "flash-mtk.sh missing +x attr" txt = zf.read(f"{top}/FLASH-INSTRUCTIONS.txt").decode("utf-8") for needle in ("./flash-mtk.sh --flash-full", "sha256sum -c SHA256SUMS.txt", "LEFT USB-C port", "Docker is NOT required"): assert needle in txt, f"FLASH-INSTRUCTIONS.txt missing {needle!r}" # Extract with unzip to verify preserved executable bits, SHA256SUMS, and flasher launch ext_dir = os.path.join(tmp, "extracted") os.makedirs(ext_dir, exist_ok=True) subprocess.run(["unzip", "-q", out_zip, "-d", ext_dir], check=True) rel_dir = os.path.join(ext_dir, top) subprocess.run(["sha256sum", "-c", "SHA256SUMS.txt"], cwd=rel_dir, check=True, stdout=subprocess.DEVNULL) ext_env = dict(os.environ) if os.path.isdir(FLASH_DEPS): ext_env["PYTHONPATH"] = FLASH_DEPS hres = subprocess.run( ["./flash-mtk.sh", "--help"], cwd=rel_dir, env=ext_env, capture_output=True, text=True, check=False, ) assert hres.returncode == 0, f"Extracted flash-mtk.sh --help failed:\n{hres.stdout}\n{hres.stderr}" sanitized_img = os.path.join(rel_dir, "images", "geminux-rootfs.img") assert subprocess.run(["e2fsck", "-fn", sanitized_img], capture_output=True).returncode == 0 fw_mod = flash_mtk.load_firmware_module() fw_entries = set(fw_mod.debugfs_ls(sanitized_img, "lib/firmware/mediatek/mt6797")) assert {"WIFI_RAM_CODE_6797", "MANIFEST.sha256"}.issubset(fw_entries), ( f"Default package-image.sh must keep MT6797 firmware blobs; got {sorted(fw_entries)}" ) assert [n for n, _m in pkg_mod._debugfs_ls_details(sanitized_img, "etc/ssh") if n.startswith("ssh_host_")] == [] assert "sshd_config" in fw_mod.debugfs_ls(sanitized_img, "etc/ssh") assert not fw_mod._debugfs_path_exists(sanitized_img, "/root/.ssh/authorized_keys") assert not fw_mod._debugfs_path_exists(sanitized_img, "/home/user/.ssh/authorized_keys") stripped_zip = os.path.join(tmp, "geminux-0.1.0-helio-gemini-x27-stripped.zip") sres = subprocess.run( [ os.path.join(BASE_DIR, "package-image.sh"), "--images-dir", img_dir, "--output", stripped_zip, "--version", "0.1.0", "--codename", "helio", "--strip-firmware", ], capture_output=True, text=True, check=False, ) assert sres.returncode == 0, f"package-image.sh --strip-firmware failed:\n{sres.stdout}\n{sres.stderr}" strip_dir = os.path.join(tmp, "extracted-stripped") os.makedirs(strip_dir, exist_ok=True) subprocess.run(["unzip", "-q", stripped_zip, "-d", strip_dir], check=True) stripped_img = os.path.join(strip_dir, top, "images", "geminux-rootfs.img") assert subprocess.run(["e2fsck", "-fn", stripped_img], capture_output=True).returncode == 0 assert fw_mod.debugfs_ls(stripped_img, "lib/firmware/mediatek/mt6797") == [] print("[PASS] Release ZIP packager (sanitized rootfs, FLASH-INSTRUCTIONS.txt, SHA256SUMS, runnable flasher) verified") def test_cli_help(): res = subprocess.run( [os.path.join(BASE_DIR, "flash-mtk.sh"), "--help"], capture_output=True, text=True, check=False, ) assert res.returncode == 0, res.stderr for flag in ( "--only-backup", "--flash-full", "--flash-rootfs-only", "--customize-rootfs", "--skip-firmware-inject", "--username", "--user-password", "--ask-user-password", "--root-password", "--ask-root-password", "--use-default-credentials", "--encrypt", "--luks-password", "--ask-luks-password", "--reboot", "--poweroff", "--no-reboot", "--wait-timeout", ): assert flag in res.stdout, f"Missing CLI option {flag} in --help" print("[PASS] flash-mtk.sh --help verified") def main(): test_gpt_repartition() test_write_safety() test_firmware_extraction() test_mtkclient_gpt_settings() test_finish_da_session() test_fast_preloader_handshake() test_xflash_shutdown_wire_packet() test_sha512_crypt_and_username_validation() test_account_customization_ext4() test_luks2_encryption_offline() test_firmware_injection_ext4() test_release_zip_packager() test_cli_help() if __name__ == "__main__": main()