From 6e41db2a7407e03ad50aed8b9be18989e5eddb83 Mon Sep 17 00:00:00 2001 From: Meghdad <61308304+MeghdadFadaee@users.noreply.github.com> Date: Thu, 15 Oct 2026 19:50:10 +0330 Subject: [PATCH] feat: simplify receiving and remove arbitrary limits - Use fixed port 8787 and reconnect automatically after Wi-Fi loss - Remove session expiry, APK expiry, size caps, and upload deadlines - Replace manual keys with watch-approved browser access - Improve streaming, storage recovery, and resource cleanup - Preserve explicit Android installation consent - Document retained safeguards and expand emulator coverage --- README.md | 12 +- .../java/meghdad/pakkit/LocalReceiveTest.kt | 86 +++++++- .../meghdad/pakkit/PackageInspectionTest.kt | 18 +- .../java/meghdad/pakkit/PackageStoreTest.kt | 54 ++++- .../meghdad/pakkit/ReceiverLifecycleTest.kt | 45 ++++ .../java/meghdad/pakkit/ServerExpiryTest.kt | 35 --- .../meghdad/pakkit/WatchExperienceTest.kt | 23 +- .../java/meghdad/pakkit/WatchTest.kt | 4 +- app/src/main/AndroidManifest.xml | 1 + app/src/main/assets/web/app.js | 129 +++++++---- app/src/main/assets/web/index.html | 27 +-- app/src/main/assets/web/style.css | 40 ++-- .../java/meghdad/pakkit/PakkitApplication.kt | 11 + .../main/java/meghdad/pakkit/apk/ApkRules.kt | 9 +- .../meghdad/pakkit/apk/PackageInspector.kt | 23 +- .../java/meghdad/pakkit/apk/UserMessage.kt | 9 +- .../java/meghdad/pakkit/data/PackageStore.kt | 23 +- .../meghdad/pakkit/install/ApkInstaller.kt | 10 +- .../meghdad/pakkit/transfer/BrowserAccess.kt | 98 +++++++++ .../meghdad/pakkit/transfer/HttpProtocol.kt | 48 +++- .../pakkit/transfer/LocalHttpServer.kt | 172 ++++++++++----- .../meghdad/pakkit/transfer/ReceiveService.kt | 110 +++++----- .../java/meghdad/pakkit/transfer/Receiving.kt | 15 +- .../java/meghdad/pakkit/ui/WatchActivity.kt | 205 ++++++++---------- app/src/main/res/values/strings.xml | 21 +- .../java/meghdad/pakkit/apk/ApkRulesTest.kt | 33 +-- .../meghdad/pakkit/apk/CompatibilityTest.kt | 26 +-- .../pakkit/transfer/BrowserAccessTest.kt | 66 ++++++ .../pakkit/transfer/HttpProtocolTest.kt | 59 ++++- docs/ARCHITECTURE.md | 48 ++-- docs/DESIGN.md | 8 +- docs/DEVELOPMENT.md | 23 +- docs/PLATFORM.md | 6 +- docs/PRIVACY.md | 8 +- docs/RESTRICTIONS.md | 56 +++++ docs/VALIDATION.md | 20 +- scripts/create-large-fixture.py | 54 +++++ scripts/emulator_utils.py | 6 +- scripts/test-emulators.py | 25 ++- web-tests/browser.test.cjs | 101 +++++++-- web-tests/emulator.test.cjs | 35 ++- 41 files changed, 1241 insertions(+), 561 deletions(-) create mode 100644 app/src/androidTest/java/meghdad/pakkit/ReceiverLifecycleTest.kt delete mode 100644 app/src/androidTest/java/meghdad/pakkit/ServerExpiryTest.kt create mode 100644 app/src/main/java/meghdad/pakkit/PakkitApplication.kt create mode 100644 app/src/main/java/meghdad/pakkit/transfer/BrowserAccess.kt create mode 100644 app/src/test/java/meghdad/pakkit/transfer/BrowserAccessTest.kt create mode 100644 docs/RESTRICTIONS.md create mode 100644 scripts/create-large-fixture.py diff --git a/README.md b/README.md index c7116fa..6fd8546 100644 --- a/README.md +++ b/README.md @@ -8,12 +8,12 @@ Send an APK from your browser to your Wear OS watch, then approve installation o 1. Open Pakkit on a supported watch. 2. Connect the watch and browser device to the same trusted Wi-Fi. -3. Tap **Start receiving** and scan the QR code. For manual entry, tap **View link** on the watch and open the complete link in your browser. -4. Select one complete `.apk` up to **50 MiB**. Watch transfer progress in the browser and on the watch. -5. Review the app on your watch. If prompted, tap **Allow installs** to grant source permission, then tap **Install** and approve it. -6. End the receiving session when finished. Sessions automatically end after ten minutes or on Wi-Fi loss. +3. Tap **Start receiving** and scan the QR code or open the displayed address. The port is always **8787**. +4. Tap **Allow browser** on your watch, then choose an APK in the browser. There is no product file-size limit; available storage and Android determine what fits. +5. Review the app and tap **Install** on your watch. First-time **Allow installs** grants source permission and continues the requested installation. Approve it in Android’s installer. +6. Tap **Stop receiving** when finished. Receiving has no app-imposed expiry and reconnects when Wi-Fi returns. -The local connection uses **unencrypted HTTP**. Use trusted Wi-Fi and keep the private link secret. Package inspection checks format and compatibility; it does not certify app safety. Source approval, firmware security policy and Android’s installer determine whether installation is available. Split packages and app bundles are unsupported. See [platform constraints](docs/PLATFORM.md). +The local connection uses **unencrypted HTTP**. Use trusted Wi-Fi and approve only browsers you recognize. Package inspection checks format and compatibility; it does not certify app safety. Source approval, firmware security policy and Android’s installer determine whether installation is available. Split packages and app bundles are unsupported. See [platform constraints](docs/PLATFORM.md). The current artifacts are development builds. Public distribution requires the checks in [release preparation](docs/RELEASE.md). @@ -55,4 +55,4 @@ python3 scripts/test-emulators.py --watch emulator-5554 --small --skip-build For browser tests and real Android-Emulator-to-Wear-Emulator uploads, see [development and testing](docs/DEVELOPMENT.md). Results and screenshots are generated under `app/build/reports/validation`, not checked into source control. -[Architecture](docs/ARCHITECTURE.md) · [Design](docs/DESIGN.md) · [Platform](docs/PLATFORM.md) · [Privacy](docs/PRIVACY.md) · [Release](docs/RELEASE.md) · [Validation](docs/VALIDATION.md) +[Restriction audit](docs/RESTRICTIONS.md) · [Architecture](docs/ARCHITECTURE.md) · [Design](docs/DESIGN.md) · [Platform](docs/PLATFORM.md) · [Privacy](docs/PRIVACY.md) · [Release](docs/RELEASE.md) · [Validation](docs/VALIDATION.md) diff --git a/app/src/androidTest/java/meghdad/pakkit/LocalReceiveTest.kt b/app/src/androidTest/java/meghdad/pakkit/LocalReceiveTest.kt index 0592107..83b3d80 100644 --- a/app/src/androidTest/java/meghdad/pakkit/LocalReceiveTest.kt +++ b/app/src/androidTest/java/meghdad/pakkit/LocalReceiveTest.kt @@ -14,16 +14,17 @@ import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class LocalReceiveTest : WatchTest() { @Test - fun authenticatedUploadVerifiesPackageAndStopRevokesPrivateLink() { + fun watchApprovedBrowserCanUploadAndStoppingRevokesAccess() { openWatch() context.startForegroundService(Intent(context, ReceiveService::class.java)) await(30_000) { Receiving.state.url != null } val url = URI(requireNotNull(Receiving.state.url)) val sessions = context.packageManager.packageInstaller.mySessions.map { it.sessionId } + var browserCredential: String? = null fun request( method: String, path: String, - token: String? = url.fragment, + credential: String? = browserCredential, origin: String = "http://${url.authority}", host: String = url.authority, body: ByteArray? = null, @@ -33,8 +34,8 @@ class LocalReceiveTest : WatchTest() { socket.soTimeout = 10_000 val headers = "$method $path HTTP/1.1\r\nHost: $host\r\n" + - (token?.let { "Authorization: Bearer $it\r\n" } ?: "") + - "Origin: $origin\r\n" + + (credential?.let { "Authorization: Bearer $it\r\n" } ?: "") + + "Origin: $origin\r\nUser-Agent: Chrome Android\r\n" + (contentLength?.let { "Content-Type: application/octet-stream\r\nContent-Length: $it\r\n" } ?: "") + @@ -67,11 +68,26 @@ class LocalReceiveTest : WatchTest() { head.toString() + bytes.toString(Charsets.UTF_8) } } + fun assertUploadWakeReleased() { + await { Receiving.state.total == 0L } + val dump = + instrumentation.uiAutomation.executeShellCommand("dumpsys power").use { descriptor + -> + android.os.ParcelFileDescriptor.AutoCloseInputStream(descriptor).use { + it.readBytes().toString(Charsets.UTF_8) + } + } + assertTrue("Power state must be observable", dump.contains("Wake Locks:")) + assertFalse( + "Completed requests must not hold an upload wake lock", + Regex("(?m)^\\s*PARTIAL_WAKE_LOCK.*pakkit:upload.*$").containsMatchIn(dump), + ) + } assertTrue(request("GET", "/").contains("Pack it.")) - assertTrue(request("GET", "/api/status", token = null).startsWith("HTTP/1.1 403")) - assertTrue(request("GET", "/api/status", token = "wrong").startsWith("HTTP/1.1 403")) + assertTrue(request("GET", "/api/status", credential = null).startsWith("HTTP/1.1 403")) + assertTrue(request("GET", "/api/status", credential = "wrong").startsWith("HTTP/1.1 403")) assertTrue( - request("GET", "/api/status", host = "attacker.example").startsWith("HTTP/1.1 403"), + request("GET", "/api/status", host = "attacker.example").startsWith("HTTP/1.1 403") ) assertTrue( request( @@ -80,23 +96,33 @@ class LocalReceiveTest : WatchTest() { origin = "https://attacker.example", body = byteArrayOf(1), ) - .startsWith("HTTP/1.1 403"), + .startsWith("HTTP/1.1 403") ) + val connection = request("POST", "/api/connect") + browserCredential = + org.json.JSONObject(connection.substringAfter("\r\n\r\n")).getString("credential") + assertFalse(connection.contains("Set-Cookie:")) + assertTrue(request("POST", "/api/upload", body = byteArrayOf(1)).startsWith("HTTP/1.1 403")) + assertTrue(request("GET", "/api/status").contains("pending")) + assertTrue(Receiving.answerBrowser(requireNotNull(Receiving.state.browserRequest).id, true)) + assertTrue(request("GET", "/api/status").startsWith("HTTP/1.1 200")) + assertFalse(request("GET", "/api/status").contains("expiresIn")) assertTrue( - request("POST", "/api/upload", contentLength = 52_428_801).startsWith("HTTP/1.1 400"), + request("POST", "/api/upload", contentLength = Long.MAX_VALUE).contains("storage") ) assertTrue( request("POST", "/api/upload", body = "invalid APK".toByteArray()) - .startsWith("HTTP/1.1 400"), + .startsWith("HTTP/1.1 400") ) assertNull(store.pending()) assertTrue( request("POST", "/api/upload", body = "short".toByteArray(), contentLength = 100) - .startsWith("HTTP/1.1 400"), + .startsWith("HTTP/1.1 400") ) assertNull(store.pending()) assertEquals(0L, Receiving.state.total) assertEquals("Ready to receive", Receiving.state.detail) + assertUploadWakeReleased() val fixture = instrumentation.context.assets.open("fixture.apk").use { it.readBytes() } assertTrue(request("POST", "/api/upload", body = fixture).startsWith("HTTP/1.1 200")) assertEquals(InstallState.READY, store.pending()?.state) @@ -107,10 +133,48 @@ class LocalReceiveTest : WatchTest() { ) assertTrue(request("POST", "/api/upload", body = byteArrayOf(1)).startsWith("HTTP/1.1 409")) assertTrue(request("GET", "/api/status").contains("ready")) + assertUploadWakeReleased() + // A finished install does not require a separate Done tap before the next upload. + for (terminal in listOf(InstallState.INSTALLED, InstallState.FAILED)) { + store.update(requireNotNull(store.pending()).id, terminal, "Finished") + assertTrue(request("POST", "/api/upload", body = fixture).startsWith("HTTP/1.1 200")) + assertEquals(InstallState.READY, store.pending()?.state) + } context.stopService(Intent(context, ReceiveService::class.java)) await { !Receiving.state.active } assertNull(Receiving.state.url) assertTrue(runCatching { Socket(url.host, url.port).close() }.isFailure) + context.startForegroundService(Intent(context, ReceiveService::class.java)) + await(30_000) { Receiving.state.url != null } + assertEquals(url.toString(), Receiving.state.url) + assertTrue(request("GET", "/api/status").startsWith("HTTP/1.1 403")) + } + + @Test + fun losingWifiWaitsForReconnectionWithoutEndingReceiving() { + openWatch() + context.startForegroundService(Intent(context, ReceiveService::class.java)) + await(30_000) { Receiving.state.url != null } + fun shell(command: String) { + instrumentation.uiAutomation.executeShellCommand(command).use { descriptor -> + android.os.ParcelFileDescriptor.AutoCloseInputStream(descriptor).use { + it.readBytes() + } + } + } + try { + shell("cmd wifi set-wifi-enabled disabled") + await(15_000) { Receiving.state.url == null } + assertTrue(Receiving.state.active) + shell("cmd wifi set-wifi-enabled enabled") + shell("cmd wifi connect-network AndroidWifi open") + await(30_000) { Receiving.state.url != null } + assertTrue(Receiving.state.active) + assertEquals(8787, URI(requireNotNull(Receiving.state.url)).port) + } finally { + shell("cmd wifi set-wifi-enabled enabled") + shell("cmd wifi connect-network AndroidWifi open") + } } @Test diff --git a/app/src/androidTest/java/meghdad/pakkit/PackageInspectionTest.kt b/app/src/androidTest/java/meghdad/pakkit/PackageInspectionTest.kt index 832b093..7e1836b 100644 --- a/app/src/androidTest/java/meghdad/pakkit/PackageInspectionTest.kt +++ b/app/src/androidTest/java/meghdad/pakkit/PackageInspectionTest.kt @@ -7,16 +7,30 @@ import java.util.zip.ZipEntry import java.util.zip.ZipOutputStream import meghdad.pakkit.apk.ApkRules import meghdad.pakkit.apk.PackageInspector +import meghdad.pakkit.apk.userMessage import org.junit.Assert.* import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class PackageInspectionTest : WatchTest() { + @Test + fun runningOutOfSpaceHasActionableFeedbackWithoutRawPaths() { + val failure = + java.io.IOException( + "/data/private/file.apk", + android.system.ErrnoException("write", android.system.OsConstants.ENOSPC), + ) + assertEquals( + "Free some space on your watch, then try again.", + failure.userMessage("Try again."), + ) + } + @Test fun selfUpdateIsRejectedBeforeCreatingAnInstallSession() { val ownApk = File(context.applicationInfo.sourceDir) - val digest = ownApk.inputStream().use { ApkRules.copyBounded(it).second } + val digest = ownApk.inputStream().use { ApkRules.copyAndHash(it).second } val result = runCatching { PackageInspector.inspect(context, ownApk, digest) } assertTrue(result.isFailure) assertTrue(result.exceptionOrNull()?.message.orEmpty().contains("Google Play")) @@ -31,7 +45,7 @@ class PackageInspectionTest : WatchTest() { it.write("Not an app".toByteArray()) it.closeEntry() } - val digest = file.inputStream().use { ApkRules.copyBounded(it).second } + val digest = file.inputStream().use { ApkRules.copyAndHash(it).second } assertTrue(runCatching { PackageInspector.inspect(context, file, digest) }.isFailure) } finally { file.delete() diff --git a/app/src/androidTest/java/meghdad/pakkit/PackageStoreTest.kt b/app/src/androidTest/java/meghdad/pakkit/PackageStoreTest.kt index c9e1801..7c45701 100644 --- a/app/src/androidTest/java/meghdad/pakkit/PackageStoreTest.kt +++ b/app/src/androidTest/java/meghdad/pakkit/PackageStoreTest.kt @@ -1,7 +1,6 @@ package meghdad.pakkit import androidx.test.ext.junit.runners.AndroidJUnit4 -import meghdad.pakkit.apk.ApkRules import meghdad.pakkit.apk.InstallState import meghdad.pakkit.data.PackageStore import org.junit.Assert.* @@ -10,6 +9,49 @@ import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class PackageStoreTest : WatchTest() { + @Test + fun failedMetadataWriteRestoresThePreviousReview() { + val apk = fixture() + store.stage(apk) + var failNext = true + val real = store.preferences + val faulty = + object : android.content.SharedPreferences by real { + override fun edit(): android.content.SharedPreferences.Editor { + val editor = real.edit() + return object : android.content.SharedPreferences.Editor by editor { + override fun putString( + key: String, + value: String?, + ): android.content.SharedPreferences.Editor { + editor.putString(key, value) + return this + } + + override fun commit(): Boolean { + val written = editor.commit() + if (failNext) { + failNext = false + return false + } + return written + } + } + } + } + val wrapped = + object : android.content.ContextWrapper(context) { + override fun getSharedPreferences(name: String, mode: Int) = faulty + } + assertTrue( + runCatching { + PackageStore(wrapped).update(apk.id, InstallState.INSTALLING, "Preparing") + } + .isFailure + ) + assertEquals(apk, store.pending()) + } + @Test fun persistsReviewAcrossStoreInstancesAndRejectsReplacement() { val apk = fixture() @@ -20,14 +62,14 @@ class PackageStoreTest : WatchTest() { } @Test - fun expiredReviewAndOrphanedFileAreRemoved() { - val apk = fixture().copy(created = System.currentTimeMillis() - ApkRules.TTL_MS) + fun oldReviewsRemainAvailableAndUncommittedFilesAreCleaned() { + val apk = fixture().copy(created = 1L) store.stage(apk) val orphan = fixture() - store.file(orphan.id).setLastModified(System.currentTimeMillis() - ApkRules.TTL_MS - 1000) + store.file(orphan.id).setLastModified(System.currentTimeMillis()) store.clean() - assertNull(store.pending()) - assertFalse(store.file(apk.id).exists()) + assertEquals(apk, store.pending()) + assertTrue(store.file(apk.id).exists()) assertFalse(store.file(orphan.id).exists()) } diff --git a/app/src/androidTest/java/meghdad/pakkit/ReceiverLifecycleTest.kt b/app/src/androidTest/java/meghdad/pakkit/ReceiverLifecycleTest.kt new file mode 100644 index 0000000..5b263dd --- /dev/null +++ b/app/src/androidTest/java/meghdad/pakkit/ReceiverLifecycleTest.kt @@ -0,0 +1,45 @@ +package meghdad.pakkit + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import java.net.BindException +import java.net.Inet4Address +import java.net.InetAddress +import meghdad.pakkit.transfer.LocalHttpServer +import org.junit.Assert.* +import org.junit.Test +import org.junit.runner.RunWith + +@RunWith(AndroidJUnit4::class) +class ReceiverLifecycleTest : WatchTest() { + @Test + fun ipv6ListenerAcceptsCanonicalBrowserAuthority() { + LocalHttpServer(context, InetAddress.getByName("::1"), Any()).use { server -> + server.start() + val response = + java.net.Socket(InetAddress.getByName("::1"), 8787).use { socket -> + socket.soTimeout = 5000 + socket + .getOutputStream() + .write("GET / HTTP/1.1\r\nHost: [::1]:8787\r\n\r\n".toByteArray()) + socket.getInputStream().bufferedReader().readText() + } + assertTrue(response.startsWith("HTTP/1.1 200")) + } + } + + @Test + fun portIsFixedAndBusyPortsNeverSilentlyChangeTheAddress() { + val address = InetAddress.getByName("127.0.0.1") as Inet4Address + LocalHttpServer(context, address, Any()).use { server -> + assertEquals("http://127.0.0.1:8787/", server.url) + val failure = runCatching { + LocalHttpServer(context, address, Any()).close() + } + .exceptionOrNull() + assertTrue(failure is BindException) + } + LocalHttpServer(context, address, Any()).use { + assertEquals("http://127.0.0.1:8787/", it.url) + } + } +} diff --git a/app/src/androidTest/java/meghdad/pakkit/ServerExpiryTest.kt b/app/src/androidTest/java/meghdad/pakkit/ServerExpiryTest.kt deleted file mode 100644 index 7ce51b6..0000000 --- a/app/src/androidTest/java/meghdad/pakkit/ServerExpiryTest.kt +++ /dev/null @@ -1,35 +0,0 @@ -package meghdad.pakkit - -import android.os.SystemClock -import androidx.test.ext.junit.runners.AndroidJUnit4 -import java.net.Inet4Address -import java.net.InetAddress -import java.net.Socket -import java.net.URI -import meghdad.pakkit.transfer.LocalHttpServer -import org.junit.Assert.* -import org.junit.Test -import org.junit.runner.RunWith - -@RunWith(AndroidJUnit4::class) -class ServerExpiryTest : WatchTest() { - @Test - fun expiredSessionRefusesRequestsEvenWithTheCorrectKey() { - val address = InetAddress.getByName("127.0.0.1") as Inet4Address - LocalHttpServer(context, address, SystemClock.elapsedRealtime() - 1, Any()).use { server -> - server.start() - val url = URI(server.url) - val response = - Socket(url.host, url.port).use { socket -> - socket.soTimeout = 5000 - val request = - "GET /api/status HTTP/1.1\r\nHost: ${url.authority}\r\nAuthorization: Bearer ${url.fragment}\r\n\r\n" - socket.getOutputStream().write(request.toByteArray()) - socket.getInputStream().bufferedReader().readText() - } - assertTrue(response.startsWith("HTTP/1.1 400")) - assertTrue(response.contains("didn’t arrive")) - assertNull(store.pending()) - } - } -} diff --git a/app/src/androidTest/java/meghdad/pakkit/WatchExperienceTest.kt b/app/src/androidTest/java/meghdad/pakkit/WatchExperienceTest.kt index 03257f6..af11137 100644 --- a/app/src/androidTest/java/meghdad/pakkit/WatchExperienceTest.kt +++ b/app/src/androidTest/java/meghdad/pakkit/WatchExperienceTest.kt @@ -104,21 +104,24 @@ class WatchExperienceTest : WatchTest() { val owner = Any() try { Receiving.begin(owner) - Receiving.update(owner) { it.copy(url = "http://10.0.2.16:8080/#test-display-link") } + Receiving.update(owner) { it.copy(url = "http://10.0.2.16:8787/") } openWatch() capture("scan") - instrumentation.runOnMainSync { - screen().filterIsInstance - +
+ +

A quick hello

+

Tap Allow browser on your watch.

+ +
  1. Choose
  2. Send
  3. @@ -173,7 +167,7 @@ type="file" accept=".apk,application/vnd.android.package-archive" hidden - />APK files · up to 50 MB + />APK files · sent directly to your watch