Debloat your Android TV, install apps, browse and transfer files on it, all from your phone. Just 3 MB, no tracking, no root, no PC.
Sign data/: tools/data.py index, sign, check and the Data check
tellyscope-agenta64ff6557903
diff --git a/.github/workflows/data.yml b/.github/workflows/data.ymlnew file mode 100644index 0000000..ffec904--- /dev/null+++ b/.github/workflows/data.yml@@ -0,0 +1,23 @@+name: Data++# data/ is downloaded by every installed app straight from main, so it may only change with a valid signature.+on:+ pull_request:+ paths: ["data/**", "tools/data.py", "tools/test_data.py", "tools/data-keys/**", ".github/workflows/data.yml"]+ push:+ branches: [main, dev]+ paths: ["data/**", "tools/data.py", "tools/test_data.py", "tools/data-keys/**", ".github/workflows/data.yml"]++permissions:+ contents: read++jobs:+ check:+ name: data/ index and signature+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v7+ - name: Tests+ run: python3 -m unittest discover -s tools -p 'test_data.py' -v+ - name: data/index.json is fresh and data/index.json.sig verifies+ run: python3 tools/data.py checkdiff --git a/.gitignore b/.gitignoreindex 4343bcb..19f253d 100644--- a/.gitignore+++ b/.gitignore@@ -18,3 +18,4 @@ keystore.properties# OS.DS_Store+__pycache__/diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 1ebc54e..63cece5 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -40,6 +40,38 @@ Which launchers may turn on an accessibility service is not on any list: it's `AThe tests use small fixtures in [`app/src/test/resources/fixtures/`](app/src/test/resources/fixtures/) that only check the code: change the real debloat lists in tellyscope-devices and the others in `data/`, not there. The app itself bundles none.+### Signing `data/`++The app trusts `data/` only when `data/index.json.sig` verifies: an ECDSA P-256 / SHA-256 signature over+the exact bytes of `data/index.json`, which holds the sha256 of every file in `data/`. The public keys+are built into the app and kept in [`tools/data-keys/`](tools/data-keys/) for the `Data` check: a primary,+used for every update, and a backup kept offline, so losing the primary doesn't lock apps out. The+private keys stay on the maintainer's machine, never in this repo or in CI. Make each one once:++```sh+openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out tellyscope-data-primary.pem+openssl pkey -in tellyscope-data-primary.pem -pubout -outform DER | openssl base64 -A > tools/data-keys/primary.pub+# the same with tellyscope-data-backup.pem > tools/data-keys/backup.pub, then store the backup offline+```++Changing a public key needs an app release.++**Sign last, after review, and only a branch you'll merge.** Once a signed `data/index.json` is on+GitHub it stays fetchable by its commit forever, and anyone serving it gets it treated as signed, even+if the pull request was rejected.++Every change to `data/`:++1. Contributors run `python3 tools/data.py index` and `python3 tools/data.py check --unsigned`. The+ `Data` check fails on the signature until the maintainer signs.+2. After review, on the pull request's branch, the maintainer runs+ `python3 tools/data.py sign --key ~/path/to/tellyscope-data-primary.pem`. It refuses a key that+ `tools/data-keys/` doesn't verify.+3. Commit `data/index.json.sig`, let `Data` pass, merge.++`index` keeps `version` (`YYYYMMDDNN`, UTC) while nothing else changes and raises it otherwise; the app+refuses an index older than the one it has.+## README screenshotsThey come from the screenshot tests, so they always show the current UI with sample data. To refresh them, render the tests, then put them in phone frames (needs Python 3 with Pillow):diff --git a/tools/data-keys/backup.pub b/tools/data-keys/backup.pubnew file mode 100644index 0000000..3f864a3--- /dev/null+++ b/tools/data-keys/backup.pub@@ -0,0 +1 @@+# Backup key, kept offline: placeholder, the real public key goes on the next line.diff --git a/tools/data-keys/primary.pub b/tools/data-keys/primary.pubnew file mode 100644index 0000000..79c4f25--- /dev/null+++ b/tools/data-keys/primary.pub@@ -0,0 +1 @@+# Primary key: TEST KEY, replace before merge. Its private half was thrown away, so nothing can sign with it.diff --git a/tools/data.py b/tools/data.pynew file mode 100644index 0000000..2749eb3--- /dev/null+++ b/tools/data.py@@ -0,0 +1,150 @@+#!/usr/bin/env python3+"""Index and sign data/, the lists the app downloads from this repo. Python 3.9+, standard library only.++ tools/data.py index rebuild data/index.json from data/+ tools/data.py sign --key <private key.pem> write data/index.json.sig, signed with that key+ tools/data.py check [--unsigned] fail if data/index.json is stale or data/index.json.sig+ doesn't verify against tools/data-keys/ (--unsigned skips that)++Signing and checking signatures need the openssl command. How and when to sign: CONTRIBUTING.md.+"""+import base64+import datetime+import hashlib+import json+import subprocess+import sys+import tempfile+from pathlib import Path++SCHEMA = 1+REPO = Path(__file__).resolve().parent.parent+DATA = REPO / "data"+KEYS = REPO / "tools" / "data-keys"+LISTS = ("launchers", "labels", "streaming")+# Every P-256 public key in SubjectPublicKeyInfo DER starts with these bytes, then 64 bytes of point.+P256_SPKI = bytes.fromhex("3059301306072a8648ce3d020106082a8648ce3d030107034200" "04")+++def dump(obj):+ return json.dumps(obj, indent=2, ensure_ascii=False) + "\n"+++def build_index():+ def file(path):+ return {"file": path, "sha256": hashlib.sha256((DATA / path).read_bytes()).hexdigest()}++ index = {"lists": {name: file(f"{name}.json") for name in LISTS}}+ return {"schema": SCHEMA, "version": version(index), **index}+++def version(index):+ """The old version when nothing else changed, else YYYYMMDDNN for today (UTC), always above the+ old one. The app refuses an index older than the one it has."""+ path = DATA / "index.json"+ old = json.loads(path.read_text(encoding="utf-8")) if path.is_file() else {}+ old.pop("schema", None)+ previous = old.pop("version", 0)+ if old == index and previous:+ return previous+ return max(previous + 1, int(datetime.datetime.now(datetime.timezone.utc).strftime("%Y%m%d")) * 100 + 1)+++def public_keys():+ """tools/data-keys/*.pub: one base64 SubjectPublicKeyInfo per file, '#' lines are comments.+ Returns (keys, errors)."""+ keys, errors = [], []+ for f in sorted(KEYS.glob("*.pub")):+ lines = [l.strip() for l in f.read_text(encoding="utf-8").splitlines()]+ lines = [l for l in lines if l and not l.startswith("#")]+ if not lines:+ continue # a placeholder+ try:+ der = base64.b64decode("".join(lines), validate=True)+ except ValueError:+ der = b""+ if len(der) != len(P256_SPKI) + 64 or not der.startswith(P256_SPKI):+ errors.append(f"tools/data-keys/{f.name}: not a base64 P-256 public key")+ else:+ keys.append(der)+ if not keys and not errors:+ errors.append("tools/data-keys/: no public key to check data/index.json.sig against")+ return keys, errors+++def openssl(*args):+ return subprocess.run(["openssl", *args], capture_output=True)+++def verifies(data, signature, key):+ """True if signature (DER ECDSA) is over data with key (SPKI DER), SHA-256."""+ with tempfile.TemporaryDirectory() as tmp:+ tmp = Path(tmp)+ (tmp / "data").write_bytes(data)+ (tmp / "sig").write_bytes(signature)+ (tmp / "key.der").write_bytes(key)+ return openssl("dgst", "-sha256", "-keyform", "DER", "-verify", str(tmp / "key.der"),+ "-signature", str(tmp / "sig"), str(tmp / "data")).returncode == 0+++def check_signature():+ keys, errors = public_keys()+ sig = DATA / "index.json.sig"+ if errors:+ return errors+ if not sig.is_file():+ return ["data/index.json.sig is missing: run tools/data.py sign --key <private key>"]+ try:+ signature = base64.b64decode(sig.read_text(encoding="utf-8").strip(), validate=True)+ except ValueError:+ return ["data/index.json.sig: not base64"]+ if not any(verifies((DATA / "index.json").read_bytes(), signature, k) for k in keys):+ return ["data/index.json.sig doesn't verify against tools/data-keys/: data/index.json changed "+ "since it was signed, run tools/data.py sign --key <private key>"]+ return []+++def sign(key):+ """Sign data/index.json's exact bytes with key and write data/index.json.sig, if a key in+ tools/data-keys/ verifies it."""+ data = (DATA / "index.json").read_bytes()+ with tempfile.TemporaryDirectory() as tmp:+ (Path(tmp) / "data").write_bytes(data)+ run = openssl("dgst", "-sha256", "-sign", str(key), str(Path(tmp) / "data"))+ if run.returncode != 0:+ print(run.stderr.decode(errors="replace"), file=sys.stderr)+ return 1+ keys, errors = public_keys()+ if errors or not any(verifies(data, run.stdout, k) for k in keys):+ print(*errors, "the signature doesn't verify against any key in tools/data-keys/: wrong key?",+ sep="\n", file=sys.stderr)+ return 1+ (DATA / "index.json.sig").write_text(base64.b64encode(run.stdout).decode() + "\n", encoding="utf-8")+ return 0+++def check(signed=True):+ index = DATA / "index.json"+ if not index.is_file() or index.read_text(encoding="utf-8") != dump(build_index()):+ errors = ["data/index.json is stale: run tools/data.py index"]+ else:+ errors = check_signature() if signed else []+ for e in errors:+ print(e, file=sys.stderr)+ return 1 if errors else 0+++def main(argv):+ if argv[:1] == ["check"] and argv[1:] in ([], ["--unsigned"]):+ return check(signed=not argv[1:])+ if argv[:2] == ["sign", "--key"] and len(argv) == 3:+ return sign(argv[2])+ if argv == ["index"]:+ (DATA / "index.json").write_text(dump(build_index()), encoding="utf-8")+ return 0+ print(__doc__, file=sys.stderr)+ return 2+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/tools/test_data.py b/tools/test_data.pynew file mode 100644index 0000000..54847e6--- /dev/null+++ b/tools/test_data.py@@ -0,0 +1,68 @@+import base64+import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent))+import data # noqa: E402+++class Signing(unittest.TestCase):+ """data/index.json.sig is what the app trusts, so check must fail whenever it doesn't cover the index."""++ def setUp(self):+ self.root = Path(tempfile.mkdtemp())+ self.addCleanup(shutil.rmtree, self.root)+ for d in ("data", "keys"):+ (self.root / d).mkdir()+ for name, value in (("DATA", self.root / "data"), ("KEYS", self.root / "keys")):+ self.addCleanup(setattr, data, name, getattr(data, name))+ setattr(data, name, value)+ for name in ("primary", "other"):+ subprocess.run(["openssl", "genpkey", "-algorithm", "EC", "-pkeyopt", "ec_paramgen_curve:P-256",+ "-out", str(self.root / f"{name}.pem")], check=True, capture_output=True)+ (self.root / "keys" / "primary.pub").write_text("# test\n" + self.public("primary") + "\n")+ (self.root / "keys" / "backup.pub").write_text("# placeholder\n")+ (self.root / "data" / "index.json").write_text('{"schema": 1, "version": 2026110301}\n')++ def public(self, name):+ der = subprocess.run(["openssl", "pkey", "-in", str(self.root / f"{name}.pem"), "-pubout", "-outform", "DER"],+ check=True, capture_output=True).stdout+ return base64.b64encode(der).decode()++ def test_a_signed_index_passes(self):+ self.assertEqual(data.sign(self.root / "primary.pem"), 0)+ self.assertEqual(data.check_signature(), [])++ def test_an_edit_after_signing_fails(self):+ data.sign(self.root / "primary.pem")+ (self.root / "data" / "index.json").write_text('{"schema": 1, "version": 2026110302}\n')+ self.assertIn("doesn't verify", "\n".join(data.check_signature()))++ def test_a_missing_signature_fails(self):+ self.assertIn("index.json.sig is missing", "\n".join(data.check_signature()))++ def test_sign_refuses_a_key_not_in_keys(self):+ self.assertEqual(data.sign(self.root / "other.pem"), 1)+ self.assertFalse((self.root / "data" / "index.json.sig").exists())++ def test_the_backup_key_verifies_too(self):+ (self.root / "keys" / "backup.pub").write_text(self.public("other") + "\n")+ data.sign(self.root / "other.pem")+ self.assertEqual(data.check_signature(), [])++ def test_a_key_that_is_not_p256_is_caught(self):+ (self.root / "keys" / "backup.pub").write_text("bm90IGEga2V5\n")+ self.assertIn("not a base64 P-256 public key", "\n".join(data.public_keys()[1]))++ def test_version_stays_while_nothing_changes_and_only_goes_up(self):+ (self.root / "data" / "index.json").write_text('{"schema": 1, "version": 2099010105, "lists": {}}\n')+ self.assertEqual(data.version({"lists": {}}), 2099010105)+ self.assertEqual(data.version({"lists": {"a": 1}}), 2099010106)+++if __name__ == "__main__":+ unittest.main()