Debloat any Android or Google TV over Wi-Fi and get an Apple TV-style home.
Python adbadblockandroid-tvandroid-tv-launcherapple-tvbloatware-removalclaude-codedebloatfire-tvgoogle-tvlauncherprivacysmart-tvsony-braviatclvibe-codingxiaomi
tools: theme.sh and theme.ps1 check every wallpaper name before the TV changes
Mazin Kanugaa872cc3c9cde
diff --git a/tests/test_theme_names_first.py b/tests/test_theme_names_first.pynew file mode 100644index 000000000..848a5c1e4--- /dev/null+++ b/tests/test_theme_names_first.py@@ -0,0 +1,124 @@+"""tools/theme.sh and theme.ps1 check every collection name before anything changes on the TV.++The name check used to sit inside the loop that pushes the collection, after config.json had been+replaced and the old collection emptied. A theme with one name the script refuses ("bad name.jpg")+stopped there with exit 1 and left the new config.json and the pictures before it on the TV, though+nothing said the theme had half applied. A name the check let through but b64push.py refuses, a+path with ".." in it ("sunset..jpg"), stopped the same way with b64push's exit 2. Both are now+refused in one pass next to the JSON check, before the first command reaches the TV.++theme.ps1's clear also listed only lower- and upper-case extensions, so without the launcher's+ThemeProvider it left c.JpG or e.PnG behind, which the launcher still shows (WallpaperRotation+lower-cases the name). It now uses theme.sh's bracket globs.++theme.sh runs against the fake TV of tests/test_theme_push_ownership.py. theme.ps1 cannot run here:+its clear string runs through /bin/sh, and the order of its checks is pinned as text.++Run from the repository root: python3 -m unittest discover -s tests -v+"""+import os+from pathlib import Path+import re+import shutil+import subprocess+import sys+import tempfile+import unittest++sys.path.insert(0, str(Path(__file__).resolve().parent))+import test_theme_push_ownership as push # noqa: E402 (imported as a module so its tests do not run twice)++TOOLS = push.TOOLS+URI = "content://com.gathin.tvhome.theme"+++class ThemeNamesFirstTest(unittest.TestCase):+ # Borrowed rather than inherited, so the tests of tests/test_theme_push_ownership.py do not run a+ # second time under this class.+ setUp = push.ThemePushTest.setUp+ run_theme = push.ThemePushTest.run_theme+ shell_commands = push.ThemePushTest.shell_commands++ def theme_on_the_tv(self):+ """The TV before the push: an earlier theme's config.json and one picture in its collection."""+ (self.device / "config.json").write_bytes(b'{"background": "#000000"}')+ (self.device / "wallpapers").mkdir()+ (self.device / "wallpapers" / "old.jpg").write_bytes(b"old collection")++ def assertTvUnchanged(self, result, name):+ self.assertEqual(result.returncode, 1, result.stdout + result.stderr)+ self.assertIn(f"unsupported wallpaper filename: {name}", result.stderr)+ self.assertEqual((self.device / "config.json").read_bytes(), b'{"background": "#000000"}',+ "the refused theme's config.json must not replace the one on the TV")+ self.assertEqual(sorted(p.name for p in (self.device / "wallpapers").iterdir()), ["old.jpg"],+ "the collection on the TV must be left as it was")+ self.assertEqual(self.shell_commands(), [], "nothing may reach the TV before every name is checked")++ def test_a_refused_name_leaves_the_tv_as_it_was(self):+ self.theme_on_the_tv()+ collection = self.theme / "wallpapers"+ collection.mkdir()+ (collection / "a-good.jpg").write_bytes(b"\xff\xd8good")+ (collection / "bad name.jpg").write_bytes(b"\xff\xd8bad")+ self.assertTvUnchanged(self.run_theme(str(self.theme)), "bad name.jpg")++ def test_a_name_b64push_refuses_is_refused_first(self):+ """b64push.py refuses a remote path with '..' in it, so sunset..jpg could never reach the TV."""+ self.theme_on_the_tv()+ collection = self.theme / "wallpapers"+ collection.mkdir()+ (collection / "dawn.jpg").write_bytes(b"\xff\xd8dawn")+ (collection / "sunset..jpg").write_bytes(b"\xff\xd8sunset")+ self.assertTvUnchanged(self.run_theme(str(self.theme)), "sunset..jpg")++ def test_names_with_single_dots_still_go_through(self):+ self.theme_on_the_tv()+ collection = self.theme / "wallpapers"+ collection.mkdir()+ names = ("01.dusk.jpg", "v1.2-lake.PNG")+ for name in names:+ (collection / name).write_bytes(b"\x00\xff" + name.encode())+ result = self.run_theme(str(self.theme))+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)+ self.assertEqual(sorted(p.name for p in (self.device / "wallpapers").iterdir()), sorted(names))+ self.assertEqual((self.device / "config.json").read_bytes(), self.config)++ def test_the_windows_clear_removes_every_spelling_without_the_provider(self):+ if os.name != "posix":+ raise unittest.SkipTest("the clear runs in the TV's shell; this test needs /bin/sh")+ script = (TOOLS / "theme.ps1").read_text(encoding="utf-8")+ line = next(line for line in script.splitlines() if line.startswith("$clearWallpapers = "))+ clear = line[len('$clearWallpapers = "'):-1]+ self.assertNotIn("`", clear, "PowerShell escapes would make this differ from what the TV runs")+ base = Path(tempfile.mkdtemp())+ self.addCleanup(shutil.rmtree, base, ignore_errors=True)+ device = base / "files"+ bin_dir = base / "bin"+ bin_dir.mkdir()+ content = bin_dir / "content"+ content.write_text("#!/bin/sh\nexit 1\n") # firmware or a launcher without the ThemeProvider+ content.chmod(0o755)+ command = clear.replace("$dir", str(device)).replace("$uri", URI)+ self.assertNotIn("$", command, command)+ (device / "wallpapers").mkdir(parents=True)+ for name in ("a.jpg", "b.JPG", "c.JpG", "d.Jpeg", "e.PnG", "f.WebP", "g.webp", "captions.txt"):+ (device / "wallpapers" / name).write_bytes(b"\x89picture")+ result = subprocess.run(["/bin/sh", "-c", command], capture_output=True, text=True, timeout=60,+ env={**os.environ, "PATH": f"{bin_dir}:{os.environ.get('PATH', '')}"})+ self.assertEqual(sorted(p.name for p in (device / "wallpapers").iterdir()), ["captions.txt"],+ "the launcher shows a mixed-case picture left in the folder: " + result.stderr)++ def test_the_windows_script_checks_every_name_before_the_tv(self):+ """theme.ps1 cannot run here, so pin that its name check comes before its first call to tv.py."""+ script = (TOOLS / "theme.ps1").read_text(encoding="utf-8")+ check = script.index("unsupported wallpaper filename")+ json_at = script.index("is not valid JSON")+ # Invoke-Tv (#566) or a bare "& $py -I", whichever spelling the call has.+ first_call = json_at + re.search(r"^(?:Invoke-Tv|& \$py -I) tv\.py", script[json_at:], re.M).start()+ self.assertLess(check, first_call, "a refused name must stop the push before the TV changes")+ line = next(line for line in script.splitlines() if "unsupported wallpaper filename" in line)+ self.assertIn("'..'", line, "b64push.py refuses a path with '..' in it")+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_theme_push_ownership.py b/tests/test_theme_push_ownership.pyindex 41e06574c..8c8bc8681 100644--- a/tests/test_theme_push_ownership.py+++ b/tests/test_theme_push_ownership.py@@ -329,7 +329,7 @@ class ThemePushTest(unittest.TestCase):self.assertIn("$(Drop 'wallpapers/captions.txt')", reset)self.assertIn("$clearWallpapers", reset, "one shared clear, as in theme.sh")clear = next(line for line in script.splitlines() if line.startswith("$clearWallpapers = "))- self.assertIn("rm -f $dir/wallpapers/*.jpg", clear)+ self.assertIn("rm -f $dir/wallpapers/*.[jJ][pP][gG]", clear)self.assertIn("content delete --uri $uri/wallpapers", clear)self.assertNotIn("captions", clear, "the captions file is dropped on its own line, as in theme.sh")diff --git a/themes/README.md b/themes/README.mdindex 174166236..f2e175d54 100644--- a/themes/README.md+++ b/themes/README.md@@ -169,7 +169,8 @@ shown once and never blanked on a timer. Images are centre-cropped to fill the 1drawn as a black overlay above the picture and below the launcher's text.When you apply a theme, its collection replaces the one already on the TV. Use filenames containing-only letters, digits, underscores, dots and hyphens. Images can come from any source; check that you+only letters, digits, underscores, dots and hyphens, with no two dots in a row; the theme scripts refuse+any other name before they change anything on the TV. Images can come from any source; check that youhave permission to use them. The launcher considersup to 100 nonempty images, at most 10 MB each, skips unreadable files and keeps the last good background.An empty collection falls back to `wallpaper.jpg`, or the background colour if no image is available.diff --git a/tools/theme.ps1 b/tools/theme.ps1index e32900567..b07e5ac78 100644--- a/tools/theme.ps1+++ b/tools/theme.ps1@@ -60,7 +60,7 @@ function Drop($name) { "rm -f $dir/$name 2>/dev/null; content delete --uri $uri/# empty it too: the launcher's wallpaper picker lists that folder itself, and an on-TV pick of one of its# pictures is read back from it, so a reset that left the pictures behind still shows the theme it just removed.# Both paths use this one string (the same one theme.sh has).-$clearWallpapers = "mkdir -p $dir/wallpapers 2>/dev/null; rm -f $dir/wallpapers/*.jpg $dir/wallpapers/*.jpeg $dir/wallpapers/*.png $dir/wallpapers/*.webp $dir/wallpapers/*.JPG $dir/wallpapers/*.JPEG $dir/wallpapers/*.PNG $dir/wallpapers/*.WEBP 2>/dev/null; content delete --uri $uri/wallpapers 2>/dev/null"+$clearWallpapers = "mkdir -p $dir/wallpapers 2>/dev/null; rm -f $dir/wallpapers/*.[jJ][pP][gG] $dir/wallpapers/*.[jJ][pP][eE][gG] $dir/wallpapers/*.[pP][nN][gG] $dir/wallpapers/*.[wW][eE][bB][pP] 2>/dev/null; content delete --uri $uri/wallpapers 2>/dev/null"if ($Reset) {Invoke-Tv tv.py "mkdir -p $dir 2>/dev/null; $(Drop 'config.json'); $(Drop 'wallpaper.jpg'); $(Drop 'wallpapers/captions.txt'); $clearWallpapers; printf '%s' '$revision' > $tmp-theme_revision; $(Put 'theme_revision'); $restart; echo reset"@@ -70,6 +70,16 @@ if (-not $Theme) { throw 'usage: theme.ps1 <theme folder> | -Reset' }$config = Join-Path $Theme 'config.json'if (-not (Test-Path $config)) { throw "no config.json in $Theme" }try { Get-Content $config -Raw | ConvertFrom-Json | Out-Null } catch { throw "$config is not valid JSON" }+# Every collection name is checked before anything changes on the TV, as in theme.sh: a name refused halfway+# through the push left the new config.json and part of the collection behind. b64push.py refuses '..' in a path.+$wallpapers = Join-Path $Theme 'wallpapers'+$images = @()+if (Test-Path $wallpapers -PathType Container) {+ $images = @(Get-ChildItem $wallpapers -File | Where-Object { $_.Extension -match '^\.(jpg|jpeg|png|webp)$' })+ foreach ($image in $images) {+ if ($image.Name -notmatch '^[A-Za-z0-9_.-]+$' -or $image.Name.Contains('..')) { throw "unsupported wallpaper filename: $($image.Name)" }+ }+}# Tolerated, as in theme.sh: a TV that locks Android/data still takes the files through ThemeProvider.Invoke-Tv tv.py "mkdir -p $dir 2>/dev/null; true" | Out-Null@@ -78,13 +88,9 @@ Invoke-Tv tv.py (Put 'config.json')$wall = Join-Path $Theme 'wallpaper.jpg'if (Test-Path $wall) { Invoke-Tv b64push.py $wall "$tmp-wallpaper.jpg"; Invoke-Tv tv.py (Put 'wallpaper.jpg') } else { Invoke-Tv tv.py (Drop 'wallpaper.jpg') | Out-Null }Invoke-Tv tv.py $clearWallpapers | Out-Null-$wallpapers = Join-Path $Theme 'wallpapers'-if (Test-Path $wallpapers -PathType Container) {- Get-ChildItem $wallpapers -File | Where-Object { $_.Extension -match '^\.(jpg|jpeg|png|webp)$' } | ForEach-Object {- if ($_.Name -notmatch '^[A-Za-z0-9_.-]+$') { throw "unsupported wallpaper filename: $($_.Name)" }- Invoke-Tv b64push.py $_.FullName (Stage "wallpapers/$($_.Name)")- Invoke-Tv tv.py (Put "wallpapers/$($_.Name)") | Out-Null- }+foreach ($image in $images) {+ Invoke-Tv b64push.py $image.FullName (Stage "wallpapers/$($image.Name)")+ Invoke-Tv tv.py (Put "wallpapers/$($image.Name)") | Out-Null}# The collection's names (wallpaper_captions); a theme without them leaves no stale names behind.$captions = Join-Path $Theme 'wallpapers\captions.txt'diff --git a/tools/theme.sh b/tools/theme.shindex a62401003..6a40680f1 100755--- a/tools/theme.sh+++ b/tools/theme.sh@@ -74,6 +74,21 @@ THEME="${THEME_ARG:?usage: theme.sh <theme folder> | --reset}"[ -f "$THEME/config.json" ] || { echo "no config.json in $THEME" >&2; exit 1; }"$PY" -I -c 'import json,sys; json.load(open(sys.argv[1], encoding="utf-8-sig"))' "$THEME/config.json" 2>/dev/null \|| { echo "$THEME/config.json is not valid JSON" >&2; exit 1; }+# Every collection name is checked before anything changes on the TV: a name refused halfway through the push+# left the new config.json and part of the collection behind. b64push.py refuses a path with '..' in it, so+# such a name (sunset..jpg) is refused here too. The names that pass have no spaces, so NAMES splits on them.+NAMES=""+if [ -d "$THEME/wallpapers" ]; then+ for IMAGE in "$THEME"/wallpapers/*; do+ [ -f "$IMAGE" ] || continue+ case "$IMAGE" in+ *.[jJ][pP][gG]|*.[jJ][pP][eE][gG]|*.[pP][nN][gG]|*.[wW][eE][bB][pP])+ NAME=$(basename "$IMAGE")+ [[ "$NAME" =~ ^[A-Za-z0-9_.-]+$ && "$NAME" != *..* ]] || { echo "unsupported wallpaper filename: $NAME" >&2; exit 1; }+ NAMES="$NAMES $NAME" ;;+ esac+ done+fitv "mkdir -p $DIR" >/dev/null 2>&1 || truetv --push "$THEME/config.json" "$TMP-config.json" >/dev/null@@ -85,18 +100,10 @@ elsetv "$(del wallpaper.jpg)" >/dev/nullfitv "$CLEAR_WALLPAPERS" >/dev/null-if [ -d "$THEME/wallpapers" ]; then- for IMAGE in "$THEME"/wallpapers/*; do- [ -f "$IMAGE" ] || continue- case "$IMAGE" in- *.[jJ][pP][gG]|*.[jJ][pP][eE][gG]|*.[pP][nN][gG]|*.[wW][eE][bB][pP])- NAME=$(basename "$IMAGE")- [[ "$NAME" =~ ^[A-Za-z0-9_.-]+$ ]] || { echo "unsupported wallpaper filename: $NAME" >&2; exit 1; }- "$PY" -I b64push.py "$IMAGE" "$(stage "wallpapers/$NAME")"- tv "$(put "wallpapers/$NAME")" >/dev/null ;;- esac- done-fi+for NAME in $NAMES; do+ "$PY" -I b64push.py "$THEME/wallpapers/$NAME" "$(stage "wallpapers/$NAME")"+ tv "$(put "wallpapers/$NAME")" >/dev/null+done# The collection's names (wallpaper_captions); a theme without them leaves no stale names behind.if [ -f "$THEME/wallpapers/captions.txt" ]; then"$PY" -I b64push.py "$THEME/wallpapers/captions.txt" "$(stage wallpapers/captions.txt)"