Files
LihonT/lihont/clone.py
cheb0chik ce1d870d54 LihonT 2 Luna beta: source release
Mod for TikTok 47.1.3 (arm64) in Material 3 style: bottom bar, profile menu, TikTok settings and
comments; downloads without the watermark; switches for ads, live streams and the Shop tab; badges of
other mods next to names and the niche mod badge (members service); app icons; mod settings screen.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-22 20:32:13 +03:00

186 lines
7.6 KiB
Python

"""Repackage the built LihonT 2.0 APK under an independent application ID.
The output installs alongside TikTok and any LihonT 1.x build instead of
replacing them. Class names, method definitions and resource IDs stay fixed;
only application identity changes: the manifest package attribute, provider
authorities, custom permissions, resource package names in resources.arsc and
the matching string literals inside DEX files. The APK is then re-signed.
python -m lihont.clone ComplectAPK/lihont-2.0-test.apk \
-o ComplectAPK/lihont-2.0-test.burmalda.apk --package test.test.burmalda
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import shutil
import subprocess
from pathlib import Path
from .apkzip import Apk
from .axml import Axml
from . import dexpatch, editions, manifest
from .toolchain import Toolchain
SOURCE_VERSION = "47.1.3"
def edition_dex_helper(tools: Toolchain, room: Path, clone: str, api: int) -> Path:
"""Compile a clone-specific EditionDex: the Java helper hardcodes the id."""
source = Path(__file__).parent / "java" / "EditionDex.java"
if not source.exists():
source = Path("src/EditionDex.java").resolve()
text = source.read_text(encoding="utf-8")
if editions.CLONE not in text:
raise ValueError("EditionDex source does not carry the expected clone id")
variant = room / "src" / "EditionDex.java"
variant.parent.mkdir(parents=True, exist_ok=True)
variant.write_text(text.replace(editions.CLONE, clone), encoding="utf-8")
compiler = room / "compiler"
compiler.mkdir(parents=True, exist_ok=True)
subprocess.run(
["javac", "--release", "17", "-classpath", tools.smali,
"-d", str(compiler), str(variant)], check=True
)
return compiler
def rewrite_dex(apk: Apk, mapping: dict, tools: Toolchain, room: Path, clone: str, api: int) -> dict:
compiler = edition_dex_helper(tools, room, clone, api)
smali_jar = tools.smali
report: dict = {}
cache_root = room / "dex-cache"
for name in sorted(n for n in apk.names() if n.endswith(".dex")):
data = apk.read(name)
if not any(key.encode("ascii") in data for key in mapping):
continue
key = hashlib.sha256(
data + json.dumps(mapping, sort_keys=True).encode()
+ clone_fingerprint(mapping).encode()
).hexdigest()
cache = cache_root / key
cache.mkdir(parents=True, exist_ok=True)
patched = cache / "patched.dex"
info_path = cache / "report.json"
if patched.exists() and info_path.exists():
info = json.loads(info_path.read_text())
if hashlib.sha256(patched.read_bytes()).hexdigest() != info["sha256"]:
raise ValueError("Invalid cached DEX in " + name)
print("Cached " + name, flush=True)
else:
original = cache / "original.dex"
original.write_bytes(data)
properties = cache / "identities.properties"
properties.write_text(
"\n".join(k + "=" + v for k, v in sorted(mapping.items())),
encoding="utf-8",
)
print("Rewrite DEX identities: " + name, flush=True)
result = subprocess.run(
["java", "-Xmx1g", "-cp", os.pathsep.join([str(compiler), smali_jar]),
"EditionDex", str(original), str(patched), str(properties), str(api)],
check=True, capture_output=True, text=True, encoding="utf-8", errors="replace",
)
changed = json.loads(result.stdout.strip())
info = {"sha256": hashlib.sha256(patched.read_bytes()).hexdigest(), **changed}
info_path.write_text(json.dumps(info, indent=2), encoding="utf-8")
if dexpatch.defined_methods(data) != dexpatch.defined_methods(patched.read_bytes()) or \
dexpatch.dex_format(data) != dexpatch.dex_format(patched.read_bytes()):
raise ValueError("Clone changed class definitions or DEX format in " + name)
if info["literals"]:
apk.replace(name, patched.read_bytes())
report[name] = {"literals": info["literals"], "classes": info["classes"]}
return report
def clone_fingerprint(mapping: dict) -> str:
return hashlib.sha256(
"|".join(k + "->" + v for k, v in sorted(mapping.items())).encode()
).hexdigest()[:16]
def build(source: str, output: str, clone: str, workspace: str = "work/clone") -> dict:
source_path, output_path, room = (
Path(source).resolve(), Path(output).resolve(), Path(workspace).resolve()
)
if source_path == output_path:
raise ValueError("Keep the input APK unchanged")
if not clone or "." not in clone:
raise ValueError("Clone application id looks invalid: " + clone)
room.mkdir(parents=True, exist_ok=True)
tools = Toolchain("tools")
apk = Apk(str(source_path))
report = {
"clone_package": clone, "source": source_path.name,
"source_sha256": hashlib.sha256(source_path.read_bytes()).hexdigest(),
}
try:
axml = Axml.parse(apk.read("AndroidManifest.xml"))
if manifest.package_name(axml) != editions.ORIGINAL or \
manifest.version_name(axml) != SOURCE_VERSION:
raise ValueError("Expected the LihonT 2.0 TikTok " + SOURCE_VERSION + " baseline")
api = manifest.min_sdk(axml)
# editions.* helpers carry the previous clone id; retarget them all.
old_clone = editions.CLONE
editions.CLONE = clone
try:
mapping = editions.authority_map(axml)
# SHARED was precomputed at import time with the old clone id.
mapping = {
key: (clone + value[len(old_clone):] if value.startswith(old_clone) else value)
for key, value in mapping.items()
}
editions.clone_manifest(axml, mapping)
resources, changed_packages = editions.clone_resource_packages(apk.read("resources.arsc"))
apk.replace("resources.arsc", resources)
report["resource_packages"] = changed_packages
finally:
editions.CLONE = old_clone
report["changed_dex"] = rewrite_dex(apk, mapping, tools, room, clone, api)
apk.replace("AndroidManifest.xml", axml.build())
apk.drop_signature()
output_path.parent.mkdir(parents=True, exist_ok=True)
apk.write(str(output_path))
finally:
apk.close()
tools.sign(str(output_path))
# Verify the signed artifact actually carries the requested identity.
check = Apk(str(output_path))
try:
identity = manifest.package_name(Axml.parse(check.read("AndroidManifest.xml")))
finally:
check.close()
if identity != clone:
raise ValueError("Clone identity mismatch: " + identity)
report["verified_package"] = identity
report.update({
"file": output_path.name, "bytes": output_path.stat().st_size,
"sha256": hashlib.sha256(output_path.read_bytes()).hexdigest(),
})
Path(str(output_path) + ".json").write_text(
json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8"
)
return report
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("apk")
parser.add_argument("-o", "--out", required=True)
parser.add_argument("--package", default="test.test.burmalda")
parser.add_argument("--work", default="work/clone")
args = parser.parse_args()
print(json.dumps(
build(args.apk, args.out, args.package, args.work),
ensure_ascii=False, indent=2
))
if __name__ == "__main__":
main()