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
This commit is contained in:
Meghdad committed 2026-10-15 19:50:10 +03:30
1 parent 1a64de5515
commit 6e41db2a74
41 files changed
+1241 -561

No files matched your search

+6 -6
View File
@@ -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. 1. Open Pakkit on a supported watch.
2. Connect the watch and browser device to the same trusted Wi-Fi. 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. 3. Tap **Start receiving** and scan the QR code or open the displayed address. The port is always **8787**.
4. Select one complete `.apk` up to **50 MiB**. Watch transfer progress in the browser and on the watch. 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 on your watch. If prompted, tap **Allow installs** to grant source permission, then tap **Install** and approve it. 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. End the receiving session when finished. Sessions automatically end after ten minutes or on Wi-Fi loss. 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). 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. 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)
@@ -14,16 +14,17 @@ import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class) @RunWith(AndroidJUnit4::class)
class LocalReceiveTest : WatchTest() { class LocalReceiveTest : WatchTest() {
@Test @Test
fun authenticatedUploadVerifiesPackageAndStopRevokesPrivateLink() { fun watchApprovedBrowserCanUploadAndStoppingRevokesAccess() {
openWatch() openWatch()
context.startForegroundService(Intent(context, ReceiveService::class.java)) context.startForegroundService(Intent(context, ReceiveService::class.java))
await(30_000) { Receiving.state.url != null } await(30_000) { Receiving.state.url != null }
val url = URI(requireNotNull(Receiving.state.url)) val url = URI(requireNotNull(Receiving.state.url))
val sessions = context.packageManager.packageInstaller.mySessions.map { it.sessionId } val sessions = context.packageManager.packageInstaller.mySessions.map { it.sessionId }
var browserCredential: String? = null
fun request( fun request(
method: String, method: String,
path: String, path: String,
token: String? = url.fragment, credential: String? = browserCredential,
origin: String = "http://${url.authority}", origin: String = "http://${url.authority}",
host: String = url.authority, host: String = url.authority,
body: ByteArray? = null, body: ByteArray? = null,
@@ -33,8 +34,8 @@ class LocalReceiveTest : WatchTest() {
socket.soTimeout = 10_000 socket.soTimeout = 10_000
val headers = val headers =
"$method $path HTTP/1.1\r\nHost: $host\r\n" + "$method $path HTTP/1.1\r\nHost: $host\r\n" +
(token?.let { "Authorization: Bearer $it\r\n" } ?: "") + (credential?.let { "Authorization: Bearer $it\r\n" } ?: "") +
"Origin: $origin\r\n" + "Origin: $origin\r\nUser-Agent: Chrome Android\r\n" +
(contentLength?.let { (contentLength?.let {
"Content-Type: application/octet-stream\r\nContent-Length: $it\r\n" "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) 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", "/").contains("Pack it."))
assertTrue(request("GET", "/api/status", token = null).startsWith("HTTP/1.1 403")) assertTrue(request("GET", "/api/status", credential = null).startsWith("HTTP/1.1 403"))
assertTrue(request("GET", "/api/status", token = "wrong").startsWith("HTTP/1.1 403")) assertTrue(request("GET", "/api/status", credential = "wrong").startsWith("HTTP/1.1 403"))
assertTrue( 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( assertTrue(
request( request(
@@ -80,23 +96,33 @@ class LocalReceiveTest : WatchTest() {
origin = "https://attacker.example", origin = "https://attacker.example",
body = byteArrayOf(1), 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( 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( assertTrue(
request("POST", "/api/upload", body = "invalid APK".toByteArray()) request("POST", "/api/upload", body = "invalid APK".toByteArray())
.startsWith("HTTP/1.1 400"), .startsWith("HTTP/1.1 400")
) )
assertNull(store.pending()) assertNull(store.pending())
assertTrue( assertTrue(
request("POST", "/api/upload", body = "short".toByteArray(), contentLength = 100) request("POST", "/api/upload", body = "short".toByteArray(), contentLength = 100)
.startsWith("HTTP/1.1 400"), .startsWith("HTTP/1.1 400")
) )
assertNull(store.pending()) assertNull(store.pending())
assertEquals(0L, Receiving.state.total) assertEquals(0L, Receiving.state.total)
assertEquals("Ready to receive", Receiving.state.detail) assertEquals("Ready to receive", Receiving.state.detail)
assertUploadWakeReleased()
val fixture = instrumentation.context.assets.open("fixture.apk").use { it.readBytes() } val fixture = instrumentation.context.assets.open("fixture.apk").use { it.readBytes() }
assertTrue(request("POST", "/api/upload", body = fixture).startsWith("HTTP/1.1 200")) assertTrue(request("POST", "/api/upload", body = fixture).startsWith("HTTP/1.1 200"))
assertEquals(InstallState.READY, store.pending()?.state) 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("POST", "/api/upload", body = byteArrayOf(1)).startsWith("HTTP/1.1 409"))
assertTrue(request("GET", "/api/status").contains("ready")) 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)) context.stopService(Intent(context, ReceiveService::class.java))
await { !Receiving.state.active } await { !Receiving.state.active }
assertNull(Receiving.state.url) assertNull(Receiving.state.url)
assertTrue(runCatching { Socket(url.host, url.port).close() }.isFailure) 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 @Test
@@ -7,16 +7,30 @@ import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream import java.util.zip.ZipOutputStream
import meghdad.pakkit.apk.ApkRules import meghdad.pakkit.apk.ApkRules
import meghdad.pakkit.apk.PackageInspector import meghdad.pakkit.apk.PackageInspector
import meghdad.pakkit.apk.userMessage
import org.junit.Assert.* import org.junit.Assert.*
import org.junit.Test import org.junit.Test
import org.junit.runner.RunWith import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class) @RunWith(AndroidJUnit4::class)
class PackageInspectionTest : WatchTest() { 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 @Test
fun selfUpdateIsRejectedBeforeCreatingAnInstallSession() { fun selfUpdateIsRejectedBeforeCreatingAnInstallSession() {
val ownApk = File(context.applicationInfo.sourceDir) 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) } val result = runCatching { PackageInspector.inspect(context, ownApk, digest) }
assertTrue(result.isFailure) assertTrue(result.isFailure)
assertTrue(result.exceptionOrNull()?.message.orEmpty().contains("Google Play")) assertTrue(result.exceptionOrNull()?.message.orEmpty().contains("Google Play"))
@@ -31,7 +45,7 @@ class PackageInspectionTest : WatchTest() {
it.write("Not an app".toByteArray()) it.write("Not an app".toByteArray())
it.closeEntry() 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) assertTrue(runCatching { PackageInspector.inspect(context, file, digest) }.isFailure)
} finally { } finally {
file.delete() file.delete()
@@ -1,7 +1,6 @@
package meghdad.pakkit package meghdad.pakkit
import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.ext.junit.runners.AndroidJUnit4
import meghdad.pakkit.apk.ApkRules
import meghdad.pakkit.apk.InstallState import meghdad.pakkit.apk.InstallState
import meghdad.pakkit.data.PackageStore import meghdad.pakkit.data.PackageStore
import org.junit.Assert.* import org.junit.Assert.*
@@ -10,6 +9,49 @@ import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class) @RunWith(AndroidJUnit4::class)
class PackageStoreTest : WatchTest() { 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 @Test
fun persistsReviewAcrossStoreInstancesAndRejectsReplacement() { fun persistsReviewAcrossStoreInstancesAndRejectsReplacement() {
val apk = fixture() val apk = fixture()
@@ -20,14 +62,14 @@ class PackageStoreTest : WatchTest() {
} }
@Test @Test
fun expiredReviewAndOrphanedFileAreRemoved() { fun oldReviewsRemainAvailableAndUncommittedFilesAreCleaned() {
val apk = fixture().copy(created = System.currentTimeMillis() - ApkRules.TTL_MS) val apk = fixture().copy(created = 1L)
store.stage(apk) store.stage(apk)
val orphan = fixture() val orphan = fixture()
store.file(orphan.id).setLastModified(System.currentTimeMillis() - ApkRules.TTL_MS - 1000) store.file(orphan.id).setLastModified(System.currentTimeMillis())
store.clean() store.clean()
assertNull(store.pending()) assertEquals(apk, store.pending())
assertFalse(store.file(apk.id).exists()) assertTrue(store.file(apk.id).exists())
assertFalse(store.file(orphan.id).exists()) assertFalse(store.file(orphan.id).exists())
} }
@@ -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)
}
}
}
@@ -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())
}
}
}
@@ -104,21 +104,24 @@ class WatchExperienceTest : WatchTest() {
val owner = Any() val owner = Any()
try { try {
Receiving.begin(owner) 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() openWatch()
capture("scan") capture("scan")
instrumentation.runOnMainSync { assertActionsReachable()
screen().filterIsInstance<Button>().single { it.text == "View link" }.performClick() Receiving.update(owner) {
it.copy(
browserRequest =
meghdad.pakkit.transfer.BrowserAccess.Request(
"test-browser",
"Chrome on Android",
"10.0.2.17",
)
)
} }
instrumentation.waitForIdleSync() instrumentation.waitForIdleSync()
assertActionsReachable() assertActionsReachable()
capture("link") capture("browser-approval")
instrumentation.runOnMainSync { Receiving.update(owner) { it.copy(browserRequest = null) }
screen()
.filterIsInstance<Button>()
.single { it.text == "Back to code" }
.performClick()
}
Receiving.update(owner) { it.copy(total = 1000, received = 420) } Receiving.update(owner) { it.copy(total = 1000, received = 420) }
instrumentation.waitForIdleSync() instrumentation.waitForIdleSync()
capture("sending") capture("sending")
@@ -34,7 +34,7 @@ abstract class WatchTest {
val monitor = instrumentation.addMonitor(WatchActivity::class.java.name, null, false) val monitor = instrumentation.addMonitor(WatchActivity::class.java.name, null, false)
context.startActivity( context.startActivity(
Intent(context, WatchActivity::class.java) Intent(context, WatchActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK), .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
) )
activity = requireNotNull(monitor.waitForActivityWithTimeout(5000)) activity = requireNotNull(monitor.waitForActivityWithTimeout(5000))
instrumentation.removeMonitor(monitor) instrumentation.removeMonitor(monitor)
@@ -46,7 +46,7 @@ abstract class WatchTest {
val file = store.file(id) val file = store.file(id)
val digest = val digest =
instrumentation.context.assets.open("fixture.apk").use { input -> instrumentation.context.assets.open("fixture.apk").use { input ->
file.outputStream().use { ApkRules.copyBounded(input, it).second } file.outputStream().use { ApkRules.copyAndHash(input, it).second }
} }
return PendingApk( return PendingApk(
id, id,
+1
View File
@@ -11,6 +11,7 @@
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE" />
<application <application
android:name=".PakkitApplication"
android:allowBackup="false" android:allowBackup="false"
android:dataExtractionRules="@xml/pakkit_data_rules" android:dataExtractionRules="@xml/pakkit_data_rules"
android:icon="@mipmap/pakkit_launcher" android:icon="@mipmap/pakkit_launcher"
+81 -48
View File
@@ -1,18 +1,25 @@
'use strict'; 'use strict';
const $ = (id) => document.getElementById(id); const $ = (id) => document.getElementById(id);
let token = location.hash.slice(1), let file = null,
file = null,
upload = null, upload = null,
online = false, online = false,
pending = false; pending = false,
choosingNext = false;
// Storage is isolated by scheme + host + port. No cookie can leak access to another
// app's server on a different port of the same watch. Nothing is copied by the user.
let credential = '';
function accessHeaders() {
try {
credential = localStorage.getItem('pakkitAccess') || credential;
} catch {}
return credential ? { Authorization: 'Bearer ' + credential } : {};
}
const initialTheme = window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark'; const initialTheme = window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark';
document.documentElement.dataset.theme = initialTheme; document.documentElement.dataset.theme = initialTheme;
$('theme').onclick = () => { $('theme').onclick = () => {
document.documentElement.dataset.theme = document.documentElement.dataset.theme =
document.documentElement.dataset.theme === 'dark' ? 'light' : 'dark'; document.documentElement.dataset.theme === 'dark' ? 'light' : 'dark';
}; };
// Keep the secret out of subsequent navigation, referrers and visible browser history.
if (token) history.replaceState(null, '', location.pathname);
function setText(id, value) { function setText(id, value) {
if ($(id).textContent !== value) $(id).textContent = value; if ($(id).textContent !== value) $(id).textContent = value;
} }
@@ -27,25 +34,21 @@ function panel(id) {
item.classList.toggle('complete', index < step); item.classList.toggle('complete', index < step);
}); });
$('progress-panel').setAttribute('aria-busy', String(id === 'progress-panel')); $('progress-panel').setAttribute('aria-busy', String(id === 'progress-panel'));
['dropzone', 'selection', 'progress-panel', 'result'].forEach( ['pairing', 'dropzone', 'selection', 'progress-panel', 'result'].forEach(
(key) => ($(key).hidden = key !== id), (key) => ($(key).hidden = key !== id),
); );
} }
function selected(next) { function selected(next) {
if (!online || pending || upload) return; if (!online || pending || upload) return;
message(); message();
if ( if (!next || next.size === 0) {
!next || message('This file is empty. Choose an app to send.');
!next.name.toLowerCase().endsWith('.apk') ||
next.size === 0 ||
next.size > 50 * 1024 * 1024
) {
message('Choose a single APK up to 50 MB. Bundles and split APKs won’t work here.');
return; return;
} }
file = next; file = next;
$('filename').textContent = file.name; $('filename').textContent = file.name;
$('filesize').textContent = (file.size / 1048576).toFixed(1) + ' MB · ready to send'; $('filesize').dataset.bytes = String(file.size);
$('filesize').textContent = formatSize(file.size) + ' · ready to send';
panel('selection'); panel('selection');
$('send').focus({ preventScroll: true }); $('send').focus({ preventScroll: true });
} }
@@ -100,9 +103,9 @@ $('send').onclick = () => {
const xhr = new XMLHttpRequest(); const xhr = new XMLHttpRequest();
upload = xhr; upload = xhr;
xhr.open('POST', '/api/upload'); xhr.open('POST', '/api/upload');
xhr.setRequestHeader('Authorization', 'Bearer ' + token); Object.entries(accessHeaders()).forEach(([name, value]) => xhr.setRequestHeader(name, value));
xhr.setRequestHeader('Content-Type', 'application/octet-stream'); xhr.setRequestHeader('Content-Type', 'application/octet-stream');
xhr.timeout = 300000; // No total upload timeout. A slow, progressing transfer is allowed to finish.
xhr.upload.onprogress = (e) => { xhr.upload.onprogress = (e) => {
if (!e.lengthComputable) return; if (!e.lengthComputable) return;
const percent = Math.floor((e.loaded / e.total) * 100); const percent = Math.floor((e.loaded / e.total) * 100);
@@ -133,14 +136,13 @@ $('send').onclick = () => {
return; return;
} }
pending = true; pending = true;
choosingNext = false;
file = null; file = null;
result('Made it to your watch', 'Review ' + data.label + ' on your watch.'); result('Made it to your watch', 'Review ' + data.label + ' on your watch.');
poll(); poll();
}; };
xhr.onerror = () => xhr.onerror = () =>
failed('Connection lost. Check that both devices are on the same Wi-Fi, then try again.'); failed('Connection lost. Your file is ready to send again when your watch reconnects.');
xhr.ontimeout = () =>
failed('That took too long. Open a fresh link from your watch and try again.');
xhr.onabort = () => failed('Transfer cancelled. Your app may have arrived—check your watch.'); xhr.onabort = () => failed('Transfer cancelled. Your app may have arrived—check your watch.');
xhr.send(file); xhr.send(file);
}; };
@@ -148,54 +150,88 @@ $('cancel').onclick = () => upload?.abort();
$('again').onclick = () => { $('again').onclick = () => {
if (!pending) { if (!pending) {
file = null; file = null;
choosingNext = true;
panel('dropzone'); panel('dropzone');
message(); message();
} }
}; };
$('access-form').onsubmit = (e) => { function formatSize(bytes) {
e.preventDefault(); const units = ['B', 'KB', 'MB', 'GB', 'TB'];
token = $('access').value.trim().replace(/^.*#/, ''); const unit = Math.min(Math.floor(Math.log10(Math.max(bytes, 1)) / 3), units.length - 1);
$('access').value = ''; return (
poll(); new Intl.NumberFormat(undefined, { maximumFractionDigits: 1 }).format(bytes / 1000 ** unit) +
' ' +
units[unit]
);
}
function pairing(state) {
online = false;
document.querySelector('.connection').dataset.online = 'false';
setText('connection', state === 'denied' ? 'Not connected' : 'Waiting for your watch');
$('choose').disabled = true;
$('send').disabled = true;
panel('pairing');
setText('pairing-title', state === 'denied' ? 'Maybe next time?' : 'A quick hello');
setText(
'pairing-detail',
state === 'denied'
? 'Your watch declined this browser.'
: state === 'busy'
? 'Your watch is connecting another browser. We’ll wait here.'
: 'Tap Allow browser on your watch. You only need to do this once while receiving is on.',
);
$('retry-connection').hidden = state !== 'denied';
}
async function connect(retry = false) {
const response = await fetch(retry ? '/api/retry' : '/api/connect', {
method: 'POST',
headers: accessHeaders(),
});
if (!response.ok) throw new Error('disconnected');
const data = await response.json();
if (data.credential) {
credential = data.credential;
try {
localStorage.setItem('pakkitAccess', credential);
} catch {}
}
pairing(data.connection);
}
$('retry-connection').onclick = () => {
connect(true).catch(() => message('Open Pakkit on your watch and start receiving.'));
}; };
let polling = false; let polling = false;
async function poll() { async function poll() {
if (polling || !token) return; if (polling) return;
polling = true; polling = true;
try { try {
const response = await fetch('/api/status', { const response = await fetch('/api/status', {
headers: { Authorization: 'Bearer ' + token }, headers: accessHeaders(),
cache: 'no-store', cache: 'no-store',
signal: AbortSignal.timeout ? AbortSignal.timeout(5000) : undefined, signal: AbortSignal.timeout ? AbortSignal.timeout(5000) : undefined,
}); });
if (response.status === 403) { if (response.status === 403) {
online = false; const data = await response.json();
document.querySelector('.connection').dataset.online = 'false'; if (data.connection === 'unknown') await connect();
$('access-form').hidden = false; else pairing(data.connection);
$('choose').disabled = true;
$('connection').textContent = 'Let’s connect';
message('Scan the code on your watch to reconnect.');
return; return;
} }
if (!response.ok) throw new Error('disconnected'); if (!response.ok) throw new Error('disconnected');
const data = await response.json(); const data = await response.json();
if (!online) message(); if (!online) {
message();
if (!pending && !upload) panel(file ? 'selection' : 'dropzone');
}
online = true; online = true;
$('send').disabled = false; $('send').disabled = false;
$('access-form').hidden = true;
setText('connection', 'Connected to your watch'); setText('connection', 'Connected to your watch');
document.querySelector('.connection').dataset.online = 'true'; document.querySelector('.connection').dataset.online = 'true';
$('expiry').textContent =
'· ' +
Math.floor(data.expiresIn / 60) +
':' +
String(data.expiresIn % 60).padStart(2, '0') +
' remaining';
$('choose').disabled = false; $('choose').disabled = false;
if (upload) return; if (upload) return;
const waiting = data.state === 'waiting'; const waiting = data.state === 'waiting';
if (!waiting) { if (!waiting) {
pending = true; if (['installed', 'failed'].includes(data.state) && choosingNext) return;
pending = !['installed', 'failed'].includes(data.state);
const states = { const states = {
ready: ['Made it to your watch', 'Review ' + data.label + ' on your watch.'], ready: ['Made it to your watch', 'Review ' + data.label + ' on your watch.'],
confirm: ['One tap closer', 'Approve installation on your watch.'], confirm: ['One tap closer', 'Approve installation on your watch.'],
@@ -206,9 +242,10 @@ async function poll() {
const content = states[data.state] || ['Check your watch.', data.detail]; const content = states[data.state] || ['Check your watch.', data.detail];
result(content[0], content[1], data.state === 'installed'); result(content[0], content[1], data.state === 'installed');
$('result').dataset.state = data.state; $('result').dataset.state = data.state;
if (['installed', 'failed'].includes(data.state)) $('again').hidden = false;
if (data.state === 'failed') $('result-icon').textContent = '!'; if (data.state === 'failed') $('result-icon').textContent = '!';
} else if (pending) { } else if (pending) {
pending = false; ((pending = false), (choosingNext = false));
result('Ready for another?', 'Your watch is ready to receive a new app.', true); result('Ready for another?', 'Your watch is ready to receive a new app.', true);
$('again').hidden = false; $('again').hidden = false;
} }
@@ -220,17 +257,13 @@ async function poll() {
$('choose').disabled = true; $('choose').disabled = true;
if (!upload) if (!upload)
message( message(
'Check your watch’s Wi-Fi. If receiving has stopped, start again and scan the new code.', 'Check Wi-Fi on your watch. If its address has changed, open the new one shown in Pakkit.',
); );
} finally { } finally {
polling = false; polling = false;
} }
} }
if (!token) { panel('pairing');
$('access-form').hidden = false;
$('choose').disabled = true;
$('connection').textContent = 'Let’s connect';
}
poll(); poll();
setInterval(() => { setInterval(() => {
if (!document.hidden) poll(); if (!document.hidden) poll();
+10 -17
View File
@@ -145,18 +145,12 @@
</div> </div>
<h2 id="card-title">Good things<br />come in Pakkits.</h2> <h2 id="card-title">Good things<br />come in Pakkits.</h2>
<p class="card-description">Choose an app for your watch. We’ll deliver it.</p> <p class="card-description">Choose an app for your watch. We’ll deliver it.</p>
<form id="access-form" hidden> <div id="pairing" role="status" aria-live="polite">
<label for="access">Connect your watch</label> <div class="pairing-symbol" aria-hidden="true">↗</div>
<p>Scan the code on your watch, or paste its full link here.</p> <h3 id="pairing-title">A quick hello</h3>
<input <p id="pairing-detail">Tap Allow browser on your watch.</p>
id="access" <button id="retry-connection" class="secondary" type="button" hidden>Try again</button>
type="password" </div>
aria-label="Watch link"
autocomplete="off"
spellcheck="false"
required
/><button class="primary" type="submit">Connect to watch</button>
</form>
<ol class="steps" aria-label="Transfer steps"> <ol class="steps" aria-label="Transfer steps">
<li aria-current="step">Choose</li> <li aria-current="step">Choose</li>
<li>Send</li> <li>Send</li>
@@ -173,7 +167,7 @@
type="file" type="file"
accept=".apk,application/vnd.android.package-archive" accept=".apk,application/vnd.android.package-archive"
hidden hidden
/><small>APK files · up to 50 MB</small> /><small>APK files · sent directly to your watch</small>
</div> </div>
<div id="selection" hidden> <div id="selection" hidden>
<div class="file-row"> <div class="file-row">
@@ -214,12 +208,11 @@
><details class="connection-help"> ><details class="connection-help">
<summary>About this connection</summary> <summary>About this connection</summary>
<p> <p>
Use Wi-Fi you trust. Files travel across your network without encryption. Keep your Use Wi-Fi you trust. Files travel across your network without encryption. Approve only
watch’s link private. browsers you recognize.
</p> </p>
</details> </details>
<span id="expiry"></span </span>
></span>
</footer> </footer>
</div> </div>
</body> </body>
+22 -18
View File
@@ -532,20 +532,6 @@ h3 {
margin: 12px 0; margin: 12px 0;
} }
#access-form {
margin-bottom: 24px;
}
#access-form label {
font-size: 13px;
}
#access-form p {
font-size: 12px;
color: var(--muted);
line-height: 1.6;
}
input:not([type='file']) { input:not([type='file']) {
width: 100%; width: 100%;
background: var(--bg); background: var(--bg);
@@ -667,10 +653,6 @@ input:not([type='file']) {
line-height: 1.7; line-height: 1.7;
} }
#expiry {
font-variant-numeric: tabular-nums;
}
.dropzone > span, .dropzone > span,
small { small {
font-size: 12px; font-size: 12px;
@@ -886,3 +868,25 @@ small {
font-size: 11px; font-size: 11px;
} }
} }
#pairing {
text-align: center;
padding: 24px 4px;
min-height: 230px;
}
#pairing-detail {
color: var(--muted);
font-size: 14px;
line-height: 1.7;
}
.pairing-symbol {
display: grid;
place-items: center;
width: 56px;
height: 56px;
margin: 0 auto 20px;
border-radius: 18px;
color: var(--violet);
background: #9e82ff12;
font-size: 28px;
}
@@ -0,0 +1,11 @@
package meghdad.pakkit
import android.app.Application
import meghdad.pakkit.data.PackageStore
class PakkitApplication : Application() {
override fun onCreate() {
super.onCreate()
PackageStore(this).clean()
}
}
@@ -5,21 +5,15 @@ import java.io.OutputStream
import java.security.MessageDigest import java.security.MessageDigest
object ApkRules { object ApkRules {
const val MAX_BYTES = 50L * 1024 * 1024
const val TTL_MS = 24L * 60 * 60 * 1000
fun validId(id: String) = fun validId(id: String) =
Regex("[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}").matches(id) Regex("[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}").matches(id)
fun fresh(created: Long, now: Long) = created <= now + 60_000 && now - created < TTL_MS
fun compatibleAbis(packageAbis: Set<String>, deviceAbis: Set<String>) = fun compatibleAbis(packageAbis: Set<String>, deviceAbis: Set<String>) =
packageAbis.isEmpty() || packageAbis.any { it in deviceAbis } packageAbis.isEmpty() || packageAbis.any { it in deviceAbis }
fun copyBounded( fun copyAndHash(
input: InputStream, input: InputStream,
output: OutputStream? = null, output: OutputStream? = null,
max: Long = MAX_BYTES,
): Pair<Long, String> { ): Pair<Long, String> {
val hash = MessageDigest.getInstance("SHA-256") val hash = MessageDigest.getInstance("SHA-256")
val buffer = ByteArray(64 * 1024) val buffer = ByteArray(64 * 1024)
@@ -29,7 +23,6 @@ object ApkRules {
if (count < 0) break if (count < 0) break
if (count == 0) continue if (count == 0) continue
total += count total += count
requireUser(total <= max) { "Choose an APK up to 50 MB." }
hash.update(buffer, 0, count) hash.update(buffer, 0, count)
output?.write(buffer, 0, count) output?.write(buffer, 0, count)
} }
@@ -9,28 +9,14 @@ import java.util.zip.ZipFile
object PackageInspector { object PackageInspector {
@Suppress("DEPRECATION") @Suppress("DEPRECATION")
fun inspect(context: Context, file: File, hash: String): Apk { fun inspect(context: Context, file: File, hash: String): Apk {
requireUser(file.length() in 1..ApkRules.MAX_BYTES) { "Choose an APK up to 50 MB." } requireUser(file.length() > 0) { "This file is empty. Choose another APK." }
val abis = mutableSetOf<String>() val abis = mutableSetOf<String>()
ZipFile(file).use { zip -> ZipFile(file).use { zip ->
requireUser(zip.getEntry("AndroidManifest.xml") != null) { requireUser(zip.getEntry("AndroidManifest.xml") != null) {
"This file is not an Android APK." "This file is not an Android APK."
} }
requireUser(zip.size() < 100_000) { // Inspect directory metadata only; never inflate the package into memory.
"This file is too complex to open. Try another APK."
}
var expanded = 0L
zip.entries().asSequence().forEach { entry -> zip.entries().asSequence().forEach { entry ->
requireUser(entry.size >= 0 && entry.size <= 128L * 1024 * 1024) {
"This app is too large to unpack. Try a smaller APK."
}
expanded += entry.size
requireUser(expanded <= 200L * 1024 * 1024) {
"This app is too large to unpack. Try a smaller APK."
}
if (entry.name == "AndroidManifest.xml")
requireUser(entry.size <= 2 * 1024 * 1024) {
"This file can’t be opened. Try another APK."
}
val parts = entry.name.split('/') val parts = entry.name.split('/')
if (parts.size >= 3 && parts[0] == "lib" && entry.name.endsWith(".so")) if (parts.size >= 3 && parts[0] == "lib" && entry.name.endsWith(".so"))
abis += parts[1] abis += parts[1]
@@ -91,18 +77,17 @@ object PackageInspector {
) )
} }
fun checkForWatch(apk: Apk, sdk: Int, abis: Set<String>, free: Long) { fun checkForWatch(apk: Apk, sdk: Int, abis: Set<String>) {
requireUser(apk.minSdk <= sdk) { requireUser(apk.minSdk <= sdk) {
"This app needs a newer version of Android. Check your watch for updates." "This app needs a newer version of Android. Check your watch for updates."
} }
requireUser(ApkRules.compatibleAbis(apk.abis, abis)) { requireUser(ApkRules.compatibleAbis(apk.abis, abis)) {
"This version doesn’t work on your watch. Try a version made for it." "This version doesn’t work on your watch. Try a version made for it."
} }
requireSpace(apk.bytes, free)
} }
fun requireSpace(bytes: Long, free: Long) { fun requireSpace(bytes: Long, free: Long) {
requireUser(free > bytes * 3 + 20 * 1024 * 1024) { requireUser(bytes > 0 && bytes <= free) {
"Free more storage on your watch, then try again." "Free more storage on your watch, then try again."
} }
} }
@@ -8,4 +8,11 @@ inline fun requireUser(value: Boolean, message: () -> String) {
} }
fun Throwable.userMessage(fallback: String): String = fun Throwable.userMessage(fallback: String): String =
if (this is UserMessage) message ?: fallback else fallback when {
this is UserMessage -> message ?: fallback
generateSequence(this) { it.cause }
.any {
it is android.system.ErrnoException && it.errno == android.system.OsConstants.ENOSPC
} -> "Free some space on your watch, then try again."
else -> fallback
}
@@ -6,6 +6,7 @@ import java.io.File
import meghdad.pakkit.apk.ApkRules import meghdad.pakkit.apk.ApkRules
import meghdad.pakkit.apk.InstallState import meghdad.pakkit.apk.InstallState
import meghdad.pakkit.apk.PendingApk import meghdad.pakkit.apk.PendingApk
import meghdad.pakkit.apk.UserMessage
import org.json.JSONObject import org.json.JSONObject
/** One private package and its review, stored atomically under a stable on-disk schema. */ /** One private package and its review, stored atomically under a stable on-disk schema. */
@@ -38,7 +39,7 @@ class PackageStore(context: Context) {
state = state, state = state,
detail = detail, detail = detail,
sessionId = sessionId ?: current.sessionId, sessionId = sessionId ?: current.sessionId,
), )
) )
true true
} }
@@ -50,19 +51,27 @@ class PackageStore(context: Context) {
check(preferences.edit().remove(PENDING_KEY).commit()) check(preferences.edit().remove(PENDING_KEY).commit())
} }
/** Expiry prevents installation; disk cleanup is intentionally lazy, on the next app launch. */ /** Called at process startup, before any transfer can own an uncommitted file. */
fun clean(now: Long = System.currentTimeMillis()) = fun clean() =
synchronized(lock) { synchronized(lock) {
pending()?.takeUnless { ApkRules.fresh(it.created, now) }?.let { dismiss(it.id) }
val keep = pending()?.id val keep = pending()?.id
directory.listFiles()?.forEach { file -> directory.listFiles()?.forEach { file ->
if (file.name != "$keep.apk" && now - file.lastModified() >= ApkRules.TTL_MS) if (file.name != "$keep.apk") file.delete()
file.delete()
} }
} }
private fun persist(apk: PendingApk) { private fun persist(apk: PendingApk) {
check(preferences.edit().putString(PENDING_KEY, apk.json().toString()).commit()) val previous = preferences.getString(PENDING_KEY, null)
if (!preferences.edit().putString(PENDING_KEY, apk.json().toString()).commit()) {
// SharedPreferences updates memory before its disk write; restore both views on
// failure.
if (!preferences.edit().putString(PENDING_KEY, previous).commit()) {
android.util.Log.w("PakkitStore", "Could not persist review rollback")
}
throw UserMessage(
"Couldn’t save this app. Free some space on your watch and try again."
)
}
} }
companion object { companion object {
@@ -31,21 +31,19 @@ class ApkInstaller(private val context: Context) {
requireUser(context.packageManager.canRequestPackageInstalls()) { requireUser(context.packageManager.canRequestPackageInstalls()) {
"Allow Pakkit to install apps, then try again." "Allow Pakkit to install apps, then try again."
} }
requireUser(ApkRules.fresh(apk.created, System.currentTimeMillis())) {
"This file has expired. Send it again to install."
}
val file = store.file(apk.id) val file = store.file(apk.id)
val digest = file.inputStream().use { ApkRules.copyBounded(it).second } val digest = file.inputStream().use { ApkRules.copyAndHash(it).second }
requireUser(digest == apk.apk.sha256) { requireUser(digest == apk.apk.sha256) {
"This file has changed. Send a fresh copy to install." "This file has changed. Send a fresh copy to install."
} }
val inspected = PackageInspector.inspect(context, file, digest) // Receipt already inspected these bytes; the digest proves they are unchanged.
val inspected = apk.apk
PackageInspector.checkForWatch( PackageInspector.checkForWatch(
inspected, inspected,
Build.VERSION.SDK_INT, Build.VERSION.SDK_INT,
Build.SUPPORTED_ABIS.toSet(), Build.SUPPORTED_ABIS.toSet(),
PackageInspector.free(context),
) )
PackageInspector.requireSpace(file.length(), PackageInspector.free(context))
apk.sessionId?.let { runCatching { installer.abandonSession(it) } } apk.sessionId?.let { runCatching { installer.abandonSession(it) } }
val params = val params =
PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL) PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL)
@@ -0,0 +1,98 @@
package meghdad.pakkit.transfer
import java.security.SecureRandom
import java.util.Base64
import java.util.UUID
/**
* Session-only browser access. Credentials stay in the exact browser origin, never in the product
* UI.
*/
class BrowserAccess(private val changed: (Request?) -> Unit = {}) {
data class Request(val id: String, val label: String, val address: String)
enum class State {
APPROVED,
PENDING,
DENIED,
BUSY,
UNKNOWN,
}
data class Connection(val state: State, val credential: String? = null)
// Unapproved peers share one pending slot. Further records require a watch decision,
// so network traffic alone cannot grow this map. Approvals do not have a time/device quota.
private val decisions = mutableMapOf<String, State>()
private var pending: Pair<String, Request>? = null
@Synchronized
fun state(credential: String?): State =
if (credential == null) State.UNKNOWN else decisions[credential] ?: State.UNKNOWN
@Synchronized
fun connect(credential: String?, label: String, address: String): Connection {
val current = state(credential)
if (current != State.UNKNOWN) return Connection(current)
if (pending != null) return Connection(State.BUSY)
val secret =
Base64.getUrlEncoder()
.withoutPadding()
.encodeToString(ByteArray(32).also { SecureRandom().nextBytes(it) })
val request = Request(UUID.randomUUID().toString(), label, address)
decisions[secret] = State.PENDING
pending = secret to request
changed(request)
return Connection(State.PENDING, secret)
}
@Synchronized
fun answer(id: String, allow: Boolean): Boolean {
val (credential, request) = pending?.takeIf { it.second.id == id } ?: return false
decisions[credential] = if (allow) State.APPROVED else State.DENIED
pending = null
changed(null)
return true
}
@Synchronized
fun retry(credential: String?) {
if (credential != null && state(credential) == State.DENIED) decisions.remove(credential)
}
@Synchronized
fun close() {
decisions.clear()
pending = null
changed(null)
}
companion object {
fun credential(header: String?): String? =
header
?.takeIf { it.startsWith("Bearer ") }
?.removePrefix("Bearer ")
?.takeIf { it.matches(Regex("[A-Za-z0-9_-]{43}")) }
fun label(agent: String): String {
val browser =
when {
"Edg" in agent -> "Edge"
"Firefox" in agent -> "Firefox"
"Chrome" in agent || "CriOS" in agent -> "Chrome"
"Safari" in agent -> "Safari"
else -> "Browser"
}
val device =
when {
"Android" in agent -> "Android"
"iPhone" in agent || "iPad" in agent -> "iOS"
"Windows" in agent -> "Windows"
"Macintosh" in agent -> "Mac"
"Linux" in agent -> "Linux"
else -> null
}
return if (device == null) browser else "$browser on $device"
}
}
}
@@ -1,18 +1,21 @@
package meghdad.pakkit.transfer package meghdad.pakkit.transfer
import java.io.InputStream import java.io.InputStream
import java.security.MessageDigest import java.net.InetAddress
import meghdad.pakkit.apk.ApkRules import java.net.URI
import meghdad.pakkit.apk.requireUser
/** Deliberately small HTTP/1.1 subset: one request per socket, no pipelining or chunked uploads. */ /** Deliberately small HTTP/1.1 subset: one request per socket, no pipelining or chunked uploads. */
object HttpProtocol { object HttpProtocol {
data class Request(val method: String, val path: String, val headers: Map<String, String>) data class Request(val method: String, val path: String, val headers: Map<String, String>)
fun read(input: InputStream): Request { fun read(input: InputStream, clock: () -> Long = System::nanoTime): Request {
val started = clock()
var total = 0 var total = 0
fun line(): String { fun line(): String {
val out = StringBuilder() val out = StringBuilder()
while (true) { while (true) {
require(clock() - started <= 5_000_000_000L) { "Request headers stalled" }
val b = input.read() val b = input.read()
require(b >= 0 && ++total <= 8192) { "Invalid request headers" } require(b >= 0 && ++total <= 8192) { "Invalid request headers" }
if (b == 13) { if (b == 13) {
@@ -41,18 +44,47 @@ object HttpProtocol {
return Request(first[0], first[1], headers) return Request(first[0], first[1], headers)
} }
fun authorized(header: String?, token: String): Boolean = /** Accept only this listener's literal address/port, including equivalent IPv6 spellings. */
MessageDigest.isEqual( fun sameAuthority(authority: String?, address: InetAddress, port: Int): Boolean = runCatching {
(header ?: "").toByteArray(Charsets.UTF_8), if (authority == null) return false
"Bearer $token".toByteArray(Charsets.UTF_8), val uri = URI("http://$authority")
if (
uri.rawUserInfo != null ||
!uri.rawPath.isNullOrEmpty() ||
uri.rawQuery != null ||
uri.rawFragment != null ||
uri.port != port
) )
return false
val host = uri.host?.removeSurrounding("[", "]") ?: return false
val parsed =
if (':' in host && host.matches(Regex("[0-9a-fA-F:.]+"))) {
InetAddress.getByName(
host
) // A colon-containing numeric literal cannot trigger DNS.
} else {
val parts = host.split('.')
if (
parts.size != 4 ||
parts.any {
it.isEmpty() ||
!it.all(Char::isDigit) ||
(it.toIntOrNull() ?: -1) !in 0..255
}
)
return false
InetAddress.getByAddress(parts.map { it.toInt().toByte() }.toByteArray())
}
parsed == address
}
.getOrDefault(false)
fun uploadLength(headers: Map<String, String>): Long { fun uploadLength(headers: Map<String, String>): Long {
require(headers["content-type"] == "application/octet-stream") { "Send a complete APK" } require(headers["content-type"] == "application/octet-stream") { "Send a complete APK" }
val raw = headers["content-length"] ?: error("Content length required") val raw = headers["content-length"] ?: error("Content length required")
require(raw.matches(Regex("[0-9]+"))) { "Invalid content length" } require(raw.matches(Regex("[0-9]+"))) { "Invalid content length" }
val size = raw.toLongOrNull() ?: error("Invalid content length") val size = raw.toLongOrNull() ?: error("Invalid content length")
require(size in 1..ApkRules.MAX_BYTES) { "Choose an APK up to 50 MiB" } requireUser(size > 0) { "This file is empty. Choose another APK." }
return size return size
} }
} }
@@ -1,19 +1,19 @@
package meghdad.pakkit.transfer package meghdad.pakkit.transfer
import android.annotation.SuppressLint
import android.content.Context import android.content.Context
import android.os.Build import android.os.Build
import android.os.SystemClock import android.os.PowerManager
import android.util.Base64
import java.io.BufferedInputStream import java.io.BufferedInputStream
import java.io.Closeable import java.io.Closeable
import java.io.File import java.io.File
import java.io.IOException import java.io.IOException
import java.io.InputStream import java.io.InputStream
import java.net.Inet4Address import java.net.Inet6Address
import java.net.InetAddress
import java.net.InetSocketAddress import java.net.InetSocketAddress
import java.net.ServerSocket import java.net.ServerSocket
import java.net.Socket import java.net.Socket
import java.security.SecureRandom
import java.util.UUID import java.util.UUID
import java.util.concurrent.ArrayBlockingQueue import java.util.concurrent.ArrayBlockingQueue
import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ConcurrentHashMap
@@ -22,8 +22,10 @@ import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicBoolean
import meghdad.pakkit.apk.ApkRules import meghdad.pakkit.apk.ApkRules
import meghdad.pakkit.apk.InstallState
import meghdad.pakkit.apk.PackageInspector import meghdad.pakkit.apk.PackageInspector
import meghdad.pakkit.apk.PendingApk import meghdad.pakkit.apk.PendingApk
import meghdad.pakkit.apk.requireUser
import meghdad.pakkit.apk.userMessage import meghdad.pakkit.apk.userMessage
import meghdad.pakkit.data.PackageStore import meghdad.pakkit.data.PackageStore
import org.json.JSONObject import org.json.JSONObject
@@ -31,27 +33,32 @@ import org.json.JSONObject
/** Bounded HTTP endpoint. Wi-Fi acquisition, notifications and power belong to ReceiveService. */ /** Bounded HTTP endpoint. Wi-Fi acquisition, notifications and power belong to ReceiveService. */
class LocalHttpServer( class LocalHttpServer(
private val context: Context, private val context: Context,
address: Inet4Address, private val address: InetAddress,
private val deadline: Long,
private val owner: Any, private val owner: Any,
private val access: BrowserAccess = BrowserAccess(),
) : Closeable { ) : Closeable {
private val store = PackageStore(context) private val store = PackageStore(context)
private val listener = private val listener =
ServerSocket().apply { ServerSocket().also { socket ->
reuseAddress = true try {
bind(InetSocketAddress(address, 0), 4) socket.reuseAddress = true
socket.bind(InetSocketAddress(address, PORT), 4)
} catch (error: Exception) {
runCatching { socket.close() }
throw error
}
} }
private val workers = ThreadPoolExecutor(2, 2, 0, TimeUnit.SECONDS, ArrayBlockingQueue(4)) private val workers = ThreadPoolExecutor(2, 2, 0, TimeUnit.SECONDS, ArrayBlockingQueue(4))
private val sockets = ConcurrentHashMap.newKeySet<Socket>() private val sockets = ConcurrentHashMap.newKeySet<Socket>()
private val uploading = AtomicBoolean(false) private val uploading = AtomicBoolean(false)
private val closed = AtomicBoolean(false) private val closed = AtomicBoolean(false)
private val token = private val commitLock = Any()
Base64.encodeToString( private val host =
ByteArray(24).also { SecureRandom().nextBytes(it) }, address.hostAddress.orEmpty().substringBefore('%').let {
Base64.URL_SAFE or Base64.NO_WRAP or Base64.NO_PADDING, if (address is Inet6Address) "[$it]" else it
) }
private val authority = "${address.hostAddress}:${listener.localPort}" private val authority = "$host:${listener.localPort}"
val url = "http://$authority/#$token" val url = "http://$authority/"
fun start() { fun start() {
Thread( Thread(
@@ -93,11 +100,11 @@ class LocalHttpServer(
val response = Response(socket) val response = Response(socket)
try { try {
val input = BufferedInputStream(socket.getInputStream(), 8192) val input = BufferedInputStream(socket.getInputStream(), 8192)
socket.soTimeout = 5_000
val request = HttpProtocol.read(input) val request = HttpProtocol.read(input)
check(!closed.get() && SystemClock.elapsedRealtime() < deadline) { socket.soTimeout = 15_000
"Receiving has ended. Open a fresh link from your watch." requireUser(!closed.get()) { "Receiving has stopped. Open Pakkit to start again." }
} if (!HttpProtocol.sameAuthority(request.headers["host"], address, PORT)) {
if (request.headers["host"] != authority) {
response.error(403, "Open the address shown on your watch.") response.error(403, "Open the address shown on your watch.")
return return
} }
@@ -110,18 +117,37 @@ class LocalHttpServer(
) )
return return
} }
if (!HttpProtocol.authorized(request.headers["authorization"], token)) { if (request.method == "POST" && !validOrigin(request.headers["origin"])) {
response.error(403, "Open the private link or scan the QR code on your watch.") response.error(403, "Open the address shown on your watch to send an app.")
return
}
val credential = BrowserAccess.credential(request.headers["authorization"])
if (request.method == "POST" && request.path in setOf("/api/connect", "/api/retry")) {
if (request.path == "/api/retry") access.retry(credential)
val connection =
access.connect(
credential,
BrowserAccess.label(request.headers["user-agent"].orEmpty()),
socket.inetAddress.hostAddress.orEmpty(),
)
response.json(
200,
JSONObject().put("connection", connection.state.name.lowercase()).apply {
connection.credential?.let { put("credential", it) }
},
)
return
}
val browser = access.state(credential)
if (browser != BrowserAccess.State.APPROVED) {
response.json(403, JSONObject().put("connection", browser.name.lowercase()))
return return
} }
when { when {
request.method == "GET" && request.path == "/api/status" -> request.method == "GET" && request.path == "/api/status" ->
response.json(200, status()) response.json(200, status())
request.method == "POST" && request.path == "/api/upload" -> { request.method == "POST" && request.path == "/api/upload" ->
if (request.headers["origin"] != "http://$authority") upload(request, input, response)
response.error(403, "Open the link shown on your watch to send an app.")
else upload(request, input, response)
}
else -> response.error(404, "Not found") else -> response.error(404, "Not found")
} }
} catch (error: Exception) { } catch (error: Exception) {
@@ -135,6 +161,10 @@ class LocalHttpServer(
} }
} }
private fun validOrigin(origin: String?): Boolean =
origin?.startsWith("http://") == true &&
HttpProtocol.sameAuthority(origin.removePrefix("http://"), address, PORT)
private fun status(): JSONObject { private fun status(): JSONObject {
val pending = store.pending() val pending = store.pending()
val live = Receiving.state val live = Receiving.state
@@ -144,9 +174,12 @@ class LocalHttpServer(
.put("label", pending?.apk?.label.orEmpty()) .put("label", pending?.apk?.label.orEmpty())
.put("received", live.received) .put("received", live.received)
.put("total", live.total) .put("total", live.total)
.put("expiresIn", ((deadline - SystemClock.elapsedRealtime()) / 1000).coerceAtLeast(0)) .put("connection", "approved")
} }
// The read-idle socket timeout and close() bound stalled I/O; no total transfer deadline.
// Release in finally also covers validation failures, cancellation and running out of space.
@SuppressLint("WakelockTimeout")
private fun upload(request: HttpProtocol.Request, input: InputStream, response: Response) { private fun upload(request: HttpProtocol.Request, input: InputStream, response: Response) {
val length = HttpProtocol.uploadLength(request.headers) val length = HttpProtocol.uploadLength(request.headers)
if (!uploading.compareAndSet(false, true)) { if (!uploading.compareAndSet(false, true)) {
@@ -154,46 +187,60 @@ class LocalHttpServer(
return return
} }
var partial: File? = null var partial: File? = null
val wake =
context
.getSystemService(PowerManager::class.java)
.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "pakkit:upload")
try { try {
store
.pending()
?.takeIf { it.state in setOf(InstallState.INSTALLED, InstallState.FAILED) }
?.let { store.dismiss(it.id) }
if (store.pending() != null) { if (store.pending() != null) {
response.error(409, "Finish with the app on your watch before sending another.") response.error(409, "Finish with the app on your watch before sending another.")
return return
} }
PackageInspector.requireSpace(length, PackageInspector.free(context)) PackageInspector.requireSpace(length, PackageInspector.free(context))
val id = UUID.randomUUID().toString() wake.acquire()
val file = store.file(id) try {
partial = file val id = UUID.randomUUID().toString()
Receiving.update(owner) { val file = store.file(id)
it.copy(detail = "Your app is on its way…", total = length, received = 0) partial = file
} updateLive {
val body = it.copy(detail = "Your app is on its way…", total = length, received = 0)
UploadBody( }
input, val body =
length, UploadBody(
progress = { received -> input,
Receiving.update(owner) { it.copy(received = received) } length,
}, progress = { received ->
updateLive { it.copy(received = received) }
},
)
val digest = file.outputStream().use { ApkRules.copyAndHash(body, it).second }
updateLive { it.copy(detail = "Getting your app ready…") }
val apk = PackageInspector.inspect(context, file, digest)
PackageInspector.checkForWatch(
apk,
Build.VERSION.SDK_INT,
Build.SUPPORTED_ABIS.toSet(),
) )
val digest = file.outputStream().use { ApkRules.copyBounded(body, it).second } synchronized(commitLock) {
Receiving.update(owner) { it.copy(detail = "Getting your app ready…") } requireUser(!closed.get()) {
val apk = PackageInspector.inspect(context, file, digest) "Receiving has stopped. Start again to send this app."
PackageInspector.checkForWatch( }
apk, store.stage(PendingApk(id, System.currentTimeMillis(), apk))
Build.VERSION.SDK_INT, }
Build.SUPPORTED_ABIS.toSet(), partial = null
PackageInspector.free(context), updateLive { it.copy(detail = "Ready to install") }
) response.json(200, JSONObject().put("label", apk.label).put("state", "ready"))
check(!closed.get() && SystemClock.elapsedRealtime() < deadline) { } finally {
"Receiving has ended. Open a fresh link from your watch." wake.release()
} }
store.stage(PendingApk(id, System.currentTimeMillis(), apk))
partial = null
Receiving.update(owner) { it.copy(detail = "Ready to install") }
response.json(200, JSONObject().put("label", apk.label).put("state", "ready"))
} finally { } finally {
partial?.delete() partial?.delete()
uploading.set(false) uploading.set(false)
Receiving.update(owner) { updateLive {
it.copy( it.copy(
received = 0, received = 0,
total = 0, total = 0,
@@ -204,8 +251,16 @@ class LocalHttpServer(
} }
} }
private fun updateLive(change: (Receiving.State) -> Receiving.State) {
synchronized(commitLock) {
if (!closed.get()) Receiving.update(owner, change)
}
}
override fun close() { override fun close() {
if (!closed.compareAndSet(false, true)) return synchronized(commitLock) {
if (!closed.compareAndSet(false, true)) return
}
try { try {
listener.close() listener.close()
} finally { } finally {
@@ -252,6 +307,7 @@ class LocalHttpServer(
} }
companion object { companion object {
const val PORT = 8787
private val ASSETS = private val ASSETS =
mapOf( mapOf(
"/" to ("index.html" to "text/html; charset=utf-8"), "/" to ("index.html" to "text/html; charset=utf-8"),
@@ -14,48 +14,58 @@ import android.net.NetworkCapabilities
import android.net.NetworkRequest import android.net.NetworkRequest
import android.os.Handler import android.os.Handler
import android.os.Looper import android.os.Looper
import android.os.PowerManager import java.net.BindException
import android.os.SystemClock
import java.net.Inet4Address import java.net.Inet4Address
import java.net.InetAddress
import meghdad.pakkit.R import meghdad.pakkit.R
import meghdad.pakkit.ui.WatchActivity import meghdad.pakkit.ui.WatchActivity
/** Owns the user-started session and releases all network/power resources on every exit path. */ /** User-controlled receiving; network loss suspends the listener, never the user's intent. */
class ReceiveService : Service() { class ReceiveService : Service() {
private val main = Handler(Looper.getMainLooper()) private val main = Handler(Looper.getMainLooper())
private val connectivity by lazy { getSystemService(ConnectivityManager::class.java) } private val connectivity by lazy { getSystemService(ConnectivityManager::class.java) }
private var server: LocalHttpServer? = null private var server: LocalHttpServer? = null
private var network: Network? = null private var network: Network? = null
private var address: Inet4Address? = null private var address: InetAddress? = null
private var registered = false private var registered = false
private var ended = false private var ended = false
private var deadline = 0L private val access = BrowserAccess { request ->
private var wake: PowerManager.WakeLock? = null Receiving.update(this) { it.copy(browserRequest = request) }
}
private val callback = private val callback =
object : ConnectivityManager.NetworkCallback() { object : ConnectivityManager.NetworkCallback() {
override fun onLinkPropertiesChanged(network: Network, properties: LinkProperties) { override fun onLinkPropertiesChanged(network: Network, properties: LinkProperties) {
main.post { main.post {
if (ended) return@post if (ended) return@post
if (this@ReceiveService.network == null) { val candidates =
if (properties.linkAddresses.isNotEmpty()) open(network, properties) properties.linkAddresses
} else if ( .map { it.address }
this@ReceiveService.network == network && .filter {
properties.linkAddresses.none { it.address == address } !it.isLoopbackAddress &&
) { !it.isAnyLocalAddress &&
finish("Wi-Fi changed. Ready to reconnect?") !it.isMulticastAddress
}
val ipv4 =
candidates.firstOrNull { it is Inet4Address }
?: candidates.firstOrNull { !it.isLinkLocalAddress }
if (ipv4 == null) {
if (network == this@ReceiveService.network) suspendListener()
return@post
} }
if (server != null && network == this@ReceiveService.network && ipv4 == address)
return@post
open(network, ipv4)
} }
} }
override fun onLost(network: Network) { override fun onLost(network: Network) {
main.post { main.post {
if (network == this@ReceiveService.network) if (!ended && network == this@ReceiveService.network) suspendListener()
finish("Wi-Fi disconnected. Ready to reconnect?")
} }
} }
override fun onUnavailable() { override fun onUnavailable() {
main.post { finish("Connect your watch to Wi-Fi, then try again.") } main.post { if (!ended) suspendListener() }
} }
} }
@@ -63,17 +73,13 @@ class ReceiveService : Service() {
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent?.action == STOP) { if (intent?.action == STOP) {
finish("Session ended") finish("Receiving stopped")
return START_NOT_STICKY return START_NOT_STICKY
} }
if (registered || ended) return START_NOT_STICKY if (registered || ended) return START_NOT_STICKY
val manager = getSystemService(NotificationManager::class.java) val manager = getSystemService(NotificationManager::class.java)
manager.createNotificationChannel( manager.createNotificationChannel(
NotificationChannel( NotificationChannel("receive", "App transfers", NotificationManager.IMPORTANCE_LOW)
"receive",
"App transfers",
NotificationManager.IMPORTANCE_LOW,
),
) )
val open = val open =
PendingIntent.getActivity( PendingIntent.getActivity(
@@ -92,20 +98,18 @@ class ReceiveService : Service() {
val notification = val notification =
Notification.Builder(this, "receive") Notification.Builder(this, "receive")
.setSmallIcon(R.drawable.pakkit_mark) .setSmallIcon(R.drawable.pakkit_mark)
.setContentTitle("Ready for your next app") .setContentTitle("Receiving is on")
.setContentText("Open Pakkit to connect your browser.") .setContentText("Open Pakkit to connect your browser.")
.setContentIntent(open) .setContentIntent(open)
.setOngoing(true) .setOngoing(true)
.addAction(Notification.Action.Builder(null, "End session", stop).build()) .addAction(Notification.Action.Builder(null, "Stop receiving", stop).build())
.build() .build()
startForeground( startForeground(
NOTIFICATION, NOTIFICATION,
notification, notification,
ServiceInfo.FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE, ServiceInfo.FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE,
) )
Receiving.begin(this) Receiving.begin(this, access)
deadline = SystemClock.elapsedRealtime() + DURATION_MS
main.postDelayed({ finish("Time’s up. Ready for another app?") }, DURATION_MS)
try { try {
registered = true registered = true
connectivity.requestNetwork( connectivity.requestNetwork(
@@ -114,35 +118,41 @@ class ReceiveService : Service() {
.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.build(), .build(),
callback, callback,
25_000,
) )
} catch (_: Exception) { } catch (error: Exception) {
android.util.Log.w("PakkitReceive", "Cannot request Wi-Fi", error)
finish("Can’t reach Wi-Fi. Check your watch’s connection.") finish("Can’t reach Wi-Fi. Check your watch’s connection.")
} }
// A killed process does not silently reopen network access. The user starts it again.
return START_NOT_STICKY return START_NOT_STICKY
} }
private fun open(network: Network, properties: LinkProperties) { private fun open(network: Network, address: InetAddress) {
suspendListener()
this.network = network
this.address = address
try { try {
val address = val listener = LocalHttpServer(applicationContext, address, this, access)
properties.linkAddresses
.map { it.address }
.filterIsInstance<Inet4Address>()
.firstOrNull { it.isSiteLocalAddress }
?: error("A private IPv4 Wi-Fi address is required")
this.network = network
this.address = address
val listener = LocalHttpServer(applicationContext, address, deadline, this)
server = listener server = listener
wake =
getSystemService(PowerManager::class.java)
.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "pakkit:receive")
.apply { acquire((deadline - SystemClock.elapsedRealtime()).coerceAtLeast(1)) }
listener.start() listener.start()
Receiving.update(this) { it.copy(url = listener.url, detail = "Ready to receive") } Receiving.update(this) { it.copy(url = listener.url, detail = "Ready to receive") }
} catch (error: Exception) { } catch (error: Exception) {
android.util.Log.w("PakkitReceive", "Cannot open receiving session", error) android.util.Log.w("PakkitReceive", "Cannot open receiver", error)
finish("Couldn’t connect. Check Wi-Fi and try again.") finish(
if (error is BindException)
"Port ${LocalHttpServer.PORT} is in use. Close the other receiver and try again."
else "Couldn’t connect. Check Wi-Fi and try again."
)
}
}
private fun suspendListener() {
server?.close()
server = null
network = null
address = null
Receiving.update(this) {
it.copy(url = null, received = 0, total = 0, detail = "Waiting for Wi-Fi…")
} }
} }
@@ -160,19 +170,21 @@ class ReceiveService : Service() {
server = null server = null
if (registered) runCatching { connectivity.unregisterNetworkCallback(callback) } if (registered) runCatching { connectivity.unregisterNetworkCallback(callback) }
registered = false registered = false
wake?.let { if (it.isHeld) it.release() } access.close()
wake = null
Receiving.end(this, message) Receiving.end(this, message)
} }
override fun onTimeout(startId: Int, fgsType: Int) {
finish("Your watch paused receiving. Open Pakkit to start again.")
}
override fun onDestroy() { override fun onDestroy() {
ended = true ended = true
release("Session ended") release("Receiving stopped")
super.onDestroy() super.onDestroy()
} }
companion object { companion object {
const val DURATION_MS = 10 * 60 * 1000L
const val STOP = "stop" const val STOP = "stop"
private const val NOTIFICATION = 81 private const val NOTIFICATION = 81
} }
@@ -4,14 +4,13 @@ import android.os.Handler
import android.os.Looper import android.os.Looper
import java.util.concurrent.CopyOnWriteArraySet import java.util.concurrent.CopyOnWriteArraySet
/** /** Live session state is never persisted: process death revokes browser approvals. */
* Live session state is never persisted: process death immediately invalidates its private link.
*/
object Receiving { object Receiving {
data class State( data class State(
val active: Boolean = false, val active: Boolean = false,
val url: String? = null, val url: String? = null,
val detail: String = "Connect your watch and browser to the same Wi-Fi.", val detail: String = "Connect your watch and browser to the same Wi-Fi.",
val browserRequest: BrowserAccess.Request? = null,
val received: Long = 0, val received: Long = 0,
val total: Long = 0, val total: Long = 0,
) )
@@ -21,6 +20,7 @@ object Receiving {
private set private set
private var owner: Any? = null private var owner: Any? = null
private var access: BrowserAccess? = null
private val listeners = CopyOnWriteArraySet<() -> Unit>() private val listeners = CopyOnWriteArraySet<() -> Unit>()
private val main = Handler(Looper.getMainLooper()) private val main = Handler(Looper.getMainLooper())
private val notify = Runnable { listeners.forEach { it() } } private val notify = Runnable { listeners.forEach { it() } }
@@ -34,7 +34,8 @@ object Receiving {
} }
@Synchronized @Synchronized
fun begin(owner: Any) { fun begin(owner: Any, access: BrowserAccess? = null) {
this.access = access
this.owner = owner this.owner = owner
publish(State(active = true, detail = "Connecting to Wi-Fi…")) publish(State(active = true, detail = "Connecting to Wi-Fi…"))
} }
@@ -48,9 +49,15 @@ object Receiving {
fun end(owner: Any, detail: String) { fun end(owner: Any, detail: String) {
if (this.owner !== owner) return if (this.owner !== owner) return
this.owner = null this.owner = null
this.access = null
publish(State(detail = detail)) publish(State(detail = detail))
} }
fun answerBrowser(id: String, allow: Boolean): Boolean {
val current = synchronized(this) { access }
return current?.answer(id, allow) ?: false
}
private fun publish(state: State) { private fun publish(state: State) {
this.state = state this.state = state
main.removeCallbacks(notify) main.removeCallbacks(notify)
@@ -19,12 +19,13 @@ import android.widget.TextClock
import java.util.concurrent.Executors import java.util.concurrent.Executors
import kotlin.math.roundToInt import kotlin.math.roundToInt
import meghdad.pakkit.R import meghdad.pakkit.R
import meghdad.pakkit.apk.ApkRules
import meghdad.pakkit.apk.InstallState import meghdad.pakkit.apk.InstallState
import meghdad.pakkit.apk.PendingApk import meghdad.pakkit.apk.PendingApk
import meghdad.pakkit.apk.userMessage
import meghdad.pakkit.data.PackageStore import meghdad.pakkit.data.PackageStore
import meghdad.pakkit.install.ApkInstaller import meghdad.pakkit.install.ApkInstaller
import meghdad.pakkit.install.PendingApproval import meghdad.pakkit.install.PendingApproval
import meghdad.pakkit.transfer.BrowserAccess
import meghdad.pakkit.transfer.ReceiveService import meghdad.pakkit.transfer.ReceiveService
import meghdad.pakkit.transfer.Receiving import meghdad.pakkit.transfer.Receiving
@@ -38,31 +39,26 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
private var busy = false private var busy = false
private var error: String? = null private var error: String? = null
private var renderedState = "" private var renderedState = ""
private var showingLink = false private var resumed = false
private var backRegistered = false private var approvalLaunched: Int? = null
private val linkBack = private var requestedInstallId: String? = null
if (Build.VERSION.SDK_INT >= 33)
android.window.OnBackInvokedCallback {
showingLink = false
refresh()
}
else null
private var qrUrl = "" private var qrUrl = ""
private var qrBitmap: android.graphics.Bitmap? = null private var qrBitmap: android.graphics.Bitmap? = null
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
store = PackageStore(this) store = PackageStore(this)
store.clean()
acceptIntent(intent) acceptIntent(intent)
showingLink = savedInstanceState?.getBoolean("showingLink") ?: false requestedInstallId = savedInstanceState?.getString("requestedInstallId")
approvalLaunched = savedInstanceState?.getInt("approvalLaunched", -1)?.takeIf { it >= 0 }
refresh() refresh()
savedInstanceState?.getInt("scroll")?.let { y -> scroll.post { scroll.scrollTo(0, y) } } savedInstanceState?.getInt("scroll")?.let { y -> scroll.post { scroll.scrollTo(0, y) } }
} }
override fun onSaveInstanceState(outState: Bundle) { override fun onSaveInstanceState(outState: Bundle) {
outState.putInt("scroll", scroll.scrollY) outState.putInt("scroll", scroll.scrollY)
outState.putBoolean("showingLink", showingLink) outState.putString("requestedInstallId", requestedInstallId)
approvalLaunched?.let { outState.putInt("approvalLaunched", it) }
super.onSaveInstanceState(outState) super.onSaveInstanceState(outState)
} }
@@ -89,21 +85,25 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
override fun onResume() { override fun onResume() {
super.onResume() super.onResume()
resumed = true
store.preferences.registerOnSharedPreferenceChangeListener(this) store.preferences.registerOnSharedPreferenceChangeListener(this)
Receiving.observe(sessionObserver) Receiving.observe(sessionObserver)
refresh() refresh()
val requested = requestedInstallId
requestedInstallId = null
if (requested != null && packageManager.canRequestPackageInstalls()) {
store.pending()?.takeIf { it.id == requested }?.let { install(it) }
}
} }
override fun onPause() { override fun onPause() {
resumed = false
Receiving.removeObserver(sessionObserver) Receiving.removeObserver(sessionObserver)
store.preferences.unregisterOnSharedPreferenceChangeListener(this) store.preferences.unregisterOnSharedPreferenceChangeListener(this)
super.onPause() super.onPause()
} }
override fun onDestroy() { override fun onDestroy() {
if (Build.VERSION.SDK_INT >= 33 && backRegistered) {
onBackInvokedDispatcher.unregisterOnBackInvokedCallback(requireNotNull(linkBack))
}
io.shutdown() io.shutdown()
super.onDestroy() super.onDestroy()
} }
@@ -198,29 +198,17 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
if (isDestroyed || isFinishing) return if (isDestroyed || isFinishing) return
val job = store.pending() val job = store.pending()
val live = Receiving.state val live = Receiving.state
if (live.url == null || job != null || live.total > 0) showingLink = false
val stateKey = val stateKey =
job?.let { "${it.id}:${it.state}" } live.browserRequest?.let { "browser:${it.id}" }
?: job?.let { "${it.id}:${it.state}" }
?: when { ?: when {
showingLink && live.url != null -> "link"
live.total > 0 -> "uploading" live.total > 0 -> "uploading"
live.url != null -> "receiving" live.url != null -> "receiving"
live.active -> "connecting" live.active -> "connecting"
else -> "home" else -> "home"
} }
if (Build.VERSION.SDK_INT >= 33) {
val handleBack = showingLink && job == null && live.url != null && live.total == 0L
if (handleBack && !backRegistered) {
onBackInvokedDispatcher.registerOnBackInvokedCallback(
android.window.OnBackInvokedDispatcher.PRIORITY_DEFAULT,
requireNotNull(linkBack),
)
} else if (!handleBack && backRegistered) {
onBackInvokedDispatcher.unregisterOnBackInvokedCallback(requireNotNull(linkBack))
}
backRegistered = handleBack
}
val previousState = renderedState val previousState = renderedState
if (stateKey != previousState) error = null
val y = if (::scroll.isInitialized && stateKey == renderedState) scroll.scrollY else 0 val y = if (::scroll.isInitialized && stateKey == renderedState) scroll.scrollY else 0
renderedState = stateKey renderedState = stateKey
scroll = RoundScrollView(this).apply { setBackgroundColor(colors.canvas) } scroll = RoundScrollView(this).apply { setBackgroundColor(colors.canvas) }
@@ -247,16 +235,20 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
} }
) )
if (job == null) home() error?.let { add(line(it, 13f, colors.error), 12) }
if (live.browserRequest != null) browserRequest(live.browserRequest)
else if (job == null) home()
else { else {
incoming(job) incoming(job)
if (Receiving.state.url != null) if (live.active) {
button(getString(R.string.watch_end_session), false) { button(getString(R.string.watch_end_session), false) {
stopService(Intent(this, ReceiveService::class.java)) stopService(Intent(this, ReceiveService::class.java))
refresh()
} }
} else {
button(getString(R.string.watch_start_receiving), false) { startReceiving() }
}
} }
error?.let { add(line(it, 13f, colors.error), 12) }
scroll.isFocusable = true scroll.isFocusable = true
scroll.isFocusableInTouchMode = true scroll.isFocusableInTouchMode = true
setContentView(scroll) setContentView(scroll)
@@ -269,17 +261,31 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
column.alpha = 0f column.alpha = 0f
column.animate().alpha(1f).setDuration(180).start() column.animate().alpha(1f).setDuration(180).start()
} }
scroll.post { scroll.scrollTo(0, y) } scroll.post {
scroll.scrollTo(0, y)
val approval = PendingApproval.intent
if (
resumed &&
job?.state == InstallState.CONFIRM &&
job.sessionId != null &&
PendingApproval.id == job.id &&
approval != null &&
approvalLaunched != job.sessionId
) {
approvalLaunched = job.sessionId
runCatching { startActivity(approval) }
.onFailure {
error = getString(R.string.watch_approval_error)
refresh()
}
}
}
} }
private fun home() { private fun home() {
val live = Receiving.state val live = Receiving.state
val url = live.url val url = live.url
if (url != null) { if (url != null) {
if (showingLink && live.total == 0L) {
showLink(url)
return
}
if (live.total > 0) { if (live.total > 0) {
parcel(48) parcel(48)
val percent = (live.received * 100 / live.total).coerceAtMost(100) val percent = (live.received * 100 / live.total).coerceAtMost(100)
@@ -356,11 +362,13 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
) )
add(line(getString(R.string.watch_scan_to_send), 20f, bold = true), 12) add(line(getString(R.string.watch_scan_to_send), 20f, bold = true), 12)
add(line(getString(R.string.watch_scan_description), 13f, colors.secondary), 8) add(line(getString(R.string.watch_scan_description), 13f, colors.secondary), 8)
add(line(getString(R.string.watch_ready_for_10_minutes), 12f, colors.mint), 10) add(
button(getString(R.string.watch_view_link), false) { line(url, 12f, colors.mint).apply {
showingLink = true textDirection = View.TEXT_DIRECTION_LTR
refresh() setTextIsSelectable(true)
} },
10,
)
} }
button(getString(R.string.watch_end_session), false) { button(getString(R.string.watch_end_session), false) {
stopService(Intent(this, ReceiveService::class.java)) stopService(Intent(this, ReceiveService::class.java))
@@ -387,60 +395,49 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
) )
if (live.active) { if (live.active) {
badge(getString(R.string.watch_finding_wi_fi)) badge(getString(R.string.watch_finding_wi_fi))
add(line(getString(R.string.watch_connecting_description), 13f, colors.secondary), 12) add(line(live.detail, 13f, colors.secondary), 12)
button(getString(R.string.watch_cancel), false) { button(getString(R.string.watch_end_session), false) {
stopService(Intent(this, ReceiveService::class.java)) stopService(Intent(this, ReceiveService::class.java))
} }
} else { } else {
button(getString(R.string.watch_start_receiving)) { button(getString(R.string.watch_start_receiving)) { startReceiving() }
error = null
runCatching { startForegroundService(Intent(this, ReceiveService::class.java)) }
.onFailure {
error = getString(R.string.watch_connection_error)
refresh()
}
}
add(line(getString(R.string.brand_tagline), 12f, colors.accent), 14) add(line(getString(R.string.brand_tagline), 12f, colors.accent), 14)
if (live.detail != Receiving.State().detail) if (live.detail != Receiving.State().detail && live.detail != "Receiving stopped")
add(line(live.detail, 13f, colors.secondary), 12) add(line(live.detail, 13f, colors.secondary), 12)
button(getString(R.string.watch_wi_fi), false) { }
runCatching { button(getString(R.string.watch_wi_fi), false) {
startActivity(Intent(android.provider.Settings.ACTION_WIFI_SETTINGS)) runCatching {
} startActivity(Intent(android.provider.Settings.ACTION_WIFI_SETTINGS))
.onFailure {
error = getString(R.string.watch_wifi_unavailable)
refresh()
}
} }
.onFailure {
error = getString(R.string.watch_wifi_unavailable)
refresh()
}
} }
} }
private fun showLink(url: String) { private fun startReceiving() {
add(line(getString(R.string.watch_your_watch_link), 20f, bold = true), 14) error = null
add(line(getString(R.string.watch_link_description), 13f, colors.secondary), 12) runCatching { startForegroundService(Intent(this, ReceiveService::class.java)) }
add( .onFailure {
line(url, 12f, colors.mint).apply { error = getString(R.string.watch_connection_error)
textDirection = View.TEXT_DIRECTION_LTR refresh()
setTextIsSelectable(true) }
},
14,
)
add(line(getString(R.string.watch_connection_privacy), 12f, colors.secondary), 14)
button(getString(R.string.watch_back_to_code), false) {
showingLink = false
refresh()
}
} }
// Android 12 uses this callback; Android 13+ registers the platform callback above. private fun browserRequest(request: BrowserAccess.Request) {
@Suppress("DEPRECATION") add(line(getString(R.string.watch_connect_browser), 21f, bold = true), 8)
@android.annotation.SuppressLint("GestureBackNavigation") add(line(request.label, 15f, colors.secondary), 10)
@Deprecated("Legacy callback for Android 12") add(line(request.address, 12f, colors.secondary), 5)
override fun onBackPressed() { button(getString(R.string.watch_allow_browser)) {
if (showingLink) { Receiving.answerBrowser(request.id, true)
showingLink = false }
refresh() button(getString(R.string.watch_not_now), false) {
} else super.onBackPressed() Receiving.answerBrowser(request.id, false)
}
button(getString(R.string.watch_end_session), false) {
stopService(Intent(this, ReceiveService::class.java))
}
} }
private fun incoming(job: PendingApk) { private fun incoming(job: PendingApk) {
@@ -481,25 +478,7 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
when (state) { when (state) {
InstallState.READY, InstallState.READY,
InstallState.FAILED -> { InstallState.FAILED -> {
if (!ApkRules.fresh(job.created, System.currentTimeMillis())) { if (store.file(job.id).exists()) {
add(
line(
getString(R.string.watch_file_expired),
13f,
colors.error,
),
12,
)
} else if (store.file(job.id).exists()) {
if (!apk.wear)
add(
line(
getString(R.string.watch_fit_notice),
12f,
colors.error,
),
10,
)
if (packageManager.canRequestPackageInstalls()) if (packageManager.canRequestPackageInstalls())
button( button(
if (state == InstallState.FAILED) getString(R.string.watch_try_again) if (state == InstallState.FAILED) getString(R.string.watch_try_again)
@@ -516,11 +495,13 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
), ),
10, 10,
) )
button(getString(R.string.watch_allow_installs)) { settings() } button(getString(R.string.watch_allow_installs)) {
requestedInstallId = job.id
settings()
}
button(getString(R.string.watch_google_play), false) { play() } button(getString(R.string.watch_google_play), false) { play() }
} }
} }
add(line(getString(R.string.watch_trust_notice), 12f, colors.secondary), 10)
button(getString(R.string.watch_remove_file), false) { dismiss(job) } button(getString(R.string.watch_remove_file), false) { dismiss(job) }
} }
InstallState.CONFIRM -> { InstallState.CONFIRM -> {
@@ -589,6 +570,7 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
private fun settings() { private fun settings() {
runCatching { startActivity(ApkInstaller.settings(this)) } runCatching { startActivity(ApkInstaller.settings(this)) }
.onFailure { .onFailure {
requestedInstallId = null
error = getString(R.string.watch_permission_unavailable) error = getString(R.string.watch_permission_unavailable)
refresh() refresh()
} }
@@ -604,8 +586,11 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
error = null error = null
refresh() refresh()
io.execute { io.execute {
ApkInstaller(applicationContext).install(job) val result = runCatching { ApkInstaller(applicationContext).install(job) }
runOnUiThread { runOnUiThread {
result.exceptionOrNull()?.let {
error = it.userMessage(getString(R.string.watch_save_error))
}
busy = false busy = false
refresh() refresh()
} }
+7 -14
View File
@@ -1,32 +1,21 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<resources> <resources>
<string name="watch_end_session">End session</string> <string name="watch_end_session">Stop receiving</string>
<string name="watch_just_checking">Just checking…</string> <string name="watch_just_checking">Just checking…</string>
<string name="watch_on_its_way">On its way</string> <string name="watch_on_its_way">On its way</string>
<string name="watch_getting_your_app_ready">Getting your app ready.</string> <string name="watch_getting_your_app_ready">Getting your app ready.</string>
<string name="watch_keep_your_browser_open">Keep your browser open.</string> <string name="watch_keep_your_browser_open">Keep your browser open.</string>
<string name="watch_scan_to_send">Scan to send</string> <string name="watch_scan_to_send">Scan to connect</string>
<string name="watch_scan_description">Both devices on the same Wi-Fi.</string> <string name="watch_scan_description">Both devices on the same Wi-Fi.</string>
<string name="watch_ready_for_10_minutes">Ready for 10 minutes</string>
<string name="watch_view_link">View link</string>
<string name="watch_finding_wi_fi">Finding Wi-Fi</string> <string name="watch_finding_wi_fi">Finding Wi-Fi</string>
<string name="watch_connecting_description">Getting ready for your next app.</string>
<string name="watch_cancel">Cancel</string>
<string name="watch_start_receiving">Start receiving</string> <string name="watch_start_receiving">Start receiving</string>
<string name="watch_connection_error">Couldn’t connect. Check Wi-Fi and try again.</string> <string name="watch_connection_error">Couldn’t connect. Check Wi-Fi and try again.</string>
<string name="watch_wi_fi">Wi-Fi</string> <string name="watch_wi_fi">Wi-Fi</string>
<string name="watch_wifi_unavailable">Open Wi-Fi in your watch’s Settings.</string> <string name="watch_wifi_unavailable">Open Wi-Fi in your watch’s Settings.</string>
<string name="watch_your_watch_link">Your watch link</string>
<string name="watch_link_description">Open this link on a device using the same Wi-Fi.</string>
<string name="watch_connection_privacy">Use Wi-Fi you trust. Transfers aren’t encrypted. Keep this link private.</string>
<string name="watch_back_to_code">Back to code</string>
<string name="watch_all_yours">All yours.</string> <string name="watch_all_yours">All yours.</string>
<string name="watch_couldn_t_install">Couldn’t install</string> <string name="watch_couldn_t_install">Couldn’t install</string>
<string name="watch_getting_ready">Getting ready…</string> <string name="watch_getting_ready">Getting ready…</string>
<string name="watch_ready_to_install">Ready to install</string> <string name="watch_ready_to_install">Ready to install</string>
<string name="watch_file_expired">This file has expired. Send it again to install.</string>
<string name="watch_fit_notice">Made for a phone? It may not fit your watch.</string>
<string name="watch_trust_notice">Only install apps you trust.</string>
<string name="watch_try_again">Try again</string> <string name="watch_try_again">Try again</string>
<string name="watch_install">Install</string> <string name="watch_install">Install</string>
<string name="watch_permission_description">Allow Pakkit to install apps. You’ll approve each one.</string> <string name="watch_permission_description">Allow Pakkit to install apps. You’ll approve each one.</string>
@@ -43,7 +32,11 @@
<string name="watch_permission_unavailable">Your watch doesn’t offer this setting. Find apps on Google Play instead.</string> <string name="watch_permission_unavailable">Your watch doesn’t offer this setting. Find apps on Google Play instead.</string>
<string name="watch_launch_unavailable">This app can’t be opened here. Check your watch’s app list.</string> <string name="watch_launch_unavailable">This app can’t be opened here. Check your watch’s app list.</string>
<string name="watch_play_unavailable">Find Google Play in your watch’s app list.</string> <string name="watch_play_unavailable">Find Google Play in your watch’s app list.</string>
<string name="scan_code_description">QR code to connect your browser. Use View link for the full address.</string> <string name="scan_code_description">QR code to connect your browser. The address is below.</string>
<string name="watch_percent_received">%1$d%% received</string> <string name="watch_percent_received">%1$d%% received</string>
<string name="watch_app_summary">%1$s · %2$s MB</string> <string name="watch_app_summary">%1$s · %2$s MB</string>
<string name="watch_connect_browser">Connect browser?</string>
<string name="watch_allow_browser">Allow browser</string>
<string name="watch_not_now">Not now</string>
<string name="watch_save_error">Couldn’t save this app. Free some space and try again.</string>
</resources> </resources>
@@ -9,7 +9,7 @@ class ApkRulesTest {
@Test @Test
fun copyComputesKnownDigest() { fun copyComputesKnownDigest() {
val output = ByteArrayOutputStream() val output = ByteArrayOutputStream()
val result = ApkRules.copyBounded(ByteArrayInputStream("abc".toByteArray()), output) val result = ApkRules.copyAndHash(ByteArrayInputStream("abc".toByteArray()), output)
assertEquals(3L, result.first) assertEquals(3L, result.first)
assertEquals( assertEquals(
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
@@ -18,14 +18,29 @@ class ApkRulesTest {
assertEquals("abc", output.toString("UTF-8")) assertEquals("abc", output.toString("UTF-8"))
} }
@Test(expected = IllegalArgumentException::class) @Test
fun stopsBeforeWritingOverLimit() { fun streamsBeyondThePreviousFileLimitWithABoundedBuffer() {
ApkRules.copyBounded(ByteArrayInputStream(ByteArray(1025)), ByteArrayOutputStream(), 1024) val length = 64L * 1024 * 1024
var remaining = length
val input =
object : java.io.InputStream() {
override fun read(): Int = error("Bulk reads only")
override fun read(bytes: ByteArray, offset: Int, count: Int): Int {
assertTrue("Copy buffer stays bounded", bytes.size <= 64 * 1024)
if (remaining == 0L) return -1
val size = minOf(count.toLong(), remaining).toInt()
bytes.fill(0, offset, offset + size)
remaining -= size
return size
}
}
assertEquals(length, ApkRules.copyAndHash(input).first)
} }
@Test(expected = IllegalArgumentException::class) @Test(expected = IllegalArgumentException::class)
fun refusesEmptyFiles() { fun refusesEmptyFiles() {
ApkRules.copyBounded(ByteArrayInputStream(byteArrayOf()), ByteArrayOutputStream()) ApkRules.copyAndHash(ByteArrayInputStream(byteArrayOf()), ByteArrayOutputStream())
} }
@Test @Test
@@ -35,14 +50,6 @@ class ApkRulesTest {
assertTrue(ApkRules.validId("05b414ab-a230-42f8-9a6d-1be25dcc3224")) assertTrue(ApkRules.validId("05b414ab-a230-42f8-9a6d-1be25dcc3224"))
} }
@Test
fun expirationAndClockSkewAreBounded() {
val now = 1_000_000_000L
assertTrue(ApkRules.fresh(now - 1000, now))
assertFalse(ApkRules.fresh(now - ApkRules.TTL_MS, now))
assertFalse(ApkRules.fresh(now + 120000, now))
}
@Test @Test
fun nativeLibrariesNeedMatchingProcessor() { fun nativeLibrariesNeedMatchingProcessor() {
assertTrue(ApkRules.compatibleAbis(emptySet(), setOf("arm64-v8a"))) assertTrue(ApkRules.compatibleAbis(emptySet(), setOf("arm64-v8a")))
@@ -7,25 +7,25 @@ class CompatibilityTest {
private val apk = Apk("Test", "test.app", "1", 31, 1024, "digest", setOf("arm64-v8a"), true) private val apk = Apk("Test", "test.app", "1", 31, 1024, "digest", setOf("arm64-v8a"), true)
@Test @Test
fun acceptsCompatibleSdkAbiAndStorage() { fun acceptsCompatibleSdkAndProcessor() {
PackageInspector.checkForWatch(apk, 36, setOf("arm64-v8a"), 100L * 1024 * 1024) PackageInspector.checkForWatch(apk, 36, setOf("arm64-v8a"))
} }
@Test @Test
fun rejectsIncompatibleSdkProcessorAndInsufficientStorage() { fun rejectsActualPlatformIncompatibility() {
assertTrue( assertTrue(
runCatching { runCatching { PackageInspector.checkForWatch(apk, 30, setOf("arm64-v8a")) }.isFailure
PackageInspector.checkForWatch(apk, 30, setOf("arm64-v8a"), Long.MAX_VALUE)
}
.isFailure,
) )
assertTrue( assertTrue(
runCatching { PackageInspector.checkForWatch(apk, 36, setOf("x86_64"), Long.MAX_VALUE) } runCatching { PackageInspector.checkForWatch(apk, 36, setOf("x86_64")) }.isFailure
.isFailure,
)
assertTrue(
runCatching { PackageInspector.checkForWatch(apk, 36, setOf("arm64-v8a"), 1024) }
.isFailure,
) )
} }
@Test
fun storageUsesAvailableBytesWithoutAMultiplierOrOverflow() {
PackageInspector.requireSpace(100, 100)
PackageInspector.requireSpace(Long.MAX_VALUE, Long.MAX_VALUE)
assertTrue(runCatching { PackageInspector.requireSpace(101, 100) }.isFailure)
assertTrue(runCatching { PackageInspector.requireSpace(Long.MAX_VALUE, 1024) }.isFailure)
}
} }
@@ -0,0 +1,66 @@
package meghdad.pakkit.transfer
import org.junit.Assert.*
import org.junit.Test
class BrowserAccessTest {
@Test
fun approvingAnotherBrowserDoesNotEvictEarlierApprovals() {
var request: BrowserAccess.Request? = null
val access = BrowserAccess { request = it }
val first = access.connect(null, "Browser", "ip").credential
access.answer(requireNotNull(request).id, true)
repeat(64) {
access.connect(null, "Browser", "ip")
access.answer(requireNotNull(request).id, true)
}
assertEquals(BrowserAccess.State.APPROVED, access.state(first))
}
@Test
fun onlyTheWatchCanApproveAndDecisionsAreSessionScoped() {
var pending: BrowserAccess.Request? = null
val access = BrowserAccess { pending = it }
val connection = access.connect(null, "Chrome", "192.168.1.2")
val credential = requireNotNull(connection.credential)
assertEquals(BrowserAccess.State.PENDING, access.state(credential))
assertFalse(access.answer("forged", true))
assertTrue(access.answer(requireNotNull(pending).id, true))
repeat(100) { assertEquals(BrowserAccess.State.APPROVED, access.state(credential)) }
assertNull(access.connect(credential, "Chrome", "192.168.1.2").credential)
access.close()
assertEquals(BrowserAccess.State.UNKNOWN, access.state(credential))
}
@Test
fun unknownPeersCannotReplacePendingRequestsOrAutoRetryDenial() {
var pending: BrowserAccess.Request? = null
val access = BrowserAccess { pending = it }
val first = access.connect(null, "Chrome", "ip")
val id = requireNotNull(pending).id
repeat(1000) {
assertEquals(BrowserAccess.State.BUSY, access.connect(null, "Unknown", "ip").state)
}
assertEquals(id, pending?.id)
access.answer(id, false)
assertEquals(
BrowserAccess.State.DENIED,
access.connect(first.credential, "Chrome", "ip").state,
)
access.retry(first.credential)
assertEquals(
BrowserAccess.State.PENDING,
access.connect(first.credential, "Chrome", "ip").state,
)
}
@Test
fun credentialsArePrivateOpaqueValuesWithExactHeaderFraming() {
val credential = requireNotNull(BrowserAccess().connect(null, "Browser", "ip").credential)
assertEquals(credential, BrowserAccess.credential("Bearer $credential"))
assertNull(BrowserAccess.credential("Bearer $credential extra"))
assertNull(BrowserAccess.credential("bearer $credential"))
assertNull(BrowserAccess.credential("Bearer guessed"))
assertEquals("Chrome on Android", BrowserAccess.label("Mozilla Android Chrome Safari"))
}
}
@@ -6,11 +6,30 @@ import org.junit.Test
class HttpProtocolTest { class HttpProtocolTest {
private fun request(value: String) = HttpProtocol.read(value.byteInputStream()) private fun request(value: String) = HttpProtocol.read(value.byteInputStream())
@Test
fun authorityChecksNumericAddressesWithoutAssumingPrivateIpv4() {
val v6 = java.net.InetAddress.getByName("fd00::1")
assertTrue(HttpProtocol.sameAuthority("[fd00:0:0:0:0:0:0:1]:8787", v6, 8787))
assertTrue(HttpProtocol.sameAuthority("[fd00::1]:8787", v6, 8787))
val v4 = java.net.InetAddress.getByName("100.64.1.2")
assertTrue(HttpProtocol.sameAuthority("100.64.1.2:8787", v4, 8787))
for (host in
listOf(
"evil.example:8787",
"100.64.1.2:9999",
"evil@100.64.1.2:8787",
"100.64.1.2:8787/path",
"100.64.1.2:8787?q=x",
)) {
assertFalse(host, HttpProtocol.sameAuthority(host, v4, 8787))
}
}
@Test @Test
fun acceptsBoundedRawUpload() { fun acceptsBoundedRawUpload() {
val r = val r =
request( request(
"POST /api/upload HTTP/1.1\r\nHost: 192.168.1.4:8080\r\nContent-Length: 42\r\nContent-Type: application/octet-stream\r\n\r\n", "POST /api/upload HTTP/1.1\r\nHost: 192.168.1.4:8080\r\nContent-Length: 42\r\nContent-Type: application/octet-stream\r\n\r\n"
) )
assertEquals(42L, HttpProtocol.uploadLength(r.headers)) assertEquals(42L, HttpProtocol.uploadLength(r.headers))
assertEquals("/api/upload", r.path) assertEquals("/api/upload", r.path)
@@ -27,41 +46,57 @@ class HttpProtocolTest {
"Long: " + "a".repeat(9000), "Long: " + "a".repeat(9000),
)) { )) {
assertTrue( assertTrue(
runCatching { request("POST /api/upload HTTP/1.1\r\n$headers\r\n\r\n") }.isFailure, runCatching { request("POST /api/upload HTTP/1.1\r\n$headers\r\n\r\n") }.isFailure
) )
} }
} }
@Test @Test
fun rejectsInvalidLengthsAndTypes() { fun rejectsInvalidLengthsAndTypes() {
for (length in listOf("-1", "+1", "1,1", "0", "52428801", "wat", "9223372036854775808")) { for (length in listOf("-1", "+1", "1,1", "0", "wat", "9223372036854775808")) {
assertTrue( assertTrue(
runCatching { runCatching {
HttpProtocol.uploadLength( HttpProtocol.uploadLength(
mapOf( mapOf(
"content-type" to "application/octet-stream", "content-type" to "application/octet-stream",
"content-length" to length, "content-length" to length,
), )
) )
} }
.isFailure, .isFailure
) )
} }
assertTrue( assertTrue(
runCatching { runCatching {
HttpProtocol.uploadLength( HttpProtocol.uploadLength(
mapOf("content-type" to "text/plain", "content-length" to "42"), mapOf("content-type" to "text/plain", "content-length" to "42")
) )
} }
.isFailure, .isFailure
) )
} }
@Test @Test
fun requiresExactBearerToken() { fun slowHeadersCannotHoldAWorkerIndefinitely() {
assertTrue(HttpProtocol.authorized("Bearer secret", "secret")) var time = 0L
assertFalse(HttpProtocol.authorized(null, "secret")) val result = runCatching {
assertFalse(HttpProtocol.authorized("Bearer secretX", "secret")) HttpProtocol.read("GET / HTTP/1.1\r\n\r\n".byteInputStream()) {
assertFalse(HttpProtocol.authorized("bearer secret", "secret")) time += 1_000_000_000
time
}
}
assertTrue(result.isFailure)
}
@Test
fun acceptsLargeContentLengthsWithoutIntegerTruncation() {
for (size in listOf(52_428_801L, 4L * 1024 * 1024 * 1024, Long.MAX_VALUE)) {
assertEquals(
size,
HttpProtocol.uploadLength(
mapOf("content-type" to "application/octet-stream", "content-length" to "$size")
),
)
}
} }
} }
+24 -24
View File
@@ -1,45 +1,45 @@
# Architecture # Architecture
Pakkit is a single Android application for Wear OS. The watch hosts both the native review/install experience and a static HTML/CSS/JavaScript interface delivered to a browser over local Wi-Fi. Pakkit is a Wear OS application that serves its bundled HTML/CSS/JavaScript interface to a browser over Wi-Fi. The watch owns access approval, package review and Android installation. The browser can transfer files and observe state; it cannot request installation.
## Ownership | Package | Responsibility |
| --- | --- |
| `ui` | Native watch views, circular scrolling, QR, browser approval and package review |
| `transfer` | Live receiving state, Wi-Fi lifecycle, fixed-port server, browser access and streamed HTTP bodies |
| `apk` | Inspected metadata, content/compatibility checks, streaming integrity and durable state model |
| `data` | Private files and one durable package review |
| `install` | User-requested Android sessions, system consent and verified installer callbacks |
| Package | Responsibility | There is no frontend build step, CDN, cloud relay, account or transfer backend. ZXing Core is the only explicit runtime library. `qa/fixture` supplies a signed test APK to instrumentation only; browser tools and large generated fixtures never ship.
| ---------- | -------------------------------------------------------------------------------------------- |
| `ui` | WatchActivity, round scrolling, status glyphs and watch design tokens |
| `transfer` | Receiving state, Wi-Fi service, local HTTP endpoint, framing and bounded upload body |
| `apk` | APK metadata, package inspection, compatibility/space/integrity rules and typed review state |
| `data` | PackageStore: one staged APK and its durable review/installation state |
| `install` | ApkInstaller, validated system callback and pending system approval intent |
The native UI composes Android platform views. The web app is served directly from `app/src/main/assets/web`; there is no frontend build step, CDN, WebView, account, backend or internet requirement for transfer. The only explicit runtime library is ZXing Core. A separate Gradle application under `qa/fixture` supplies a signed test APK exclusively to the instrumentation APK.
## Receiving lifecycle ## Receiving lifecycle
WatchActivity starts ReceiveService only after an explicit action. The non-exported connectedDevice foreground service owns the notification/stop action, a requested Wi-Fi network, a timed partial CPU wake lock and a ten-minute deadline. It waits for link properties and binds LocalHttpServer to that network’s private IPv4 address and an ephemeral port. Network loss or address change ends the session. START_NOT_STICKY and absence of boot receivers prevent automatic resurrection. An explicit watch action starts the non-exported connectedDevice foreground service. It requests Wi-Fi without a product timeout and listens on **8787**. IPv4 is preferred; unscoped IPv6 is supported. Only an actual local interface address is bound. A busy port is a clear failure, not an instruction to fall back to a random port.
LocalHttpServer owns the listener, two workers, four queued connections, tracked sockets, HTTP routing and one streamed upload. Service teardown closes the listener and accepted sockets, stops workers, unregisters the Wi-Fi callback, removes callbacks and releases the CPU lock. The display is not held awake. The session can continue while the display sleeps, subject to firmware and OS constraints. Network loss closes the listener and active sockets, resets live transfer progress and leaves receiving enabled. The outstanding network request supplies new link properties; the listener rebinds automatically. Browser access belongs to the service and survives a listener rebind. An IP change still requires opening the new address. Stop, OS timeout and destruction close network resources and clear access. START_NOT_STICKY and the absence of boot receivers prevent silent reopening after process death.
`Receiving` holds an immutable, volatile snapshot in memory. Updates are tagged with the owning service instance, so a stopped session’s workers cannot change a later session. UI notifications are coalesced onto the main thread and observers are removed on pause. Private links and byte counters are never written to preferences. Process death invalidates the session; the user starts a fresh one. Idle receiving holds no CPU wake lock. An actual upload/inspection owns one, released in finally. Two workers, four queued sockets, exact HTTP framing and idle-read protection bound concurrent resource use. A header parsing budget prevents slow headers from retaining a worker indefinitely. These do not impose a transfer-duration or package-size ceiling. Screen-off operation remains subject to the OS and firmware.
## Durable package state `Receiving` publishes an immutable in-memory snapshot through coalesced main-thread observers. Service ownership and listener-close guards prevent stale workers from modifying later state. The server's close/commit lock prevents a file being staged after Stop. UI observers are removed on pause; byte counters and browser credentials are not persisted.
PackageStore retains one PendingApk: UUID, creation time, inspected metadata, an InstallState, detail and optional installer session ID. It preserves a stable private storage schema across application updates. All writers share a lock; staging refuses replacement of an existing review, and updates require the current package ID. Dismissed reviews cannot be resurrected by late callbacks. ## Browser access
Files use app-private UUID filenames. Complete APKs remain eligible for review for 24 hours. Launch cleanup removes expired reviews and old unreferenced files. Partial/rejected uploads are deleted in a finally block. Installation success or dismissal deletes the staged APK. Expiry is an eligibility deadline with lazy disk cleanup, not a scheduled background deletion promise. The QR and displayed address are ordinary URLs without secrets. On page load, a same-origin POST requests browser access. The watch shows the browser/device description and peer address. Its Allow/Not now actions approve or deny a random, session-only access credential. The browser stores the credential in localStorage isolated to this scheme/host/port and sends it in Authorization headers. Reloads and tabs in the same browser profile do not ask again. Storage-denied browsers use memory and may need approval after reload. An explicit retry can request approval after denial. Unknown peers cannot replace the prompt already under consideration. One pending slot bounds unauthenticated request allocation; further decision records require a watch action. Approvals have no time or browser-count quota.
## HTTP and trust Only approved credentials can observe package status or upload. Host and POST Origin must resolve numerically to this listener's address/port; IPv6 compression is normalized without allowing hostnames. Static assets come from a fixed allowlist. CSP, no-cache/no-referrer/nosniff, no CORS and no framing remain in force. HTTP is unencrypted and requires trusted networking; authentication does not provide transport confidentiality.
Each session generates a 192-bit random key embedded in the private URL fragment. JavaScript removes it from visible history after page load and keeps it in memory for Authorization headers. A reload without the fragment requires the key again. A fixed asset allowlist prevents filesystem traversal. APIs require the key; uploads also require the exact Origin. Exact Host validation resists DNS rebinding. No CORS, framing, external scripts/styles/fonts, cached responses or browser-controlled installation endpoints are enabled. ## Streaming and storage
HttpProtocol accepts a small HTTP/1.1 subset: GET/POST, one request per connection, 8 KiB total headers, 4 KiB lines, unique headers and no chunked/Expect framing. Uploads require decimal Content-Length in 1..50 MiB and application/octet-stream. UploadBody reads exactly that length, treats truncation as failure and reports progress at most four times per second. A 64 KiB buffer writes the private file while computing SHA-256. Storage reserve and bounded ZIP/manifest inspection precede review. SDK, ABI, complete-package and self-update checks are centralized in the APK package. Uploads use File/XHR and raw octet-stream with a positive, 64-bit Content-Length. There is no application byte ceiling or total-duration timeout. A 64 KiB buffer writes to an app-private UUID file while computing SHA-256. UploadBody reads exactly the declared length and throttles progress updates. Available disk bytes are checked before writing; ENOSPC and interrupted reads fail with recovery copy and delete the partial file.
Local HTTP is unencrypted. Link secrecy and Host/Origin/hash checks do not protect against a LAN observer or active attacker. Use a trusted network. Possession of the link allows file submission, while watch review and the Android installer remain separate consent boundaries. Receipt inspects ZIP directory and Android metadata without unpacking assets into memory. Complete-package, SDK, processor and Play self-update policy checks precede review. There are no arbitrary directory-entry, expanded-data or manifest-size caps. Android's parser, package format and device resources still impose real constraints.
PackageStore retains PendingApk with UUID, receipt time, metadata, state, detail and installer session ID. The private schema remains stable across updates. A review never expires by age. PakkitApplication cleans unreferenced files at process startup, before any upload exists; activity recreation cannot delete a transfer in progress. Success/removal deletes the staged file. A new upload can replace a terminal installed/failed review. An unfinished review is preserved. Updates require the matching package ID, so dismissed reviews cannot be resurrected.
## Installation ## Installation
InstallState progresses from READY to INSTALLING, then CONFIRM when Android requires user action, and finally INSTALLED or FAILED. ApkInstaller runs off the main thread only after the watch’s Install action. It rechecks source trust, expiry, private-file digest and compatibility before creating a MODE_FULL_INSTALL session with USER_ACTION_REQUIRED. It never bypasses source approval, verification or system consent. Only a watch action starts ApkInstaller. Returning from granting source permission continues that specific request. The worker verifies source trust, the saved file's digest, current SDK/ABI compatibility and space for the staging copy. It reuses the receipt metadata proven by the digest, rather than repeating archive inspection. Android's installer determines actual installation allocation and verifies the package.
The explicit mutable PendingIntent targets a non-exported InstallReceiver. The receiver requires the active package ID, a non-null matching session ID and an installation/confirmation state. A pending action exposes only Android’s returned confirmation intent, through the watch UI or an immutable notification PendingIntent. State changes refresh the UI through PackageStore preferences; the receiver does not hold an Activity reference. Interrupted confirmation can be retried. MODE_FULL_INSTALL and USER_ACTION_REQUIRED preserve supported system consent. The non-exported receiver accepts only the active job, matching non-null session ID and expected state. When Pakkit is visible, Android's returned consent intent opens once automatically; Continue is available for recovery. Optional notification denial does not block in-app approval. Native INSTALLED state only follows Android STATUS_SUCCESS.
Optional notification denial leaves the in-app consent flow usable. Firmware that cannot expose usable source approval or installation consent is unsupported for external installs and directs users to Google Play. Read PLATFORM.md and RELEASE.md before making distribution claims. See [restriction rationale](RESTRICTIONS.md), [platform constraints](PLATFORM.md) and [validation](VALIDATION.md) for the distinction between product behavior and OS/distribution requirements.
+4 -4
View File
@@ -13,9 +13,9 @@
## Themes and layout ## Themes and layout
The native watch UI uses midnight `#090B17` to limit lit OLED pixels, lavender-white text and semantic mint/error surfaces. Body and secondary copy, badges and action gradient endpoints have automated contrast checks. Actions have a minimum 48 dp height and scalable text. Proportional margins and bottom padding allow controls to move into the usable center of a round display. The QR is sized to screen width and positioned within the circular safe area; the full URL and connection disclosure are available through **View link**, with native back navigation. The home screen pairs a compact parcel/wordmark with a visible receiving action. Source permission is requested at the app review, where its purpose is clear. The native watch UI uses midnight `#090B17` to limit lit OLED pixels, lavender-white text and semantic mint/error surfaces. Body and secondary copy, badges and action gradient endpoints have automated contrast checks. Actions have a minimum 48 dp height and scalable text. Proportional margins and bottom padding allow controls to move into the usable center of a round display. The QR is sized to screen width and positioned within the circular safe area; the ordinary fixed-port address is readable below the QR, without a link-details step. The home screen pairs a compact parcel/wordmark with a visible receiving action. Source permission is requested at the app review, where its purpose is clear.
The browser leads with the official tagline, original parcel artwork and a compact Choose / Send / Wear indicator. Mobile layouts omit the redundant journey explainer. It follows prefers-color-scheme with an explicit in-session toggle. Dark is midnight with violet/cyan lighting; light uses soft lavender and white surfaces. A two-column desktop layout becomes a single-column layout at smaller widths. The maintained CSS, HTML and JavaScript are readable source files, formatted with the optional web development tools. Native browser controls, semantic headings, focus rings, file labels and a live status region support keyboard and assistive access. The browser leads with the official tagline, original parcel artwork and a compact Choose / Send / Wear indicator. The compact state indicator replaces a lengthy journey explainer. It follows prefers-color-scheme with an explicit in-session toggle. Dark is midnight with violet/cyan lighting; light uses soft lavender and white surfaces. A two-column desktop layout becomes a single-column layout at smaller widths. The maintained CSS, HTML and JavaScript are readable source files, formatted with the optional web development tools. Native browser controls, semantic headings, focus rings, file labels and a live status region support keyboard and assistive access.
## Motion and product states ## Motion and product states
@@ -32,7 +32,7 @@ Write for the person wearing the watch: short, warm, specific and calm. Let the
| Moment | Watch | Browser | | Moment | Watch | Browser |
| --- | --- | --- | | --- | --- | --- |
| Start | Pakkit + official tagline; Start receiving | Official tagline; Choose app | | Start | Pakkit + official tagline; Start receiving | Official tagline; Choose app |
| Connect | Scan to send; View link | Connected to your watch | | Connect | Scan to connect; Allow browser | A quick hello; Connected to your watch |
| Transfer | On its way + actual percentage | On its way + actual percentage | | Transfer | On its way + actual percentage | On its way + actual percentage |
| Check | Just checking… | Just checking… | | Check | Just checking… | Just checking… |
| Review | Ready to install; Install or contextual Allow installs | Made it to your watch | | Review | Ready to install; Install or contextual Allow installs | Made it to your watch |
@@ -40,4 +40,4 @@ Write for the person wearing the watch: short, warm, specific and calm. Let the
| Success | All yours.; Open app | Looks good on you. | | Success | All yours.; Open app | Looks good on you. |
| Failure | Couldn’t install + specific recovery | Let’s try that again + specific recovery | | Failure | Couldn’t install + specific recovery | Let’s try that again + specific recovery |
Watch screen copy lives in Android string resources. Deliberately written package-validation messages are marked with `UserMessage`; unknown file/platform exceptions are replaced with recovery copy at the UI boundary, while installer diagnostics stay in logs. Notification copy follows the same voice. The app name and official tagline are shared branding resources. Browser result changes are announced with a live region, and color is never the only state indicator. Watch screen copy lives in Android string resources. Deliberately written package-validation messages are marked with `UserMessage`; unknown file/platform exceptions are replaced with recovery copy at the UI boundary, while installer diagnostics stay in logs. Notification copy follows the same voice. There are no key-entry forms, expiry countdowns, file-size warnings or repeated watch-layout warnings. The app name and official tagline are shared branding resources. Browser result changes are announced with a live region, and color is never the only state indicator.
+17 -6
View File
@@ -14,8 +14,8 @@
```sh ```sh
./gradlew :app:assembleDebug :app:assembleDebugAndroidTest :app:testDebugUnitTest :app:lint :app:bundleRelease ./gradlew :app:assembleDebug :app:assembleDebugAndroidTest :app:testDebugUnitTest :app:lint :app:bundleRelease
adb devices adb devices
python 3 scripts/test-emulators.py --watch emulator-5554 --skip-build python3 scripts/test-emulators.py --watch emulator-5554 --skip-build
python 3 scripts/test-emulators.py --watch emulator-5554 --small --skip-build python3 scripts/test-emulators.py --watch emulator-5554 --small --skip-build
``` ```
Use actual serials from `adb devices`. The runner refuses serials that do not start with `emulator-` and requires the watch feature. It never selects a physical device. It connects the watch to the virtual AndroidWifi access point, installs only the app/test APKs and saves results under `app/build/reports/validation`. The small-screen run temporarily uses 192 dp and 1.3x font scaling, restoring the previous size, density and font setting in a finally block. Use actual serials from `adb devices`. The runner refuses serials that do not start with `emulator-` and requires the watch feature. It never selects a physical device. It connects the watch to the virtual AndroidWifi access point, installs only the app/test APKs and saves results under `app/build/reports/validation`. The small-screen run temporarily uses 192 dp and 1.3x font scaling, restoring the previous size, density and font setting in a finally block.
@@ -33,7 +33,7 @@ npm test --prefix web-tests
npm run format:check --prefix web-tests npm run format:check --prefix web-tests
``` ```
These tests serve the actual bundled assets with a local API fixture and exercise 320/390/768/1440 px widths, both themes, manual session-key entry, file rejection, upload errors/retry, system-status transitions and cancellation. This isolates browser interactions; it does not stand in for watch networking. An existing Chromium executable can be selected with PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH. These tests serve the actual bundled assets with a local API fixture and exercise 320/390/768/1440 px widths, both themes, watch-approval/denial/retry states without manual keys, empty-file rejection, a 64 MiB streamed browser upload, upload errors/retry, system-status transitions and cancellation. This isolates browser interactions; it does not stand in for watch networking. An existing Chromium executable can be selected with PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH.
Playwright and Prettier are development dependencies only, locked in web-tests/package-lock.json. There is no Node toolchain in the Android runtime or asset build. `npm run format --prefix web-tests` formats web assets and browser tests; use standard Kotlin formatting for native source. Playwright and Prettier are development dependencies only, locked in web-tests/package-lock.json. There is no Node toolchain in the Android runtime or asset build. `npm run format --prefix web-tests` formats web assets and browser tests; use standard Kotlin formatting for native source.
@@ -42,12 +42,23 @@ Playwright and Prettier are development dependencies only, locked in web-tests/p
Complete Chrome’s first-run setup in the Android Emulator, leave Chrome open, and run: Complete Chrome’s first-run setup in the Android Emulator, leave Chrome open, and run:
```sh ```sh
python 3 scripts/test-emulators.py --watch emulator-5554 --browser emulator-5556 --skip-build python3 scripts/test-emulators.py --watch emulator-5554 --browser emulator-5556 --skip-build
``` ```
Both emulators must use the shared virtual Wi-Fi network. Android Emulator 36.5+ [supports direct communication between emulator instances](https://developer.android.com/studio/run/emulator-networking-interconnect). The runner starts Pakkit through its visible receiving action, reads the private link from the actual watch UI, connects Playwright to Chrome on the Android Emulator through a local ADB forward, and submits the signed QA fixture. Chrome sends the real XHR directly to the watch’s private Wi-Fi address. The test asserts watch review, then dismisses the fixture and ends the session. Debug forwarding is test infrastructure; no debug endpoint or test mode ships in Pakkit. The forward is removed afterward and the watch app is stopped even on failure. Both emulators must use the shared virtual Wi-Fi network. Android Emulator 36.5+ [supports direct communication between emulator instances](https://developer.android.com/studio/run/emulator-networking-interconnect). The runner starts Pakkit through its visible receiving action, reads the fixed-port address from the actual watch UI, connects Playwright to Chrome on the Android Emulator through a local ADB forward, approves the browser using the visible **Allow browser** watch control, and submits the signed QA fixture. Chrome sends the real XHR directly to the watch’s private Wi-Fi address. The test asserts watch review, then dismisses the fixture and ends the session. Debug forwarding is test infrastructure; no debug endpoint or test mode ships in Pakkit. The forward is removed afterward and the watch app is stopped even on failure.
An uninitialized Chrome instance or isolated/older emulator network requires environment setup; the runner does not silently substitute mock transport. Keep private session URLs out of committed logs. Generated screenshots and API summaries live under app/build/reports/validation. An uninitialized Chrome instance or isolated/older emulator network requires environment setup; the runner does not silently substitute mock transport. No URL token or manual session key is used. Generated screenshots and API summaries live under app/build/reports/validation.
## Large APK validation
Build the normal fixture, then generate a separately signed fixture with a stored 64 MiB asset:
```sh
python3 scripts/create-large-fixture.py
python3 scripts/test-emulators.py --watch emulator-5554 --browser emulator-5556 --large --skip-build
```
The resulting APK is about 66 MiB. `--bytes` can select another asset size based on the test device's actual storage. The generator copies and signs incrementally, does not modify source assets, and writes only under ignored app/build/qa. Chrome receives the test file in its own emulator storage; CDP selects that file directly, avoiding Playwright's unrelated 50 MB in-memory buffer limit. The real web app uploads the File using XHR. Generated large fixtures are never included in the app/test APK or release bundle. The runner removes the Chrome-side copy afterward.
## Fixture and release inspection ## Fixture and release inspection
+3 -3
View File
@@ -4,7 +4,7 @@
Pakkit requests a local Wi-Fi connection, hosts its browser assets and accepts a complete APK. Watch review initiates the public Android PackageInstaller session with user action required. Receiving a file is not proof that firmware permits installation. Pakkit requests a local Wi-Fi connection, hosts its browser assets and accepts a complete APK. Watch review initiates the public Android PackageInstaller session with user action required. Receiving a file is not proof that firmware permits installation.
[Wear OS network guidance](https://developer.android.com/training/wearables/data/network-communication) documents independent HTTP/TCP/UDP access. Pakkit uses a requested Wi-Fi network and a listener bound to its private IPv4 address; a proxied/default internet route is insufficient for inbound LAN access. Guest-network isolation, VPNs, firewalls and browser local-network restrictions can prevent access. IPv6-only networks and resumable/split-package uploads are outside the current scope. [Wear OS network guidance](https://developer.android.com/training/wearables/data/network-communication) documents independent HTTP/TCP/UDP access. Pakkit uses a requested Wi-Fi network and a listener bound to its Wi-Fi IPv4 or unscoped IPv6 address on port 8787; a proxied/default internet route is insufficient for inbound LAN access. Guest-network isolation, VPNs, firewalls and browser local-network restrictions can prevent access. Link-local IPv6 addresses that require client-specific zones and byte-range resume are not supported. Split-package sets require a separate multi-file installation flow.
[Standalone Wear apps](https://developer.android.com/training/wearables/apps/standalone-apps) support a QR/browser flow. The manifest declares required watch hardware and standalone=true. A watch’s OEM onboarding requirements remain independent of Pakkit’s transfer functionality. [Standalone Wear apps](https://developer.android.com/training/wearables/apps/standalone-apps) support a QR/browser flow. The manifest declares required watch hardware and standalone=true. A watch’s OEM onboarding requirements remain independent of Pakkit’s transfer functionality.
@@ -14,11 +14,11 @@ Pakkit requests a local Wi-Fi connection, hosts its browser assets and accepts a
[PackageInstaller](https://developer.android.com/reference/android/content/pm/PackageInstaller) supports sessions, pending system user action and final success/failure results. Pakkit explicitly requires user action and handles Android’s returned consent intent. A source setting or API existing on Android does not establish that every Wear OS firmware exposes usable permission/confirmation UI. Unsupported firmware directs the user to Google Play. No root, privileged installer, hidden component, debugging client or verification bypass is implemented. [PackageInstaller](https://developer.android.com/reference/android/content/pm/PackageInstaller) supports sessions, pending system user action and final success/failure results. Pakkit explicitly requires user action and handles Android’s returned consent intent. A source setting or API existing on Android does not establish that every Wear OS firmware exposes usable permission/confirmation UI. Unsupported firmware directs the user to Google Play. No root, privileged installer, hidden component, debugging client or verification bypass is implemented.
APK inspection checks size, bounded archive structure, readable signing metadata, complete-package status, SDK, ABI and storage reserve. It rejects Pakkit self-updates. It does not certify malware safety, final signature validity, runtime behavior, every hardware feature or a suitable circular layout. Android makes the final installation decision. Verification/security policy can block an otherwise well-formed upload. APK inspection checks actual package content, readable signing metadata, complete-package status, SDK and ABI. File sizes are constrained by device storage and Android, not a product ceiling. It rejects Pakkit self-updates. It does not certify malware safety, final signature validity, runtime behavior, every hardware feature or a suitable circular layout. Android makes the final installation decision. Verification/security policy can block an otherwise well-formed upload.
## Lifecycle and permissions ## Lifecycle and permissions
A user-started [connectedDevice foreground service](https://developer.android.com/develop/background-work/services/fgs/service-types#connected-device) supports a bounded local transfer with an external device. CHANGE_NETWORK_STATE supports the Wi-Fi request and this service type’s prerequisite. The service exposes a stop action and releases its network/CPU resources at termination. This design bounds resource use but does not replace hardware battery/thermal testing. A user-started [connectedDevice foreground service](https://developer.android.com/develop/background-work/services/fgs/service-types#connected-device) supports user-controlled local transfer with an external device. CHANGE_NETWORK_STATE supports the Wi-Fi request and this service type’s prerequisite. The service exposes a stop action and releases its network resources at termination. CPU wake ownership exists only while receiving/inspecting an actual file. This design bounds resource use but does not replace hardware battery/thermal testing.
[Local network protections](https://developer.android.com/privacy-and-security/local-network-permission) apply to incoming TCP too. Target 36 uses INTERNET for implicit local access. Before raising the target to 37, implement/test ACCESS_LOCAL_NETWORK runtime consent. Browser permissions can impose separate constraints. Keep this guidance aligned with the target SDK and supported firmware. [Local network protections](https://developer.android.com/privacy-and-security/local-network-permission) apply to incoming TCP too. Target 36 uses INTERNET for implicit local access. Before raising the target to 37, implement/test ACCESS_LOCAL_NETWORK runtime consent. Browser permissions can impose separate constraints. Keep this guidance aligned with the target SDK and supported firmware.
+5 -3
View File
@@ -2,12 +2,14 @@
Pakkit transfers the APK you select in a browser directly to your Wear OS watch over local Wi-Fi. The browser assets and QR generation are bundled with the watch application. No account, backend, analytics, advertising, remote font or cloud relay is used. Pakkit transfers the APK you select in a browser directly to your Wear OS watch over local Wi-Fi. The browser assets and QR generation are bundled with the watch application. No account, backend, analytics, advertising, remote font or cloud relay is used.
Receiving sessions generate a private URL/key that stays in process memory. Keep the link private and use trusted Wi-Fi. Local HTTP is unencrypted: someone able to observe or alter network traffic may access it. Pakkit removes the key from visible browser history after loading; the browser and operating system still control their own browsing data and behavior. The watch displays an ordinary local address and QR code. A browser requests access and the user approves it on the watch. The watch keeps a random access credential plus the approval decision in process memory. The browser stores the credential in localStorage for Pakkit’s exact origin (scheme, host and port), and sends it automatically only to this app’s API. Browser/device descriptions are inferred from request headers, and the peer's network address is shown for approval. There is no manual key entry. Approvals are cleared when receiving stops or the process ends. Browsers control their own site-storage retention. A stored credential becomes unusable when the watch clears its receiving session, even if it remains in browser storage.
Local HTTP is unencrypted: someone able to observe or alter network traffic may access it. Use Wi-Fi you trust. Watch approval is access control, not encryption.
APKs and package-review metadata are stored in private watch storage. Pakkit reads package/signing metadata and computes a hash to detect corruption or changed staged files. This is not malware certification. Installation requires your watch action and Android’s system consent. Android can independently verify or block packages under its own policies. APKs and package-review metadata are stored in private watch storage. Pakkit reads package/signing metadata and computes a hash to detect corruption or changed staged files. This is not malware certification. Installation requires your watch action and Android’s system consent. Android can independently verify or block packages under its own policies.
Partial/rejected uploads are deleted. Successful installation or dismissing the review deletes the staged file. Pending APKs expire for installation after 24 hours and are cleaned on the next app launch; they may remain in private storage until then. Pakkit retains one durable review. Backups and device transfer of private app data are disabled. Uninstalling Pakkit removes its private data; installed apps are separate. Partial/rejected uploads are deleted. Successful installation or dismissing the review deletes the staged file. Pending APKs do not expire by age. Uncommitted files left by process interruption are removed at the next process startup. A new upload may replace an installed or failed review. Pakkit retains one durable review. Backups and device transfer of private app data are disabled. Uninstalling Pakkit removes its private data; installed apps are separate.
Sessions end within ten minutes, on Wi-Fi loss or when stopped. Ending network access does not cancel an already committed Android installation. Process death requires a new session and key. Receiving remains enabled until the user stops it or the operating system ends it. Network loss suspends the listener and interrupts an active upload; receiving resumes when Wi-Fi returns. Ending network access does not cancel an already committed Android installation. Process death requires starting receiving and approving browser access again.
Before publication, supply the legal developer identity, support contact and hosted privacy-policy URL. Reconcile the final binary, system behavior and Google Play Data safety declaration. This file is the product disclosure source, not a completed Play submission. Before publication, supply the legal developer identity, support contact and hosted privacy-policy URL. Reconcile the final binary, system behavior and Google Play Data safety declaration. This file is the product disclosure source, not a completed Play submission.
+56
View File
@@ -0,0 +1,56 @@
# Product restrictions and their reasons
Pakkit should finish useful work, not stop because a product timer or file-size preset ran out. This audit covers receiving, browser access, files, lifecycle, installation and resource use.
## Removed or redesigned
| Previous behavior | Current behavior |
| --- | --- |
| Receiving ends after ten minutes | No app-imposed session deadline. Receiving stays on until stopped or the OS ends it. |
| Wi-Fi loss ends receiving | The listener closes, interrupted uploads are discarded, and the service waits for Wi-Fi. It binds again automatically. Browser approvals survive a rebind in the same service. |
| A new port for every session | Port **8787**, including after restarts. A genuine port collision is reported rather than silently changing the address. |
| URL secrets and manual key entry | A normal address and QR code. The browser requests access automatically; the watch approves it once per receiving session. A session-only credential stored in browser-origin storage handles subsequent requests and reloads. No keys appear in the interface, address or history. |
| 50 MiB APK limit | No application size ceiling. Positive 64-bit lengths, streaming, available storage and Android's installer determine what fits. |
| Five-minute browser upload deadline | No total XHR deadline. An upload can continue as long as data keeps arriving. |
| 24-hour expiry of a received APK | A pending review remains available until removed or installed. Process-start cleanup only deletes uncommitted/orphaned files. |
| Three-times-file-size reserve plus 20 MiB | Upload checks the bytes needed for the incoming file. Installation checks space for its staging copy; Android handles actual extraction/allocation failures. No multiplier or arbitrary reserve. |
| ZIP entry count, individual-entry, expanded-total and manifest-size caps | No preset archive caps. Inspection reads ZIP directory metadata and Android package metadata without unpacking all assets or loading the APK into memory. Runtime/parser limits remain real hardware constraints. |
| Rejection based on the browser filename | File extension is a picker hint, not an acceptance rule. The watch validates actual APK content. Empty files still cannot be installed. |
| Private IPv4 address required | Wi-Fi IPv4 or reachable, unscoped IPv6 addresses. Equivalent IPv6 spellings are accepted by the Host/Origin checks. |
| Repeated archive inspection at install | One inspection at receipt. A streamed digest verifies that those bytes are unchanged before installation; current SDK/ABI checks and Android verification still apply. |
| Separate Continue tap for normal system consent | A visible Pakkit activity opens Android's returned approval intent once. Continue remains a recovery action, not an obligatory extra step. Returning from granting source permission continues the requested installation. |
| Clear a finished/failed review on the watch before sending another | The browser can choose another app immediately. A new upload replaces terminal reviews. |
| Watch-layout warning based on a missing optional feature flag | Removed. Absence of that declaration does not prove the app will fail or have an unsuitable layout. |
| Duplicate trust warnings in the review | Installation remains an explicit decision, without repeating warnings at each step. Connection privacy details remain accessible in the browser. |
## Retained protections
| Protection | Concrete reason |
| --- | --- |
| Start/Stop receiving and foreground-service visibility | User control over a network listener and its battery/network use. No boot start or automatic restart after process death. |
| Watch approval for a new browser | An address on a shared network is not authentication. Nearby devices must not be able to upload unsolicited files. Browser descriptions are hints; they are not verified identities. |
| Revocation on Stop/process death | Explicitly closing receiving must revoke access. No trust survives a new receiving service. |
| One pending browser request | An unauthenticated peer cannot allocate an unbounded request list or replace the prompt under consideration. Each additional decision record requires a watch action. Existing approvals are not evicted by a time or browser-count quota. |
| Literal Host and same-origin POST checks; no CORS; origin-scoped credentials; CSP | Protects against DNS rebinding, cross-site submissions and unnecessary script access to credentials. IPv4/IPv6 normalization does not permit arbitrary hostnames. |
| 8 KiB headers, 4 KiB lines, unique headers, exact Content-Length | Bounds unauthenticated parsing memory and prevents ambiguous framing, request smuggling and unbounded body reads. Browser File/XHR supplies a length; chunked/Expect/pipelined bodies are not part of this endpoint. |
| Five-second header parsing budget and 15-second read inactivity timeout | Abandoned or deliberately stalled sockets must not occupy the watch's small worker pool forever. These measure stalled request I/O, not receiving-session age or total transfer duration. A slow but continuously progressing upload has no total deadline. |
| Five-second browser status probe | Detects an unreachable receiver and retries automatically. It neither cancels uploads nor expires access. |
| Two workers, four queued sockets, one active upload | Bounds threads, open sockets, concurrent disk writes and CPU wake ownership on the watch. Extra connections retry; no package size limit follows from this resource bound. |
| One unfinished package review | Prevents a new upload from overwriting an app currently under review or installation. Finished/failed reviews do not block the next upload. This is Pakkit's bounded workflow, not an Android package-count restriction. |
| Complete, readable, signed APK; SDK/processor checks | A partial/split APK cannot be installed alone by this single-APK flow, and Android rejects incompatible or unsigned packages. Package inspection is not malware certification. |
| Private UUID paths, digest check, matched installer callback/session | Prevents traversal, changed staged files and stale/forged callbacks changing the current review. |
| Pakkit self-updates use Google Play | The [REQUEST_INSTALL_PACKAGES policy](https://support.google.com/googleplay/android-developer/answer/12085295?hl=en) restricts self-update use. Removing this check would compromise the intended distribution model. |
| Source approval, explicit watch install action and system consent | Supported [PackageInstaller](https://developer.android.com/reference/android/content/pm/PackageInstaller) behavior and user control. Browser access never authorizes installation. |
| Minimum API 31 | The implementation explicitly uses USER_ACTION_REQUIRED and other API 31 native behavior. Supporting older systems would require a separately tested compatibility path, not deleting a guard. |
## Actual limits and recovery
No arbitrary byte ceiling does not mean infinite capacity. Android file lengths and installer sizes use signed 64-bit values; actual disk capacity, package format, parser memory, firmware security policy and available system installation UI remain authoritative. Storage checks are snapshots: another app can consume space afterward. ENOSPC failures produce a storage recovery message and partial files are deleted.
The worker hashes and writes using a 64 KiB buffer. APK assets are not inflated in memory. CPU wake ownership is limited to an actual upload/inspection and released in finally; idle receiving holds no CPU wake lock. Wi-Fi is requested for as long as receiving is enabled. Long screen-off availability, firmware power management, thermal behavior and battery consumption still require hardware measurement. The OS may suspend or stop background execution; Pakkit does not promise to defeat that behavior. See [Wear networking](https://developer.android.com/training/wearables/data/network-communication) and [foreground-service types](https://developer.android.com/develop/background-work/services/fgs/service-types#connected-device).
Partial uploads restart from the beginning, with the selected browser File retained for retry. Byte-range resume is not implemented. Link-local IPv6 addresses requiring a client-specific zone identifier cannot be advertised portably; the receiver prefers IPv4, then unscoped IPv6. Wi-Fi isolation, firewalls, browser permissions and address changes are network/platform constraints. The port is fixed; the router still assigns the watch's IP address.
HTTP remains unencrypted. Watch approval and credentials do not defend against a party able to read or alter LAN traffic. The product is for trusted networks; no remote relay, router port-forwarding feature or internet exposure is configured by Pakkit. The browser's connection details explain this without an additional confirmation dialog.
Credentials are origin-scoped rather than cookies: [HTTP cookies share a host across ports](https://www.rfc-editor.org/rfc/rfc6265#section-8.5), while [Web Storage is origin-isolated](https://html.spec.whatwg.org/multipage/webstorage.html). Another app serving a different port on the watch must not inherit Pakkit access. The bundled script uses automatic Authorization headers only for its relative API requests; no credential appears in the address or interface. Local storage is not encryption and remains readable by same-origin script, which is why external scripts, inline script and untrusted HTML rendering are excluded.
+10 -10
View File
@@ -8,10 +8,10 @@ See DEVELOPMENT.md for the commands and environment setup. Results are generated
| Check | Scope | | Check | Scope |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| JVM tests | Bounded copy/digest, IDs, expiry, SDK/ABI/storage policy, strict HTTP framing/auth/length, exact upload-body reads and progress throttling, native watch contrast | | JVM tests | Streaming copy/digest beyond the previous limit, IDs, SDK/ABI/available-storage policy, strict HTTP framing/authority/64-bit lengths, watch-gated browser access, exact upload-body reads and progress throttling, native watch contrast |
| Wear instrumentation | Signed archive inspection, self-update/invalid archive rejection, typed storage persistence/expiry, late callback rejection, changed-file rejection, official system consent, real socket upload/auth/Host/Origin/size checks, stop cleanup, stale-worker isolation, circular QR and reachable actions | | Wear instrumentation | Signed archive inspection, self-update/invalid archive rejection, typed storage persistence without expiry and failed-write rollback, late callback rejection, changed-file rejection, official system consent, real socket upload/access/Host/Origin/storage checks, stop cleanup/revocation, upload wake-lock release, stale-worker isolation, Wi-Fi reconnection, IPv6 listener/port collision behavior, circular QR and reachable actions |
| Small round screen | Review controls and QR geometry at 192 dp with 1.3x text, restoring emulator configuration afterward | | Small round screen | Review controls and QR geometry at 192 dp with 1.3x text, restoring emulator configuration afterward |
| Browser UI | Four widths, dark/light, private-key entry, invalid files, error/retry, watch/system-status transitions and cancellation, using actual assets with an API fixture | | Browser UI | Four widths, dark/light, keyless approval/denial/retry, reload and cross-port credential isolation, invalid files, error/retry, watch/system-status transitions and cancellation, using actual assets with an API fixture |
| Android-to-Wear transfer | Chrome on Android Emulator -> actual Wi-Fi HTTP listener on Wear OS Emulator -> verified signed APK waiting for watch review | | Android-to-Wear transfer | Chrome on Android Emulator -> actual Wi-Fi HTTP listener on Wear OS Emulator -> verified signed APK waiting for watch review |
| Release | Clean debug/test/release builds, Android lint, dependency and merged-manifest inspection, fixture exclusion from consumer artifacts | | Release | Clean debug/test/release builds, Android lint, dependency and merged-manifest inspection, fixture exclusion from consumer artifacts |
@@ -21,23 +21,23 @@ Browser UI fixtures exercise interactions independently; the separate Android Em
## Latest completed run ## Latest completed run
Product experience validation date: October 15, 2026. No physical device was accessed. Receiving simplification validation date: October 15, 2026. No physical device was accessed.
- **21 JVM tests passed**, with zero failures/errors. - **27 JVM tests passed**, with zero failures/errors.
- **17 native tests passed** on the round Wear OS API 37 emulator, with no skipped assumptions. This includes the public installer’s required-consent callback and refusal of requests after a session deadline. - **21 native tests passed** on the round Wear OS API 37 emulator, with no skipped assumptions. This includes the public installer’s required-consent callback, Wi-Fi loss/recovery without ending receiving, fixed-port reuse/collision behavior, IPv6, metadata rollback and released CPU wake locks after uploads.
- **Five round UI tests passed again** at 192 dp / 1.3x text: the initial receiving action stays visible, review/approval/error/success controls are reachable, connection details and transfer feedback work, and a decodable QR fits inside the circular bezel. Size, density and font scale were restored. - **Five round UI tests passed again** at 192 dp / 1.3x text: the initial receiving action stays visible, review/approval/error/success controls are reachable, connection details and transfer feedback work, and a decodable QR fits inside the circular bezel. Size, density and font scale were restored.
- **16 browser UI checks passed** on Chromium 140.0.7339.16 across four viewport widths and both themes, including connection recovery, keyboard focus, reduced motion and 200% zoom at an effective 320 px layout width, with zero JavaScript errors. - **18 browser UI checks passed** on Chromium 140.0.7339.16 across four viewport widths and both themes, including connection recovery, keyboard focus, reduced motion and 200% zoom at an effective 320 px layout width, with zero JavaScript errors.
- **Real Android Emulator Chrome 145.0.7632.218 uploaded the signed fixture directly to the Wear OS Emulator over virtual Wi-Fi**, receiving READY review state. The test dismissed its package, ended receiving and removed its local debug forward. - **Real Android Emulator Chrome 145.0.7632.218 uploaded signed APKs of 69,588,292 bytes and 270,914,884 bytes directly to the Wear OS Emulator over virtual Wi-Fi**, receiving READY review state. The larger APK contains a stored 256 MiB asset, exceeding the removed individual-entry and expanded-content caps. There were zero JavaScript errors and browser access was approved through the visible watch control. The test dismissed its package, ended receiving and removed its local debug forward.
- **Debug, test and release builds succeeded** for the debug app, instrumentation APK, unit tests, lint and optimized release AAB. Lint has zero errors; three remaining warnings are SDK/Gradle/library update notices, not unused code/resources. - **Debug, test and release builds succeeded** for the debug app, instrumentation APK, unit tests, lint and optimized release AAB. Lint has zero errors; three remaining warnings are SDK/Gradle/library update notices, not unused code/resources.
- Release inspection found exactly the three bundled web assets, no fixture APK/test payload, no package-visibility queries, one exported launcher and non-exported service/installer receiver. The release dependency graph contains ZXing Core, Kotlin stdlib and its annotations dependency. - Release inspection found exactly the three bundled web assets, no fixture APK/test payload, no package-visibility queries, one exported launcher and non-exported service/installer receiver. The release dependency graph contains ZXing Core, Kotlin stdlib and its annotations dependency.
- The unchanged Gradle distribution version is checksum-pinned to its official download. Release output is unsigned when signing inputs are absent; incomplete signing configuration fails clearly. - The unchanged Gradle distribution version is checksum-pinned to its official download. Release output is unsigned when signing inputs are absent; incomplete signing configuration fails clearly.
Ten watch product-state screenshots at each tested size, browser screenshots, detailed XML, text logs and browser summaries are generated under app/build/reports and app/build/test-results. They are not source assets or claims of universal hardware/browser support. Ten watch product-state screenshots at each tested size, browser screenshots, detailed XML, text logs and browser summaries are generated under app/build/reports and app/build/test-results. They are not source assets or claims of universal hardware/browser support. No elapsed-time test certifies indefinite availability: long-duration screen-off/power behavior remains a hardware gate, and the receiver has no product expiry timer. Successful large uploads prove receipt/review, not successful installation of every large app.
## Hardware-specific release matrix ## Hardware-specific release matrix
- Fresh Google Play delivery, source approval and system confirmation on supported Galaxy Watch 7 and other firmware/regions, without preexisting source trust or developer setup. Include denied/revoked permission and cancellation. - Fresh Google Play delivery, source approval and system confirmation on supported Galaxy Watch 7 and other firmware/regions, without preexisting source trust or developer setup. Include denied/revoked permission and cancellation.
- Real maximum-size transfers, interruption, ten-minute expiry, repeated sessions, IP/network changes, guest/client-isolated networks, VPNs and browser local-network permission prompts. - Transfers near actual free-storage capacity, prolonged receiving, interruption, repeated sessions, IP/network changes, guest/client-isolated networks, VPNs and browser local-network permission prompts.
- Long screen-off/Doze behavior, low battery/battery saver, charging transitions, memory/thermal behavior and measured battery consumption. Timed locks and bounded buffers alone are not measurements. - Long screen-off/Doze behavior, low battery/battery saver, charging transitions, memory/thermal behavior and measured battery consumption. Timed locks and bounded buffers alone are not measurements.
- Actual low storage and processor/SDK/package/update conflicts; system developer verification and managed-device restrictions. The OS is the final compatibility/security authority. - Actual low storage and processor/SDK/package/update conflicts; system developer verification and managed-device restrictions. The OS is the final compatibility/security authority.
- TalkBack, rotary interaction, large font and physical small-round displays; camera scanning of QR on real displays under varied lighting. - TalkBack, rotary interaction, large font and physical small-round displays; camera scanning of QR on real displays under varied lighting.
+54
View File
@@ -0,0 +1,54 @@
#!/usr/bin/env python3
"""Create a signed, uncompressed APK fixture for large-file transfer tests; never shipped."""
import argparse
import os
from pathlib import Path
import shutil
import subprocess
import zipfile
from emulator_utils import ROOT
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--bytes", type=int, default=64 * 1024 * 1024, help="Size of the stored test asset")
args = parser.parse_args()
if args.bytes <= 0:
parser.error("Use a positive asset size.")
source = ROOT / "qa/fixture/build/outputs/apk/debug/qaFixture-debug.apk"
if not source.exists():
raise SystemExit("Build :qaFixture:assembleDebug first.")
sdk = os.environ.get("ANDROID_HOME") or os.environ.get("ANDROID_SDK_ROOT")
if not sdk:
for line in (ROOT / "local.properties").read_text().splitlines():
if line.startswith("sdk.dir="):
sdk = line.removeprefix("sdk.dir=")
versions = sorted((Path(sdk) / "build-tools").glob("*/apksigner"))
if not versions:
raise SystemExit("Install Android SDK Build Tools with apksigner.")
folder = ROOT / "app/build/qa"
folder.mkdir(parents=True, exist_ok=True)
unsigned = folder / "large-unsigned.apk"
output = folder / "large-fixture.apk"
try:
with zipfile.ZipFile(source) as original, zipfile.ZipFile(unsigned, "w") as target:
for entry in original.infolist():
if entry.filename.upper().startswith("META-INF/"):
continue
with original.open(entry) as incoming, target.open(entry, "w") as outgoing:
shutil.copyfileobj(incoming, outgoing, 64 * 1024)
asset = zipfile.ZipInfo("assets/pakkit-transfer-test.bin")
asset.compress_type = zipfile.ZIP_STORED
asset.file_size = args.bytes
block = bytes(64 * 1024)
remaining = args.bytes
with target.open(asset, "w") as stream:
while remaining:
chunk = min(remaining, len(block))
stream.write(block[:chunk])
remaining -= chunk
subprocess.run([str(versions[-1]), "sign", "--ks", str(Path.home() / ".android/debug.keystore"),
"--ks-pass", "pass:android", "--key-pass", "pass:android", "--ks-key-alias", "androiddebugkey",
"--out", str(output), str(unsigned)], check=True)
subprocess.run([str(versions[-1]), "verify", str(output)], check=True)
print(f"{output} ({output.stat().st_size:,} bytes)")
finally:
unsigned.unlink(missing_ok=True)
+2 -4
View File
@@ -61,15 +61,13 @@ def tap_text(serial, label, attempts=6):
def session_url(serial): def session_url(serial):
tap_text(serial, "View link")
for _ in range(6): for _ in range(6):
tree = ui(serial) tree = ui(serial)
for node in tree.iter("node"): for node in tree.iter("node"):
value = node.get("text", "") value = node.get("text", "")
if value.startswith("http://") and "#" in value: if value.startswith("http://") and ":8787" in value:
tap_text(serial, "Back to code")
return value return value
bounds = next(tree.iter("node")).get("bounds") bounds = next(tree.iter("node")).get("bounds")
_, _, width, height = map(int, re.findall(r"\d+", bounds)) _, _, width, height = map(int, re.findall(r"\d+", bounds))
adb(serial, "shell", "input", "swipe", str(width // 2), str(height * 3 // 4), str(width // 2), str(height // 4), "300") adb(serial, "shell", "input", "swipe", str(width // 2), str(height * 3 // 4), str(width // 2), str(height // 4), "300")
raise RuntimeError("No private session link found. Check source approval and emulator Wi-Fi.") raise RuntimeError("No receiving address found. Check emulator Wi-Fi.")
+22 -3
View File
@@ -13,6 +13,7 @@ parser.add_argument("--watch", required=True, help="Wear OS emulator serial, e.g
parser.add_argument("--browser", help="Optional Android emulator serial with Chrome initialized") parser.add_argument("--browser", help="Optional Android emulator serial with Chrome initialized")
parser.add_argument("--small", action="store_true", help="Run round UI tests at 192dp and 1.3x font size") parser.add_argument("--small", action="store_true", help="Run round UI tests at 192dp and 1.3x font size")
parser.add_argument("--skip-build", action="store_true") parser.add_argument("--skip-build", action="store_true")
parser.add_argument("--large", action="store_true", help="Use app/build/qa/large-fixture.apk for the real browser upload")
args = parser.parse_args() args = parser.parse_args()
if args.browser == args.watch: if args.browser == args.watch:
parser.error("Use distinct Wear OS and Android browser emulator serials.") parser.error("Use distinct Wear OS and Android browser emulator serials.")
@@ -51,7 +52,7 @@ try:
print(output, flush=True) print(output, flush=True)
screenshots = report_dir / ("watch-product-small" if args.small else "watch-product") screenshots = report_dir / ("watch-product-small" if args.small else "watch-product")
screenshots.mkdir(exist_ok=True) screenshots.mkdir(exist_ok=True)
for name in ["home", "scan", "link", "sending", "checking", "ready", "installing", "confirm", "failed", "installed"]: for name in ["home", "scan", "browser-approval", "sending", "checking", "ready", "installing", "confirm", "failed", "installed"]:
image = adb(args.watch, "exec-out", "cat", f"/sdcard/Android/data/meghdad.pakkit/files/product-review/{name}.png") image = adb(args.watch, "exec-out", "cat", f"/sdcard/Android/data/meghdad.pakkit/files/product-review/{name}.png")
(screenshots / f"{name}.png").write_bytes(image) (screenshots / f"{name}.png").write_bytes(image)
@@ -78,10 +79,28 @@ if args.browser:
tap_text(args.watch, "Start receiving") tap_text(args.watch, "Start receiving")
url = session_url(args.watch) url = session_url(args.watch)
env = dict(os.environ, PAKKIT_SESSION_URL=url, PAKKIT_CDP_URL=f"http://127.0.0.1:{endpoint}") env = dict(os.environ, PAKKIT_SESSION_URL=url, PAKKIT_CDP_URL=f"http://127.0.0.1:{endpoint}")
subprocess.run(["node", str(ROOT / "web-tests/emulator.test.cjs")], cwd=ROOT, env=env, check=True) remote_fixture = "/sdcard/Android/data/com.android.chrome/files/pakkit-large.apk"
if args.large:
fixture = ROOT / "app/build/qa/large-fixture.apk"
if not fixture.exists():
raise RuntimeError("Run scripts/create-large-fixture.py first.")
adb(args.browser, "shell", "mkdir", "-p", "/sdcard/Android/data/com.android.chrome/files")
adb(args.browser, "push", str(fixture), remote_fixture)
env.update(PAKKIT_TEST_APK=str(fixture), PAKKIT_BROWSER_FILE=remote_fixture)
browser_test = subprocess.Popen(["node", str(ROOT / "web-tests/emulator.test.cjs")], cwd=ROOT, env=env)
try:
tap_text(args.watch, "Allow browser", attempts=12)
if browser_test.wait(timeout=180) != 0:
raise RuntimeError("Android browser transfer failed.")
finally:
if browser_test.poll() is None:
browser_test.terminate()
browser_test.wait(timeout=10)
adb(args.watch, "shell", "am", "start", "-W", "-n", "meghdad.pakkit/.ui.WatchActivity") adb(args.watch, "shell", "am", "start", "-W", "-n", "meghdad.pakkit/.ui.WatchActivity")
tap_text(args.watch, "Remove file") tap_text(args.watch, "Remove file")
tap_text(args.watch, "End session") tap_text(args.watch, "Stop receiving")
finally: finally:
if args.large:
adb(args.browser, "shell", "rm", "-f", "/sdcard/Android/data/com.android.chrome/files/pakkit-large.apk")
adb(args.browser, "forward", "--remove", f"tcp:{endpoint}") adb(args.browser, "forward", "--remove", f"tcp:{endpoint}")
adb(args.watch, "shell", "am", "force-stop", "meghdad.pakkit") adb(args.watch, "shell", "am", "force-stop", "meghdad.pakkit")
+84 -17
View File
@@ -11,7 +11,9 @@ let state = 'waiting',
failure = false, failure = false,
hold = false, hold = false,
bytesReceived = 0, bytesReceived = 0,
disconnected = false; disconnected = false,
approved = true,
denied = false;
const server = http.createServer(async (request, response) => { const server = http.createServer(async (request, response) => {
response.setHeader('Cache-Control', 'no-store'); response.setHeader('Cache-Control', 'no-store');
const routes = { const routes = {
@@ -26,8 +28,18 @@ const server = http.createServer(async (request, response) => {
return; return;
} }
response.setHeader('Content-Type', 'application/json'); response.setHeader('Content-Type', 'application/json');
if (request.headers.authorization !== 'Bearer test-key') { if (request.url === '/api/connect' || request.url === '/api/retry') {
response.writeHead(403).end('{}'); if (request.url === '/api/retry') denied = false;
response.end(
JSON.stringify({
connection: approved ? 'approved' : denied ? 'denied' : 'pending',
credential: 'test-browser',
}),
);
} else if (request.headers.authorization !== 'Bearer test-browser') {
response.writeHead(403).end(JSON.stringify({ connection: 'unknown' }));
} else if (!approved) {
response.writeHead(403).end(JSON.stringify({ connection: denied ? 'denied' : 'pending' }));
} else if (request.url === '/api/status') { } else if (request.url === '/api/status') {
if (disconnected) { if (disconnected) {
response.writeHead(503).end('{}'); response.writeHead(503).end('{}');
@@ -38,11 +50,11 @@ const server = http.createServer(async (request, response) => {
state, state,
label: 'Test app', label: 'Test app',
detail: 'Please review your watch.', detail: 'Please review your watch.',
expiresIn: 500, connection: 'approved',
}), }),
); );
} else if (request.url === '/api/upload') { } else if (request.url === '/api/upload') {
((bytesReceived = 0), (disconnected = false)); bytesReceived = 0;
for await (const chunk of request) bytesReceived += chunk.length; for await (const chunk of request) bytesReceived += chunk.length;
if (hold) return; // Cancellation while awaiting a response. if (hold) return; // Cancellation while awaiting a response.
if (failure) if (failure)
@@ -76,7 +88,7 @@ const server = http.createServer(async (request, response) => {
colorScheme: theme, colorScheme: theme,
reducedMotion: 'reduce', reducedMotion: 'reduce',
}); });
await page.goto(`${origin}/#test-key`); await page.goto(origin);
await page.getByText('Connected to your watch', { exact: true }).waitFor(); await page.getByText('Connected to your watch', { exact: true }).waitFor();
assert.equal( assert.equal(
await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), await page.evaluate(() => document.documentElement.scrollWidth > innerWidth),
@@ -84,7 +96,7 @@ const server = http.createServer(async (request, response) => {
`${width}px/${theme} overflow`, `${width}px/${theme} overflow`,
); );
assert.equal(await page.evaluate(() => document.documentElement.dataset.theme), theme); assert.equal(await page.evaluate(() => document.documentElement.dataset.theme), theme);
assert.equal(new URL(page.url()).hash, '', 'Secret must be removed from visible history.'); assert.equal(new URL(page.url()).hash, '', 'No key in the address.');
if (width === 390 || width === 1440) if (width === 390 || width === 1440)
await page.screenshot({ await page.screenshot({
path: path.join(reports, `web-${width}-${theme}.png`), path: path.join(reports, `web-${width}-${theme}.png`),
@@ -94,20 +106,53 @@ const server = http.createServer(async (request, response) => {
await page.close(); await page.close();
} }
} }
const page = await browser.newPage(); const context = await browser.newContext();
const page = await context.newPage();
const errors = []; const errors = [];
page.on('pageerror', (error) => errors.push(error.message)); page.on('pageerror', (error) => errors.push(error.message));
approved = false;
await page.goto(origin); await page.goto(origin);
await page.locator('#access').fill('test-key'); await page.getByText('Tap Allow browser on your watch.', { exact: false }).waitFor();
await page.getByRole('button', { name: 'Connect to watch' }).click(); assert.equal(
await page.locator('input:not([type="file"])').count(),
0,
'No manual authentication inputs',
);
denied = true;
await page.getByRole('heading', { name: 'Maybe next time?' }).waitFor();
await page.getByRole('button', { name: 'Try again', exact: true }).click();
await page.getByRole('heading', { name: 'A quick hello' }).waitFor();
approved = true;
await page.getByText('Connected to your watch', { exact: true }).waitFor();
await page.reload();
await page.getByText('Connected to your watch', { exact: true }).waitFor(); await page.getByText('Connected to your watch', { exact: true }).waitFor();
checks++; checks++;
await page.locator('#file').setInputFiles({ assert.deepEqual(await page.context().cookies(origin), [], 'No host-wide authorization cookie');
name: 'wrong.txt', let peerAuthorization;
mimeType: 'text/plain', const peer = http.createServer((request, response) => {
buffer: Buffer.from('test'), peerAuthorization = request.headers.authorization;
response.setHeader('Content-Type', 'text/html');
response.end('<!doctype html><title>Other watch app</title>');
}); });
await page.locator('#message').getByText('Choose a single APK', { exact: false }).waitFor(); await new Promise((resolve) => peer.listen(0, '127.0.0.1', resolve));
try {
const other = await page.context().newPage();
await other.goto(`http://127.0.0.1:${peer.address().port}/`);
assert.equal(await other.evaluate(() => localStorage.getItem('pakkitAccess')), null);
assert.equal(peerAuthorization, undefined, 'Other ports do not receive access credentials');
await other.close();
await page.bringToFront();
} finally {
peer.closeAllConnections();
peer.close();
}
checks++;
await page.locator('#file').setInputFiles({
name: 'empty.apk',
mimeType: 'application/octet-stream',
buffer: Buffer.alloc(0),
});
await page.locator('#message').getByText('This file is empty.', { exact: false }).waitFor();
checks++; checks++;
const file = { const file = {
name: 'test.apk', name: 'test.apk',
@@ -136,8 +181,15 @@ const server = http.createServer(async (request, response) => {
checks++; checks++;
state = 'installed'; state = 'installed';
await page.getByRole('heading', { name: 'Looks good on you.' }).waitFor(); await page.getByRole('heading', { name: 'Looks good on you.' }).waitFor();
state = 'waiting';
await page.getByRole('button', { name: 'Send another app' }).click(); await page.getByRole('button', { name: 'Send another app' }).click();
await page.locator('#file').setInputFiles(file);
await new Promise((resolve) => setTimeout(resolve, 1700));
assert.equal(
await page.locator('#selection').isVisible(),
true,
'A completed app does not block choosing another',
);
state = 'waiting';
checks++; checks++;
await page.locator('#file').setInputFiles(file); await page.locator('#file').setInputFiles(file);
hold = true; hold = true;
@@ -148,7 +200,7 @@ const server = http.createServer(async (request, response) => {
disconnected = true; disconnected = true;
await page.getByText('Watch out of reach', { exact: true }).waitFor(); await page.getByText('Watch out of reach', { exact: true }).waitFor();
assert.equal(await page.locator('#send').isDisabled(), true); assert.equal(await page.locator('#send').isDisabled(), true);
disconnected = false; ((disconnected = false), (approved = true), (denied = false));
await page.getByText('Connected to your watch', { exact: true }).waitFor(); await page.getByText('Connected to your watch', { exact: true }).waitFor();
checks++; checks++;
await page.getByRole('button', { name: 'Change color theme' }).click(); await page.getByRole('button', { name: 'Change color theme' }).click();
@@ -177,6 +229,21 @@ const server = http.createServer(async (request, response) => {
); );
checks++; checks++;
hold = false;
const largePath = path.join(reports, 'browser-large-fixture.apk');
const descriptor = fs.openSync(largePath, 'w');
fs.ftruncateSync(descriptor, 64 * 1024 * 1024);
fs.closeSync(descriptor);
await page.locator('#file').setInputFiles(largePath);
await page.getByRole('button', { name: 'Send to watch' }).click();
await page.getByRole('heading', { name: 'Made it to your watch' }).waitFor();
assert.equal(
bytesReceived,
64 * 1024 * 1024,
'Large upload streams without the former size limit',
);
fs.unlinkSync(largePath);
checks++;
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
const result = { const result = {
browser: await browser.version(), browser: await browser.version(),
+25 -10
View File
@@ -19,6 +19,8 @@ const path = require('node:path');
page.on('pageerror', (error) => errors.push(error.message)); page.on('pageerror', (error) => errors.push(error.message));
await page.goto(session.href, { timeout: 20000 }); await page.goto(session.href, { timeout: 20000 });
await page.getByText('Connected to your watch', { exact: true }).waitFor({ timeout: 20000 }); await page.getByText('Connected to your watch', { exact: true }).waitFor({ timeout: 20000 });
assert.equal(session.port, '8787');
assert.equal(session.hash, '');
assert.equal( assert.equal(
await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), await page.evaluate(() => document.documentElement.scrollWidth > innerWidth),
false, false,
@@ -27,25 +29,37 @@ const path = require('node:path');
path: path.join(reports, 'android-browser.png'), path: path.join(reports, 'android-browser.png'),
fullPage: true, fullPage: true,
}); });
await page.locator('#file').setInputFiles({ const fixture =
name: 'pakkit-test.apk', process.env.PAKKIT_TEST_APK ||
mimeType: 'application/vnd.android.package-archive', path.resolve(__dirname, '../qa/fixture/build/outputs/apk/debug/qaFixture-debug.apk');
buffer: fs.readFileSync( if (process.env.PAKKIT_BROWSER_FILE) {
path.resolve(__dirname, '../qa/fixture/build/outputs/apk/debug/qaFixture-debug.apk'), const cdp = await context.newCDPSession(page);
), const { root } = await cdp.send('DOM.getDocument');
}); const { nodeId } = await cdp.send('DOM.querySelector', {
nodeId: root.nodeId,
selector: '#file',
});
await cdp.send('DOM.setFileInputFiles', { nodeId, files: [process.env.PAKKIT_BROWSER_FILE] });
await cdp.detach();
} else {
await page.locator('#file').setInputFiles({
name: 'pakkit-test.apk',
mimeType: 'application/vnd.android.package-archive',
buffer: fs.readFileSync(fixture),
});
}
await page.getByRole('button', { name: 'Send to watch' }).click(); await page.getByRole('button', { name: 'Send to watch' }).click();
await page.getByRole('heading', { name: 'Made it to your watch' }).waitFor({ timeout: 30000 }); await page.getByRole('heading', { name: 'Made it to your watch' }).waitFor({ timeout: 30000 });
await page.screenshot({ await page.screenshot({
path: path.join(reports, 'android-browser-review.png'), path: path.join(reports, 'android-browser-review.png'),
fullPage: true, fullPage: true,
}); });
const status = await page.evaluate(async (token) => { const status = await page.evaluate(async () => {
const response = await fetch('/api/status', { const response = await fetch('/api/status', {
headers: { Authorization: `Bearer ${token}` }, headers: { Authorization: 'Bearer ' + localStorage.getItem('pakkitAccess') },
}); });
return response.json(); return response.json();
}, session.hash.slice(1)); });
assert.equal(status.state, 'ready'); assert.equal(status.state, 'ready');
assert.equal(status.label, 'Pakkit QA fixture'); assert.equal(status.label, 'Pakkit QA fixture');
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
@@ -54,6 +68,7 @@ const path = require('node:path');
directEmulatorWifi: true, directEmulatorWifi: true,
upload: 'ready', upload: 'ready',
javascriptErrors: errors, javascriptErrors: errors,
uploadedBytes: fs.statSync(fixture).size,
}; };
fs.writeFileSync( fs.writeFileSync(
path.join(reports, 'android-browser.json'), path.join(reports, 'android-browser.json'),