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.
Signed data/: launchers carry their signers, and a failed check asks first
jesse-agent-232d20dff5cf612
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e12c873..25a90d8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,7 +13,7 @@ until this file has a section for its version.## Unreleased- **Improved:** Launchers, app names and streaming services now come from Tellyscope's own repository. [#323](../../pull/323)-- **Improved:** Installing a launcher from a list you added shows the list and signer, and asks you to confirm. [#322](../../pull/322)+- **Improved:** The launcher list is signed. If Tellyscope can't verify it, installing a launcher shows the list and its signer, and asks you to confirm. [#322](../../pull/322)## 0.15.0 — 2026-11-03diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 9d60da5..c12a24c 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -32,7 +32,7 @@ You don't have to trust ours. Fork tellyscope-devices, edit the lists in your foThese lists live in this repository, in [`data/`](data/), and the app downloads them from `main`: change one here with a pull request, and it reaches people once it's on `main`, without an app release. Keep `data/index.json` in step: it gives each file's sha256, and the app uses only files that match. [`DataListsTest`](app/src/test/java/app/tellyscope/DataListsTest.kt) checks the lists and the index, and says which sha256 changed. tellyscope-devices still has older copies that earlier versions of the app download; they're frozen until they're retired, so don't edit them there. File formats are in that repo's README.-- `data/launchers.json`: the third-party launchers Tellyscope knows. One with an `"about"` line is offered in **Install a home screen**, in the file's order. The app names no launcher itself: what it needs to install one from an APK comes from its entry (`signers`, `max_mb`, `releases`, `fire_os`; formats in that repo's README). On Fire OS, which has no Play Store, only the `fire_os` launcher is offered, while it's on the list with `signers`: Tellyscope downloads it from its `releases` page and installs only an APK signed with one of its `signers` ([`LauncherDownload.kt`](app/src/main/java/app/tellyscope/data/LauncherDownload.kt)). On Android TV the same download is offered as **Download directly**, under the Play Store and after a warning, for any launcher with both `signers` and `releases` (`downloadable` in [`LauncherFlowUi.kt`](app/src/main/java/app/tellyscope/ui/LauncherFlowUi.kt)). When the lists come from your own source rather than the default, every one of those installs first shows the list's address and the signer, and waits for a tick saying you trust them: Tellyscope can only check the APK matches the list.+- `data/launchers.json`: the third-party launchers Tellyscope knows. One with an `"about"` line is offered in **Install a home screen**, in the file's order. The app names no launcher itself: what it needs to install one from an APK comes from its entry (`signers`, `max_mb`, `releases`, `fire_os`; `DataListsTest` checks their formats). On Fire OS, which has no Play Store, only the `fire_os` launcher is offered, while it's on the list with `signers`: Tellyscope downloads it from its `releases` page and installs only an APK signed with one of its `signers` ([`LauncherDownload.kt`](app/src/main/java/app/tellyscope/data/LauncherDownload.kt)). On Android TV the same download is offered as **Download directly**, under the Play Store and after a warning, for any launcher with both `signers` and `releases` (`downloadable` in [`LauncherFlowUi.kt`](app/src/main/java/app/tellyscope/ui/LauncherFlowUi.kt)). When `data/` fails its signature check ([below](#signing-data)), every one of those installs first shows the list's address and the signer, and waits for a tick saying you trust them: Tellyscope can then only check the APK matches the list.- `data/labels.json`: names shown for common TV apps when the TV can't tell us.- `data/streaming.json`: the streaming services the Remote can have a button for. Each names a logo, which stays in tellyscope-devices' `logos/` with its source and licence in `SOURCES.md`.diff --git a/README.md b/README.mdindex 8a891d4..ca520a3 100644--- a/README.md+++ b/README.md@@ -95,7 +95,7 @@ Tellyscope downloads two sets of public lists from GitHub, so they can change wi**What the lists can't do:**- Remove protection. The built-in protected list always wins, and `protected.json` can only add to it.-- Choose an APK to install. The only launcher Tellyscope downloads is Projectivy, from the release page and signer pinned in the app; `launchers.json` only decides whether it's offered.+- Choose an APK to install without a signature. Which launcher APK may be installed, where it downloads from and who must have signed it come only from `data/launchers.json`, and `data/` is signed by the maintainer. Your own lists can't change them. If `data/` fails its signature check, Tellyscope shows the list and its signer and asks before installing anything from it.- Turn on an accessibility service. The launchers allowed one are built into the app.## Get itdiff --git a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.ktindex fdf10e6..7188392 100644--- a/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt+++ b/app/src/main/java/app/tellyscope/data/AdbDeviceSource.kt@@ -130,7 +130,7 @@ class AdbDeviceSource(private val appNames = AppNames(File(appContext.filesDir, "app-names"))private val lists = DeviceLists(File(appContext.filesDir, "lists"))/** `data/`'s launcher, app name and streaming lists; never the user's source. */- private val data = DeviceLists(File(appContext.filesDir, "data"), DATA_BASE)+ private val data = DeviceLists(File(appContext.filesDir, "data"), DATA_BASE, DATA_KEYS)/** [historyKey] → the keep entries of that TV's list, once it has been looked up. */private val keep = ConcurrentHashMap<String, Set<String>>()diff --git a/app/src/main/java/app/tellyscope/data/DeviceLists.kt b/app/src/main/java/app/tellyscope/data/DeviceLists.ktindex 4413a7b..0bd5d2a 100644--- a/app/src/main/java/app/tellyscope/data/DeviceLists.kt+++ b/app/src/main/java/app/tellyscope/data/DeviceLists.kt@@ -106,12 +106,18 @@ fun merge(maker: String, lists: List<DeviceList>): DeviceList = DeviceList(/** A file the index names outside `devices/`, checked against [sha256] like a device file. */data class ListFile(val file: String, val sha256: String)-/** [lists] by name (`launchers`, `labels`, `streaming`, `protected`) and [logos] by logo name; empty on an index without them. */+/**+ * [lists] by name (`launchers`, `labels`, `streaming`, `protected`) and [logos] by logo name; empty on an index without them.+ * [version] goes up with each signed `data/` index. [signed]: a signature on its line 2 verifies against the keys+ * [DeviceLists] was given and its version is no lower than the newest signed one seen, so it is the one Tellyscope published.+ */data class ListIndex(val commit: String?,val devices: List<ListEntry>,val lists: Map<String, ListFile> = emptyMap(),val logos: Map<String, ListFile> = emptyMap(),+ val version: Long? = null,+ val signed: Boolean = false,)data class ListPackage(val pkg: String, val note: String?, val optional: Boolean)@@ -199,6 +205,7 @@ fun parseIndex(text: String): ListIndex? = try {}.orEmpty(),lists = o.files("lists", LIST_FILE),logos = o.files("logos", LOGO_FILE),+ version = o.optLong("version").takeIf { it > 0 },)} catch (_: org.json.JSONException) {null@@ -259,20 +266,24 @@ fun suggest(list: DeviceList, apps: List<AppInfo>, sdk: Int?): List<SuggestedGro* Fetches and caches the index, device files, lists and logos under [dir], from [default] or the* user's own source. A failed fetch falls back to the cache; a file is only used (and cached) when* its sha256 matches the index. Hand picks are remembered per [historyKey]. `data/` ([DATA_BASE])- * is read through one of these too, with its own [dir] and never a source of the user's.+ * is read through one of these too, with its own [dir], never a source of the user's, and [keys] its index+ * must be signed with ([ListIndex.signed], [verified]).*/class DeviceLists(private val dir: File,private val default: String,+ private val keys: List<String>? = null,private val fetch: suspend (String) -> ByteArray = ::download,) {/** The debloat list source, tellyscope-devices unless the user sets their own. [fetch] stays last, so it can trail. */- constructor(dir: File, fetch: suspend (String) -> ByteArray = ::download) : this(dir, LISTS_BASE, fetch)+ constructor(dir: File, fetch: suspend (String) -> ByteArray = ::download) : this(dir, LISTS_BASE, null, fetch)private val lock = Mutex()private var index: ListIndex? = nullprivate val picks = File(dir, "picks.tsv")private val sourceFile = File(dir, "source.txt")+ /** The newest signed [ListIndex.version] seen: an older index, even one signed, is never [ListIndex.signed] again. */+ private val floorFile = File(dir, "version.txt")/** The folder holding `index.json`: one the user set, else [default]. Checked again here, so a stored address that isn't `https` is never used. */val base: String get() = custom()?.let(::normalize) ?: default@@ -316,13 +327,47 @@ class DeviceLists(suspend fun index(): ListIndex? = lock.withLock {index ?: withContext(Dispatchers.IO) {dir.mkdirs()- val cache = File(dir, "index.json")- val text = attempt { fetch(base + "index.json") }?.decodeToString()- text?.let(::parseIndex)?.also { cache.writeText(text); index = it }- ?: cache.takeIf { it.exists() }?.readText()?.let(::parseIndex)+ val bytes = attempt { fetch(base + "index.json") }+ bytes?.let { b -> checked(b)?.also { save(b, it); index = it } } ?: cachedIndex()}}+ /**+ * Whether the index is [ListIndex.signed] and every list it names can be had and matches its sha256, so what+ * is used is what was signed. False offline with nothing cached, and for a source without [keys].+ */+ suspend fun verified(): Boolean {+ val index = index() ?: return false+ return index.signed && index.lists.values.all { file(it.file, it.sha256) != null }+ }++ /** [verified] from the cache alone, for the moment before the network answers. */+ suspend fun cachedVerified(): Boolean = withContext(Dispatchers.IO) {+ val index = cachedIndex() ?: return@withContext false+ index.signed && index.lists.values.all { f -> cached(f.file)?.let { sha256(it) == f.sha256 } == true }+ }++ /** [bytes] read as an index; [ListIndex.signed] when its signature line ([verifyIndex]) passes and the version is no lower than [floor]. */+ private fun checked(bytes: ByteArray): ListIndex? {+ val parsed = parseIndex(bytes.decodeToString()) ?: return null+ val keys = keys ?: return parsed+ val version = parsed.version ?: return parsed+ return parsed.copy(signed = version >= floor() && verifyIndex(bytes, keys))+ }++ /** The cached index, its signature checked again rather than remembered, so an edited cache isn't trusted. */+ private fun cachedIndex(): ListIndex? {+ val bytes = File(dir, "index.json").takeIf { it.exists() }?.readBytes() ?: return null+ return checked(bytes)+ }++ private fun save(bytes: ByteArray, parsed: ListIndex) {+ File(dir, "index.json").writeBytes(bytes)+ if (parsed.signed) parsed.version?.let { floorFile.writeText(it.toString()) }+ }++ private fun floor(): Long = floorFile.takeIf { it.exists() }?.readText()?.trim()?.toLongOrNull() ?: 0+/** The device file for [entry], from cache or the network. Null when the bytes don't match its sha256. */suspend fun list(entry: ListEntry): DeviceList? =file(entry.file, entry.sha256)?.let { parseList(it.decodeToString(), entry.id) }diff --git a/app/src/main/java/app/tellyscope/data/Launchers.kt b/app/src/main/java/app/tellyscope/data/Launchers.ktindex 6bdff71..af82f49 100644--- a/app/src/main/java/app/tellyscope/data/Launchers.kt+++ b/app/src/main/java/app/tellyscope/data/Launchers.kt@@ -122,8 +122,11 @@ data class Shared(val labels: Map<String, String> = emptyMap(),val streaming: List<StreamingService> = emptyList(),val protected: Map<String, ProtectedReason> = emptyMap(),- /** The user's own list these came from ([DeviceLists.base]), or null for the default source. */- val list: String? = null,+ /**+ * `data/`'s address ([DeviceLists.base]) while it fails its check ([DeviceLists.verified]): a bad or missing+ * signature, an older version, or a file that doesn't match the index. Null once it passes.+ */+ val unverified: String? = null,)/**@@ -133,7 +136,8 @@ data class Shared(* launch, then the downloaded one; a list that can't be had keeps what was there. The app bundles* none, so before the first fetch they are empty; a build with `fixtures/` among its Java resources* (the tests) starts from those instead. The protected list goes on to [Protected.extra], on top of- * the built-in one.+ * the built-in one. `data/` that fails its signature check is still used, but [unverified] says so, and+ * nothing installs from it without asking.*/object SharedLists {private val _state = MutableStateFlow(seed())@@ -141,8 +145,8 @@ object SharedLists {val launchers get() = _state.value.launchersval labels get() = _state.value.labelsval streaming get() = _state.value.streaming- /** The user's own list the launchers came from, or null for the default: installing from it asks first. */- val list get() = _state.value.list+ /** `data/`'s address while it fails its check, or null: installing a launcher from it asks first. */+ val unverified get() = _state.value.unverified@Volatile private var data: DeviceLists? = null@Volatile private var source: DeviceLists? = null@@ -152,8 +156,7 @@ object SharedLists {this.data = datasource = listsif (fresh) reset(_state.value.copy(protected = emptyMap()))- _state.update { it.copy(list = lists.custom()?.let { lists.base }) }- apply(data::cachedShared, lists::cachedShared)+ apply(data.cachedVerified(), data::cachedShared, lists::cachedShared)refresh()}@@ -161,14 +164,18 @@ object SharedLists {suspend fun refresh() {val data = data ?: returnval source = source ?: return- apply(data::shared, source::shared)+ apply(data.verified(), data::shared, source::shared)}/** A logo's PNG, at four times its size in dp; null until it can be had. */suspend fun logo(name: String): ByteArray? = source?.logo(name)- /** Launchers, labels and streaming from [data]; only the protected list from [source]. */- private suspend fun apply(data: suspend (String) -> String?, source: suspend (String) -> String?) {+ /**+ * Launchers, labels and streaming from [data]; only the protected list from [source]. [verified] is worked out+ * first and set in the same update, so new launchers never sit behind an old [unverified].+ */+ private suspend fun apply(verified: Boolean, data: suspend (String) -> String?, source: suspend (String) -> String?) {+ val base = this.data?.baseval launchers = data("launchers")?.let(::parseLaunchers)val labels = data("labels")?.let(::parseLabels)val streaming = data("streaming")?.let(::parseStreaming)@@ -179,6 +186,7 @@ object SharedLists {labels = labels?.ifEmpty { null } ?: now.labels,streaming = streaming?.ifEmpty { null } ?: now.streaming,protected = protected?.ifEmpty { null } ?: now.protected,+ unverified = if (verified) null else base,)}Protected.extra = _state.value.protecteddiff --git a/app/src/main/java/app/tellyscope/data/ListSignature.kt b/app/src/main/java/app/tellyscope/data/ListSignature.ktnew file mode 100644index 0000000..02ed7be--- /dev/null+++ b/app/src/main/java/app/tellyscope/data/ListSignature.kt@@ -0,0 +1,77 @@+// SPDX-License-Identifier: GPL-3.0-only++package app.tellyscope.data++import org.json.JSONArray+import org.json.JSONException+import java.security.GeneralSecurityException+import java.security.KeyFactory+import java.security.PublicKey+import java.security.Signature+import java.security.spec.X509EncodedKeySpec+import java.util.Base64++/**+ * The public keys the signatures in `data/index.json` may verify against, base64 SPKI DER of ECDSA P-256 keys, as in+ * `tools/data-keys/`: the one `data/` is signed with, then one kept offline in case it's lost. Built in, never+ * fetched: a `data/` index signed by one of them is the one Tellyscope published.+ */+val DATA_KEYS = listOf(+ // tools/data-keys/primary.pub+ "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE925XkP+cWPVg1oBCHH7Pf2wVX5JEVXn7d4Wr9bRluIDogbmatLa6IgfxrrcgimZHgYew7SLnfPuWXs4om9bSFQ==",+ // tools/data-keys/backup.pub, kept offline for a rotation or a leak+ "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEXaezXF+/UiXq/fGZOL8NYllUzxPyMbBO46pueSEjOIY+KNX19fSDZ0yEqKK+C4eC3YLwan7KlRQSLdziOrFC7g==",+)++/**+ * Whether [index], the bytes of `index.json`, carries a signature by one of [keys]. Line 2 is the signatures,+ * ` "sigs": ["p256:<base64>", …],`, each base64 of a DER ECDSA signature over SHA-256 of the file with that one+ * line cut out: from just after the first newline up to and including the second. The JSON is never parsed and+ * written back, so the bytes checked are the bytes `tools/data.py sign` signed. No `"sigs"` on line 2 is unsigned.+ * Tags other than `p256` are skipped, so a later algorithm can sign alongside; any `p256` entry that verifies+ * against any key passes. A key or signature that can't be read never passes.+ */+fun verifyIndex(index: ByteArray, keys: List<String>): Boolean {+ val first = index.indexOf('\n'.code.toByte()).takeIf { it >= 0 } ?: return false+ val second = (first + 1 until index.size).firstOrNull { index[it] == '\n'.code.toByte() } ?: return false+ val line = SIGS.matchEntire(index.copyOfRange(first + 1, second).decodeToString()) ?: return false+ val ders = try {+ JSONArray(line.groupValues[1]).let { a -> (0 until a.length()).map { a.getString(it) } }+ } catch (_: JSONException) {+ return false+ }.mapNotNull { entry ->+ entry.removePrefix("p256:").takeIf { it != entry }?.let { b64 ->+ try {+ Base64.getDecoder().decode(b64)+ } catch (_: IllegalArgumentException) {+ null+ }+ }+ }+ val signed = index.copyOfRange(0, first + 1) + index.copyOfRange(second + 1, index.size)+ val publicKeys = keys.mapNotNull(::publicKey)+ return ders.any { der ->+ publicKeys.any { key ->+ try {+ Signature.getInstance("SHA256withECDSA").run {+ initVerify(key)+ update(signed)+ verify(der)+ }+ } catch (_: GeneralSecurityException) {+ false+ }+ }+ }+}++/** Line 2 of a signed `index.json`: ` "sigs": [...],`, the list in group 1. */+private val SIGS = Regex("""^ *"sigs": *(\[.*]),$""")++private fun publicKey(b64: String): PublicKey? = try {+ KeyFactory.getInstance("EC").generatePublic(X509EncodedKeySpec(Base64.getDecoder().decode(b64)))+} catch (_: GeneralSecurityException) {+ null+} catch (_: IllegalArgumentException) {+ null+}diff --git a/app/src/main/java/app/tellyscope/ui/Copy.kt b/app/src/main/java/app/tellyscope/ui/Copy.ktindex ff3d146..1d9a769 100644--- a/app/src/main/java/app/tellyscope/ui/Copy.kt+++ b/app/src/main/java/app/tellyscope/ui/Copy.kt@@ -307,12 +307,12 @@ object Copy {val PICK_ANOTHER = UiText(R.string.copy_pick_another)val TRY_DOWNLOAD_AGAIN = UiText(R.string.copy_try_download_again)- /** A launcher from a list the user added: shown, and ticked, before anything installs. */- val OWN_LIST_TITLE = UiText(R.string.copy_own_list_title)- val OWN_LIST_TEXT = UiText(R.string.copy_own_list_text)- val OWN_LIST_LIST = UiText(R.string.copy_own_list_list)- val OWN_LIST_SIGNER = UiText(R.string.copy_own_list_signer)- val OWN_LIST_TRUST = UiText(R.string.copy_own_list_trust)+ /** A launcher from a list that failed its signature check: shown, and ticked, before anything installs. */+ val UNVERIFIED_TITLE = UiText(R.string.copy_unverified_title)+ val UNVERIFIED_TEXT = UiText(R.string.copy_unverified_text)+ val UNVERIFIED_LIST = UiText(R.string.copy_unverified_list)+ val UNVERIFIED_SIGNER = UiText(R.string.copy_unverified_signer)+ val UNVERIFIED_TRUST = UiText(R.string.copy_unverified_trust)val NOT_INSTALLED_TEXT = UiText(R.string.copy_not_installed_text)diff --git a/app/src/main/java/app/tellyscope/ui/LauncherFlowUi.kt b/app/src/main/java/app/tellyscope/ui/LauncherFlowUi.ktindex 12e8812..92b3cab 100644--- a/app/src/main/java/app/tellyscope/ui/LauncherFlowUi.kt+++ b/app/src/main/java/app/tellyscope/ui/LauncherFlowUi.kt@@ -151,7 +151,7 @@ data class LauncherActions(val later: () -> Unit = {},/** Fire OS: Install the launcher, which reads its latest release for the confirm dialog. Try again does the same. */val fireCheck: (String) -> Unit = {},- /** The tick on a launcher from the user's own list. */+ /** The tick on a launcher from a list that failed its check. */val fireTrust: (Boolean) -> Unit = {},/** Fire OS: Download and install on the confirm step. */val fireInstall: () -> Unit = {},@@ -417,7 +417,7 @@ private fun FirePick(l: Recommended?) {* went wrong. Couldn't download offers the release page and Pick the downloaded file, checked the same way.* After Download directly ([FireInstall.store]) the confirm is a warning, and it and a wrong signature offer* the Play Store instead.- * From the user's own list ([FireInstall.list]) each step that can install it opens on [OwnListCard].+ * While the launcher list fails its check ([FireInstall.list]) each step that can install it opens on [UnverifiedCard].*/@OptIn(ExperimentalMaterial3ExpressiveApi::class)@Composable@@ -430,8 +430,8 @@ private fun FireBody(f: FireInstall, pkg: String, device: Device, actions: Launcval release = f.releaseval openPage = { (release?.page ?: releases?.let { "$it/latest" })?.let(uri::openUri) ?: Unit }val source = releases?.removePrefix("https://")?.removeSuffix("/releases")- val own = f.list?.takeIf { f.step in OWN_LIST_STEPS }- if (own != null) OwnListCard(own, l?.launcher?.signers.orEmpty())+ val own = f.list?.takeIf { f.step in UNVERIFIED_STEPS }+ if (own != null) UnverifiedCard(own, l?.launcher?.signers.orEmpty())when (f.step) {null, FireInstall.Step.Checking, FireInstall.Step.Confirm -> if (f.store) {WarningBadge()@@ -481,8 +481,8 @@ private fun FireBody(f: FireInstall, pkg: String, device: Device, actions: Launc}/**- * Download it in the browser, then pick it: after Couldn't download. From the user's own list,- * picking waits for the tick ([TrustRow]).+ * Download it in the browser, then pick it: after Couldn't download. While the list fails its check, picking waits+ * for the tick ([TrustRow]).*/@Composableprivate fun Yourself(f: FireInstall, label: String, source: String?, openPage: () -> Unit, actions: LauncherActions) {@@ -504,7 +504,7 @@ private fun Yourself(f: FireInstall, label: String, source: String?, openPage: (/*** The bottom of each Fire OS step, for [pkg]: full width, so the confirm reads the same as Download directly's.- * From the user's own list, the download waits for the tick ([TrustRow]).+ * While the list fails its check, the download waits for the tick ([TrustRow]).*/@Composableprivate fun FireButtons(f: FireInstall, pkg: String, actions: LauncherActions, modifier: Modifier) {@@ -681,42 +681,42 @@ private fun WarningBadge() {}}-/** The steps that can still download or pick the APK, which [OwnListCard] opens. */-private val OWN_LIST_STEPS = setOf(null, FireInstall.Step.Checking, FireInstall.Step.Confirm, FireInstall.Step.NoDownload)+/** The steps that can still download or pick the APK, which [UnverifiedCard] opens. */+private val UNVERIFIED_STEPS = setOf(null, FireInstall.Step.Checking, FireInstall.Step.Confirm, FireInstall.Step.NoDownload)/**- * A launcher from the user's own list ([FireInstall.list]): the list's address and the signer it names, since all- * Tellyscope can check is that the APK matches them. In the error colours, above everything else on the step.+ * A launcher from a list that failed its check ([FireInstall.list]): the list's address and the signer it names,+ * since all Tellyscope can check is that the APK matches them. In the error colours, above everything else on the step.*/@Composable-private fun OwnListCard(list: String, signers: Set<String>) {+private fun UnverifiedCard(list: String, signers: Set<String>) {val c = MaterialTheme.colorSchemeSurface(shape = MaterialTheme.shapes.large, color = c.errorContainer, contentColor = c.onErrorContainer, modifier = Modifier.fillMaxWidth()) {Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {Row(verticalAlignment = Alignment.CenterVertically) {Icon(Icons.Default.Warning, null, Modifier.size(20.dp))Spacer(Modifier.width(8.dp))- Text(Copy.OWN_LIST_TITLE.resolve(), style = MaterialTheme.typography.titleSmall)+ Text(Copy.UNVERIFIED_TITLE.resolve(), style = MaterialTheme.typography.titleSmall)}- Text(Copy.OWN_LIST_TEXT.resolve(), style = MaterialTheme.typography.bodyMedium)+ Text(Copy.UNVERIFIED_TEXT.resolve(), style = MaterialTheme.typography.bodyMedium)Column {- Text(Copy.OWN_LIST_LIST.resolve(), style = MaterialTheme.typography.labelMedium)+ Text(Copy.UNVERIFIED_LIST.resolve(), style = MaterialTheme.typography.labelMedium)Text(sourceName(list), style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.Medium)}Column {- Text(Copy.OWN_LIST_SIGNER.resolve(), style = MaterialTheme.typography.labelMedium)+ Text(Copy.UNVERIFIED_SIGNER.resolve(), style = MaterialTheme.typography.labelMedium)signers.forEach { Text(groupedHex(it), style = MaterialTheme.typography.bodySmall, fontFamily = FontFamily.Monospace) }}}}}-/** A SHA-256 as [OwnListCard] shows it: groups of eight, four to a line. */+/** A SHA-256 as [UnverifiedCard] shows it: groups of eight, four to a line. */internal fun groupedHex(sha: String) = sha.chunked(8).chunked(4).joinToString("\n") { it.joinToString(" ") }/**- * I trust this list and its signer: the extra step before a launcher from the user's own list downloads or is- * picked. Keyboard and D-pad focus start here rather than on the button, which needs a press of its own.+ * I trust this list and its signer: the extra step before a launcher from a list that failed its check downloads or+ * is picked. Keyboard and D-pad focus start here rather than on the button, which needs a press of its own.*/@Composableprivate fun TrustRow(trusted: Boolean, onTrust: (Boolean) -> Unit) {@@ -739,7 +739,7 @@ private fun TrustRow(trusted: Boolean, onTrust: (Boolean) -> Unit) {) {Checkbox(trusted, onCheckedChange = null, Modifier.padding(8.dp))Spacer(Modifier.width(4.dp))- Text(Copy.OWN_LIST_TRUST.resolve(), style = MaterialTheme.typography.bodyLarge)+ Text(Copy.UNVERIFIED_TRUST.resolve(), style = MaterialTheme.typography.bodyLarge)}}}diff --git a/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt b/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.ktindex 7bf3fcf..12cbcab 100644--- a/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt+++ b/app/src/main/java/app/tellyscope/ui/TellyscopeViewModel.kt@@ -217,15 +217,15 @@ data class FireInstall(/** The APK's size once it's downloaded or picked, for the steps' first line. */val size: Long? = null,/**- * The user's own list the launcher comes from ([SharedLists.list]), null for the default source. Then nothing- * downloads or installs until the user ticks that they trust it and its signer ([trusted]).+ * `data/`'s address while it fails its check ([SharedLists.unverified]), null once it passes. Then nothing+ * downloads or installs until the user ticks that they trust the list and its signer ([trusted]).*/val list: String? = null,val trusted: Boolean = false,) {enum class Step { Checking, Confirm, Downloading, Reading, Installing, WrongApk, NoDownload, Refused }- /** From the user's own list and not yet trusted: Download and install and Pick the downloaded file wait. */+ /** From a list that failed its check and not yet trusted: Download and install and Pick the downloaded file wait. */val gated get() = list != null && !trusted}@@ -429,8 +429,8 @@ class TellyscopeViewModel(private val appFacts: AppFacts = AppFacts("unknown", "unknown phone"),/** A launcher's APK from its developer's GitHub, for Fire OS. */private val launcherDownload: LauncherDownload? = null,- /** The user's own list the launchers came from, or null for the default source. */- private val ownList: () -> String? = { SharedLists.list },+ /** `data/`'s address while the launcher list fails its check, or null once it passes. */+ private val unverified: () -> String? = { SharedLists.unverified },) : ViewModel() {private val _state = MutableStateFlow(UiState(now = clock()))@@ -958,7 +958,7 @@ class TellyscopeViewModel(val id = _state.value.selectedId ?: returnval fire = fireLauncher()?.takeIf { _state.value.selected?.let { d -> fireInstall(d, _state.value.device.apps) } == true }if (fire != null) {- updateDevice(id) { it.copy(launcher = LauncherFlow(pkg = fire.pkg, fire = FireInstall(list = ownList()))) }+ updateDevice(id) { it.copy(launcher = LauncherFlow(pkg = fire.pkg, fire = FireInstall(list = unverified()))) }return}if (RECOMMENDED.isEmpty()) {@@ -987,7 +987,7 @@ class TellyscopeViewModel(val download = launcherDownload ?: returnval launcher = apkLauncher(pkg) ?: returnval store = _state.value.device.launcher?.let { it.fire?.store ?: true } ?: return- val list = ownList()+ val list = unverified()launcherJob?.cancel()updateDevice(id) { d -> d.copy(launcher = d.launcher?.copy(pkg = pkg, fire = FireInstall(FireInstall.Step.Checking, store = store, list = list))) }launcherJob = viewModelScope.launch {@@ -1005,18 +1005,18 @@ class TellyscopeViewModel(}/**- * The source changed since the flow read it ([FireInstall.list]), so the signers no longer match what the user- * saw or ticked: back to Checking against the new one, and nothing installs.+ * The list's check changed since the flow read it ([FireInstall.list]), so the signers may not be what the user+ * saw or ticked: back to Checking against the list as it is now, and nothing installs.*/private fun listChanged(id: String, flow: LauncherFlow): Boolean {val fire = flow.fire ?: return false- val list = ownList()+ val list = unverified()if (list == fire.list) return falsecheckLauncherApk(flow.pkg)return true}- /** The tick on a launcher from the user's own list ([FireInstall.list]): until it's on, nothing downloads or installs. */+ /** The tick on a launcher from a list that failed its check ([FireInstall.list]): until it's on, nothing downloads or installs. */fun trustLauncherList(on: Boolean) {val id = _state.value.selectedId ?: returnsetFire(id) { if (it.list != null) it.copy(trusted = on) else it }diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xmlindex 267ba5f..9e89d6d 100644--- a/app/src/main/res/values-es/strings.xml+++ b/app/src/main/res/values-es/strings.xml@@ -153,11 +153,11 @@<string name="copy_pick_downloaded">Elegir el archivo descargado</string><string name="copy_pick_another">Elegir otro archivo</string><string name="copy_try_download_again">Volver a descargar</string>- <string name="copy_own_list_title">De una lista que añadiste</string>- <string name="copy_own_list_text">Tellyscope no puede responder por esta app. Solo comprueba que el archivo coincide con esta lista, y quien gestiona la lista eligió la firma.</string>- <string name="copy_own_list_list">Lista</string>- <string name="copy_own_list_signer">Firma (SHA-256)</string>- <string name="copy_own_list_trust">Confío en esta lista y en su firma</string>+ <string name="copy_unverified_title">No se pudo verificar la lista de launchers</string>+ <string name="copy_unverified_text">Tellyscope no pudo confirmar que esta es la lista que publicó. Si la lista cambió en los últimos minutos, vuelve a intentarlo más tarde. Instala ahora solo si confías en la lista y en su firma.</string>+ <string name="copy_unverified_list">Lista</string>+ <string name="copy_unverified_signer">Firma (SHA-256)</string>+ <string name="copy_unverified_trust">Confío en esta lista y en su firma</string><string name="copy_service_off_text">El servicio de accesibilidad de %1$s está desactivado, así que la TV puede recuperar Inicio.</string><string name="copy_open_again">Volver a abrir</string><string name="copy_undo">Deshacer</string>diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xmlindex 944b86d..a69f1d6 100644--- a/app/src/main/res/values-hi/strings.xml+++ b/app/src/main/res/values-hi/strings.xml@@ -153,11 +153,11 @@<string name="copy_pick_downloaded">डाउनलोड की गई फ़ाइल चुनें</string><string name="copy_pick_another">दूसरी फ़ाइल चुनें</string><string name="copy_try_download_again">फिर से डाउनलोड करें</string>- <string name="copy_own_list_title">आपकी जोड़ी हुई सूची से</string>- <string name="copy_own_list_text">Tellyscope इस ऐप की गारंटी नहीं दे सकता। यह सिर्फ़ जांचता है कि फ़ाइल इस सूची से मेल खाती है, और सिग्नेचर उसी ने चुना है जो यह सूची चलाता है।</string>- <string name="copy_own_list_list">सूची</string>- <string name="copy_own_list_signer">सिग्नेचर (SHA-256)</string>- <string name="copy_own_list_trust">मुझे इस सूची और इसके सिग्नेचर पर भरोसा है</string>+ <string name="copy_unverified_title">लॉन्चर सूची की पुष्टि नहीं हो सकी</string>+ <string name="copy_unverified_text">Tellyscope पुष्टि नहीं कर सका कि यह वही सूची है जो उसने प्रकाशित की थी। अगर सूची पिछले कुछ मिनटों में बदली है, तो थोड़ी देर बाद फिर कोशिश करें। अभी इंस्टॉल तभी करें जब आपको इस सूची और इसके सिग्नेचर पर भरोसा हो।</string>+ <string name="copy_unverified_list">सूची</string>+ <string name="copy_unverified_signer">सिग्नेचर (SHA-256)</string>+ <string name="copy_unverified_trust">मुझे इस सूची और इसके सिग्नेचर पर भरोसा है</string><string name="copy_service_off_text">%1$s की सुलभता सेवा बंद है, इसलिए TV Home को वापस ले सकता है।</string><string name="copy_open_again">फिर से खोलें</string><string name="copy_undo">पहले जैसा करें</string>diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xmlindex eae6d6d..8b94166 100644--- a/app/src/main/res/values-ja/strings.xml+++ b/app/src/main/res/values-ja/strings.xml@@ -153,11 +153,11 @@<string name="copy_pick_downloaded">ダウンロードしたファイルを選択</string><string name="copy_pick_another">別のファイルを選択</string><string name="copy_try_download_again">もう一度ダウンロード</string>- <string name="copy_own_list_title">追加したリストから</string>- <string name="copy_own_list_text">Tellyscope はこのアプリを保証できません。ファイルがこのリストと一致することだけを確認します。署名はリストの管理者が選んだものです。</string>- <string name="copy_own_list_list">リスト</string>- <string name="copy_own_list_signer">署名 (SHA-256)</string>- <string name="copy_own_list_trust">このリストとその署名を信頼する</string>+ <string name="copy_unverified_title">ランチャーのリストを確認できませんでした</string>+ <string name="copy_unverified_text">Tellyscope が公開したリストであることを確認できませんでした。数分以内にリストが変更された場合は、しばらくしてからもう一度お試しください。リストとその署名を信頼できる場合のみ、今すぐインストールしてください。</string>+ <string name="copy_unverified_list">リスト</string>+ <string name="copy_unverified_signer">署名 (SHA-256)</string>+ <string name="copy_unverified_trust">このリストとその署名を信頼する</string><string name="copy_service_off_text">%1$s のユーザー補助サービスがオフのため、テレビがホームを取り戻す可能性があります。</string><string name="copy_open_again">もう一度開く</string><string name="copy_undo">元に戻す</string>diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xmlindex cb6fd57..9b65e84 100644--- a/app/src/main/res/values-ru/strings.xml+++ b/app/src/main/res/values-ru/strings.xml@@ -153,11 +153,11 @@<string name="copy_pick_downloaded">Выбрать скачанный файл</string><string name="copy_pick_another">Выбрать другой файл</string><string name="copy_try_download_again">Скачать снова</string>- <string name="copy_own_list_title">Из списка, который вы добавили</string>- <string name="copy_own_list_text">Tellyscope не может ручаться за это приложение. Он лишь проверяет, что файл совпадает с этим списком, а подпись выбрал тот, кто ведёт список.</string>- <string name="copy_own_list_list">Список</string>- <string name="copy_own_list_signer">Подпись (SHA-256)</string>- <string name="copy_own_list_trust">Я доверяю этому списку и его подписи</string>+ <string name="copy_unverified_title">Не удалось проверить список лаунчеров</string>+ <string name="copy_unverified_text">Tellyscope не смог подтвердить, что это опубликованный им список. Если список изменился в последние несколько минут, попробуйте позже. Устанавливайте сейчас, только если доверяете списку и его подписи.</string>+ <string name="copy_unverified_list">Список</string>+ <string name="copy_unverified_signer">Подпись (SHA-256)</string>+ <string name="copy_unverified_trust">Я доверяю этому списку и его подписи</string><string name="copy_service_off_text">Служба специальных возможностей %1$s отключена, поэтому телевизор может вернуть свой главный экран.</string><string name="copy_open_again">Открыть снова</string><string name="copy_undo">Отменить</string>diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xmlindex 29dc5b8..9486847 100644--- a/app/src/main/res/values-zh-rCN/strings.xml+++ b/app/src/main/res/values-zh-rCN/strings.xml@@ -153,11 +153,11 @@<string name="copy_pick_downloaded">选择已下载的文件</string><string name="copy_pick_another">选择其他文件</string><string name="copy_try_download_again">重新下载</string>- <string name="copy_own_list_title">来自你添加的列表</string>- <string name="copy_own_list_text">Tellyscope 无法为此应用担保。它只检查文件是否与此列表一致,签名由维护该列表的人选定。</string>- <string name="copy_own_list_list">列表</string>- <string name="copy_own_list_signer">签名 (SHA-256)</string>- <string name="copy_own_list_trust">我信任此列表及其签名</string>+ <string name="copy_unverified_title">无法验证启动器列表</string>+ <string name="copy_unverified_text">Tellyscope 无法确认这是它发布的列表。如果列表在几分钟内刚有更改,请稍后再试。只有在你信任此列表及其签名时才立即安装。</string>+ <string name="copy_unverified_list">列表</string>+ <string name="copy_unverified_signer">签名 (SHA-256)</string>+ <string name="copy_unverified_trust">我信任此列表及其签名</string><string name="copy_service_off_text">%1$s 的无障碍服务已关闭,因此电视可能会抢回主屏幕。</string><string name="copy_open_again">再次打开</string><string name="copy_undo">撤消</string>diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xmlindex 81d5df8..b1c93fe 100644--- a/app/src/main/res/values/strings.xml+++ b/app/src/main/res/values/strings.xml@@ -194,12 +194,12 @@<string name="copy_pick_downloaded">Pick the downloaded file</string><string name="copy_pick_another">Pick another file</string><string name="copy_try_download_again">Try download again</string>- <!-- A launcher from a list the user added, not the default: confirmed before anything installs -->- <string name="copy_own_list_title">From a list you added</string>- <string name="copy_own_list_text">Tellyscope can\'t vouch for this app. It only checks that the file matches this list, and whoever runs the list chose the signer.</string>- <string name="copy_own_list_list">List</string>- <string name="copy_own_list_signer">Signer (SHA-256)</string>- <string name="copy_own_list_trust">I trust this list and its signer</string>+ <!-- The launcher list from data/ failed its signature or checksum check: shown, and ticked, before anything installs -->+ <string name="copy_unverified_title">Couldn\'t verify the launcher list</string>+ <string name="copy_unverified_text">Tellyscope couldn\'t confirm this is the list it published. If the list changed in the last few minutes, try again later. Install now only if you trust the list and its signer.</string>+ <string name="copy_unverified_list">List</string>+ <string name="copy_unverified_signer">Signer (SHA-256)</string>+ <string name="copy_unverified_trust">I trust this list and its signer</string><string name="copy_service_off_text">%1$s\'s accessibility service is off, so the TV can take Home back.</string><string name="copy_open_again">Open again</string>diff --git a/app/src/test/java/app/tellyscope/DataSignatureTest.kt b/app/src/test/java/app/tellyscope/DataSignatureTest.ktnew file mode 100644index 0000000..93e264d--- /dev/null+++ b/app/src/test/java/app/tellyscope/DataSignatureTest.kt@@ -0,0 +1,193 @@+// SPDX-License-Identifier: GPL-3.0-only++package app.tellyscope++import app.tellyscope.data.DATA_BASE+import app.tellyscope.data.DATA_KEYS+import app.tellyscope.data.DeviceLists+import app.tellyscope.data.LISTS_BASE+import app.tellyscope.data.SharedLists+import app.tellyscope.data.verifyIndex+import kotlinx.coroutines.test.runTest+import org.json.JSONObject+import org.junit.After+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Assume.assumeTrue+import org.junit.Rule+import org.junit.Test+import org.junit.rules.TemporaryFolder+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import java.io.File+import java.io.IOException+import java.security.KeyPair+import java.security.KeyPairGenerator+import java.security.MessageDigest+import java.security.Signature+import java.security.spec.ECGenParameterSpec+import java.util.Base64++/**+ * `data/index.json`'s signatures as the app checks them: line 2 holds them, each ECDSA P-256 over the exact bytes of+ * the file with that line cut out, against built-in keys, never an older version than the newest signed one seen, and every file matching the index. Keys are made+ * here, as `tools/data.py sign` would use them. org.json is Android's, so this runs under Robolectric.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class DataSignatureTest {+ @get:Rule val tmp = TemporaryFolder()++ @After fun reseed() = SharedLists.reseed()++ private fun keyPair(): KeyPair = KeyPairGenerator.getInstance("EC").apply { initialize(ECGenParameterSpec("secp256r1")) }.generateKeyPair()+ private val primary = keyPair()+ private val backup = keyPair()+ private val keys = listOf(primary, backup).map { Base64.getEncoder().encodeToString(it.public.encoded) }++ private fun sha256(b: ByteArray) = MessageDigest.getInstance("SHA-256").digest(b).joinToString("") { "%02x".format(it) }++ /** A `p256:` entry for line 2: base64 of the DER signature [key] makes over [unsigned]. */+ private fun p256(unsigned: ByteArray, key: KeyPair = primary): String =+ "p256:" + Base64.getEncoder().encodeToString(Signature.getInstance("SHA256withECDSA").run { initSign(key.private); update(unsigned); sign() })++ /** As `tools/data.py sign` writes it: [entries] on line 2, right after the `{`. */+ private fun withSigs(unsigned: ByteArray, vararg entries: String): ByteArray {+ val text = unsigned.decodeToString()+ val sigs = entries.joinToString(", ") { "\"$it\"" }+ return text.replaceFirst("{\n", "{\n \"sigs\": [$sigs],\n").toByteArray()+ }++ private val launchers = """{"schema":1,"launchers":[{"package":"com.good.home","name":"Good","about":"x"}]}""".toByteArray()++ /** As `tools/data.py index` writes it, unsigned. */+ private fun index(version: Long, file: ByteArray = launchers) = """+ |{+ | "schema": 1,+ | "version": $version,+ | "lists": {+ | "launchers": {"file": "launchers.json", "sha256": "${sha256(file)}"}+ | }+ |}+ |""".trimMargin().toByteArray()++ /** `data/` serving [files] at [DATA_BASE]; change them between calls to change what it serves. */+ private class Served(var files: Map<String, ByteArray>) {+ val fetch: suspend (String) -> ByteArray = { url -> files[url.removePrefix(DATA_BASE)] ?: throw IOException("404 $url") }+ }++ private fun signed(version: Long = 2026110301, key: KeyPair = primary): Map<String, ByteArray> =+ serving(index(version).let { withSigs(it, p256(it, key)) })++ private fun serving(index: ByteArray) = mapOf("index.json" to index, "launchers.json" to launchers)++ private fun lists(dir: File, served: Served) = DeviceLists(dir, DATA_BASE, keys, served.fetch)++ @Test fun signedByThePrimaryOrTheBackupKeyPasses() = runTest {+ assertTrue(lists(tmp.newFolder(), Served(signed())).verified())+ assertTrue(lists(tmp.newFolder(), Served(signed(key = backup))).verified())+ }++ @Test fun anotherKeyANoSignatureOrAnEditedIndexFails() = runTest {+ assertFalse(lists(tmp.newFolder(), Served(signed(key = keyPair()))).verified())+ assertFalse(lists(tmp.newFolder(), Served(serving(index(2026110301)))).verified())+ val edited = signed().let { it + ("index.json" to (it.getValue("index.json").decodeToString() + " ").toByteArray()) }+ assertFalse(lists(tmp.newFolder(), Served(edited)).verified())+ assertFalse(verifyIndex(withSigs(index(1), "p256:not base64!"), keys))+ assertFalse(verifyIndex(withSigs(index(1)), keys))+ }++ /** Same JSON, other bytes: an editor's reformat means signing again, never a pass. */+ @Test fun aReformattedFileFails() = runTest {+ val text = signed().getValue("index.json").decodeToString()+ val spaced = text.replace("\"version\": ", "\"version\": ")+ assertFalse(lists(tmp.newFolder(), Served(serving(spaced.toByteArray()))).verified())+ // Re-serialised, "sigs" isn't on its own line 2 any more: unsigned.+ val reserialised = JSONObject(text).toString(2).toByteArray()+ assertFalse(lists(tmp.newFolder(), Served(serving(reserialised))).verified())+ }++ /** A tag the app doesn't know is skipped, so a later algorithm can sign alongside `p256`, but never stands in for it. */+ @Test fun anUnknownTagIsSkipped() = runTest {+ val index = index(2026110301)+ val sig = p256(index).removePrefix("p256:")+ assertTrue(lists(tmp.newFolder(), Served(serving(withSigs(index, "ed25519:AAAA", "p256:$sig")))).verified())+ assertFalse(lists(tmp.newFolder(), Served(serving(withSigs(index, "ed25519:$sig")))).verified())+ assertFalse(lists(tmp.newFolder(), Served(serving(withSigs(index, sig)))).verified())+ }++ /** Signed twice, as while a key is rotated: one entry verifying is enough, whichever it is. */+ @Test fun aSecondValidSignaturePasses() = runTest {+ val index = index(2026110301)+ assertTrue(lists(tmp.newFolder(), Served(serving(withSigs(index, p256(index), p256(index, backup))))).verified())+ assertTrue(lists(tmp.newFolder(), Served(serving(withSigs(index, p256(index, keyPair()), p256(index, backup))))).verified())+ assertFalse(lists(tmp.newFolder(), Served(serving(withSigs(index, p256(index, keyPair()), p256(index, keyPair()))))).verified())+ }++ /** Signed, but not the bytes it says: the index names one launchers.json and another one is served. */+ @Test fun aFileThatDoesNotMatchTheIndexFails() = runTest {+ val other = """{"schema":1,"launchers":[{"package":"com.evil.home","name":"Evil","about":"x"}]}""".toByteArray()+ assertFalse(lists(tmp.newFolder(), Served(signed() + ("launchers.json" to other))).verified())+ }++ @Test fun anOlderVersionFailsEvenSigned() = runTest {+ val dir = tmp.newFolder()+ assertTrue(lists(dir, Served(signed(version = 2026110302))).verified())+ // A new process, as after a restart: the older index is fetched and signed, but the newer one was seen.+ val old = lists(dir, Served(signed(version = 2026110301)))+ assertEquals(2026110301L, old.index()?.version)+ assertFalse(old.verified())+ assertTrue(lists(dir, Served(signed(version = 2026110302))).verified())+ }++ @Test fun offlineTheCacheIsCheckedAgain() = runTest {+ val dir = tmp.newFolder()+ assertTrue(lists(dir, Served(signed())).verified())+ val offline = Served(emptyMap())+ assertTrue(lists(dir, offline).cachedVerified())+ assertTrue(lists(dir, offline).verified())++ File(dir, "launchers.json").writeText("""{"schema":1,"launchers":[]}""")+ assertFalse(lists(dir, offline).cachedVerified())+ File(dir, "index.json").appendText(" ")+ assertFalse(lists(dir, offline).cachedVerified())+ }++ /** The list is still used when it fails, so the card can show it, but [SharedLists.unverified] says it failed. */+ @Test fun sharedListsSaysWhenDataFailsItsCheck() = runTest {+ val served = Served(serving(index(2026110301)))+ val none = DeviceLists(tmp.newFolder()) { throw IOException("offline $it") }+ SharedLists.load(lists(tmp.newFolder(), served), none, fresh = true)+ assertEquals(listOf("com.good.home"), SharedLists.launchers.map { it.pkg })+ assertEquals(DATA_BASE, SharedLists.unverified)++ SharedLists.load(lists(tmp.newFolder(), Served(signed())), none, fresh = true)+ assertNull(SharedLists.unverified)+ }++ /**+ * The app and the Data check trust the same keys: [DATA_KEYS] is every key in the `.pub` files in+ * `tools/data-keys/`, read as `tools/data.py` reads them (`#` lines are comments, a file with no key is a+ * placeholder). Skipped until `tools/data.py` is in the repo. Not written as a glob: Kotlin nests block+ * comments, so a slash-star inside this one would leave it unclosed.+ */+ @Test fun theBuiltInKeysAreToolsDataKeys() {+ assumeTrue("tools/data.py isn't in the repo yet", File("../tools/data.py").exists())+ val files = File("../tools/data-keys").listFiles { f -> f.name.endsWith(".pub") }.orEmpty().sortedBy { it.name }+ val keys = files.mapNotNull { f ->+ f.readLines().map { it.trim() }.filter { it.isNotEmpty() && !it.startsWith("#") }.joinToString("").ifEmpty { null }+ }+ assertTrue("tools/data-keys/ has no key", keys.isNotEmpty())+ assertEquals(keys.toSet(), DATA_KEYS.toSet())+ }++ /** The list source the user can change is never signed, so it never needs to be. */+ @Test fun theDebloatListSourceHasNoKeys() = runTest {+ val index = """{"schema":1,"devices":[]}""".toByteArray()+ val lists = DeviceLists(tmp.newFolder()) { url -> if (url == LISTS_BASE + "index.json") index else throw IOException("404 $url") }+ assertFalse(lists.index()!!.signed)+ }+}diff --git a/app/src/test/java/app/tellyscope/FireOsTest.kt b/app/src/test/java/app/tellyscope/FireOsTest.ktindex 3b757d6..99ce443 100644--- a/app/src/test/java/app/tellyscope/FireOsTest.kt+++ b/app/src/test/java/app/tellyscope/FireOsTest.kt@@ -85,7 +85,7 @@ private const val RELEASES = "https://github.com/spocky/miproja1/releases"private val projectivy get() = RECOMMENDED.first { it.pkg == PROJECTIVY }.launcher/** A list the user added in place of the default source. */-private const val OWN_LIST = "https://example.org/tv-lists/"+private const val UNVERIFIED = "https://raw.githubusercontent.com/example/tellyscope/main/data/"private const val TAG = "4.72"private const val PAGE = "https://github.com/spocky/miproja1/releases/tag/$TAG"@@ -146,8 +146,8 @@ class FireOsTest {private var source = FireTv()private val download = FakeDownload()private var vm: TellyscopeViewModel? = null- /** The source as the app reads it now: a test switches it mid-flow. */- private var ownList: String? = null+ /** The launcher list's address while it fails its check, as the app reads it now: a test changes it mid-flow. */+ private var unverified: String? = null@Before fun setUp() = Dispatchers.setMain(dispatcher)@@ -239,10 +239,10 @@ class FireOsTest {assertFalse(projectivy.copy(signers = emptySet()).accepts(PROJECTIVY, setOf(SIGNER)))}- /** [list]: the user's own list. */+ /** [list]: the launcher list's address, as one that failed its check. */private fun TestScope.opened(list: String? = null): TellyscopeViewModel {- ownList = list- val v = TellyscopeViewModel(source, clock = { 0L }, launcherDownload = download, ownList = { ownList })+ unverified = list+ val v = TellyscopeViewModel(source, clock = { 0L }, launcherDownload = download, unverified = { unverified })vm = vrunCurrent()v.openLauncherFlow()@@ -357,14 +357,14 @@ class FireOsTest {assertNull(v.state.value.device.launcher?.fire?.step)}- @Test fun fromTheUsersOwnListNothingDownloadsUntilTheyTrustIt() = with(test) {- val v = opened(list = OWN_LIST)- assertEquals(OWN_LIST, v.state.value.device.launcher?.fire?.list)+ @Test fun fromAnUnverifiedListNothingDownloadsUntilTheyTrustIt() = with(test) {+ val v = opened(list = UNVERIFIED)+ assertEquals(UNVERIFIED, v.state.value.device.launcher?.fire?.list)v.checkLauncherApk(PROJECTIVY)runCurrent()val confirm = v.state.value.device.launcher?.fireassertEquals(FireInstall.Step.Confirm, confirm?.step)- assertEquals(OWN_LIST, confirm?.list)+ assertEquals(UNVERIFIED, confirm?.list)assertTrue(confirm!!.gated)v.installLauncherApk()@@ -378,9 +378,9 @@ class FireOsTest {assertEquals(listOf(PROJECTIVY), source.installs.map { it.packageName })}- @Test fun fromTheUsersOwnListDownloadDirectlyWaitsForTheTickToo() = with(test) {+ @Test fun fromAnUnverifiedListDownloadDirectlyWaitsForTheTickToo() = with(test) {source = FireTv(androidTv, listOf(store, tvHome))- val v = opened(list = OWN_LIST)+ val v = opened(list = UNVERIFIED)v.checkLauncherApk(PROJECTIVY)runCurrent()assertEquals(true, v.state.value.device.launcher?.fire?.gated)@@ -393,8 +393,8 @@ class FireOsTest {assertEquals(1, download.fetched)}- @Test fun fromTheUsersOwnListThePickWaitsForTheTick() = with(test) {- val v = couldntDownload(list = OWN_LIST)+ @Test fun fromAnUnverifiedListThePickWaitsForTheTick() = with(test) {+ val v = couldntDownload(list = UNVERIFIED)v.pickedLauncherApk(Uri.parse("content://downloads/1"))runCurrent()assertTrue(source.installs.isEmpty())@@ -407,7 +407,7 @@ class FireOsTest {}@Test fun dismissingAWrongPickAsksForTheTickAgain() = with(test) {- val v = couldntDownload(list = OWN_LIST)+ val v = couldntDownload(list = UNVERIFIED)v.trustLauncherList(true)download.signedByDeveloper = falsev.pickedLauncherApk(Uri.parse("content://downloads/1"))@@ -416,29 +416,29 @@ class FireOsTest {v.dismissLauncherApk()val fire = v.state.value.device.launcher?.fire- assertEquals(OWN_LIST, fire?.list)+ assertEquals(UNVERIFIED, fire?.list)assertEquals(true, fire?.gated)}- @Test fun switchingToTheirOwnListUnderConfirmChecksAgainFirst() = with(test) {+ @Test fun failingTheCheckUnderConfirmChecksAgainFirst() = with(test) {val v = opened()v.checkLauncherApk(PROJECTIVY)runCurrent()assertEquals(false, v.state.value.device.launcher?.fire?.gated)- ownList = OWN_LIST+ unverified = UNVERIFIEDv.installLauncherApk()runCurrent()assertEquals(0, download.fetched)val fire = v.state.value.device.launcher?.fireassertEquals(FireInstall.Step.Confirm, fire?.step)- assertEquals(OWN_LIST, fire?.list)+ assertEquals(UNVERIFIED, fire?.list)assertEquals(true, fire?.gated)}- @Test fun switchingToTheirOwnListAfterCouldntDownloadGatesThePick() = with(test) {+ @Test fun failingTheCheckAfterCouldntDownloadGatesThePick() = with(test) {val v = couldntDownload()- ownList = OWN_LIST+ unverified = UNVERIFIEDv.pickedLauncherApk(Uri.parse("content://downloads/1"))runCurrent()assertTrue(source.installs.isEmpty())diff --git a/app/src/test/java/app/tellyscope/ScreenshotTest.kt b/app/src/test/java/app/tellyscope/ScreenshotTest.ktindex 104a22b..560dc87 100644--- a/app/src/test/java/app/tellyscope/ScreenshotTest.kt+++ b/app/src/test/java/app/tellyscope/ScreenshotTest.kt@@ -1266,7 +1266,7 @@ class ScreenshotTest {runBlocking {val online = DeviceLists(dir)if (online.index() != null) names.forEach { online.logo(it) }- SharedLists.load(DeviceLists(none, DATA_BASE, offline), DeviceLists(dir, offline))+ SharedLists.load(DeviceLists(none, DATA_BASE, fetch = offline), DeviceLists(dir, offline))}try { body() } finally {SharedLists.reseed()