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:
41 files changed
+1202
-522
No files matched your search
@@ -8,12 +8,12 @@ Send an APK from your browser to your Wear OS watch, then approve installation o
|
||||
|
||||
1. Open Pakkit on a supported watch.
|
||||
2. Connect the watch and browser device to the same trusted Wi-Fi.
|
||||
3. Tap **Start receiving** and scan the QR code. For manual entry, tap **View link** on the watch and open the complete link in your browser.
|
||||
4. Select one complete `.apk` up to **50 MiB**. Watch transfer progress in the browser and on the watch.
|
||||
5. Review the app on your watch. If prompted, tap **Allow installs** to grant source permission, then tap **Install** and approve it.
|
||||
6. End the receiving session when finished. Sessions automatically end after ten minutes or on Wi-Fi loss.
|
||||
3. Tap **Start receiving** and scan the QR code or open the displayed address. The port is always **8787**.
|
||||
4. Tap **Allow browser** on your watch, then choose an APK in the browser. There is no product file-size limit; available storage and Android determine what fits.
|
||||
5. Review the app and tap **Install** on your watch. First-time **Allow installs** grants source permission and continues the requested installation. Approve it in Android’s installer.
|
||||
6. Tap **Stop receiving** when finished. Receiving has no app-imposed expiry and reconnects when Wi-Fi returns.
|
||||
|
||||
The local connection uses **unencrypted HTTP**. Use trusted Wi-Fi and keep the private link secret. Package inspection checks format and compatibility; it does not certify app safety. Source approval, firmware security policy and Android’s installer determine whether installation is available. Split packages and app bundles are unsupported. See [platform constraints](docs/PLATFORM.md).
|
||||
The local connection uses **unencrypted HTTP**. Use trusted Wi-Fi and approve only browsers you recognize. Package inspection checks format and compatibility; it does not certify app safety. Source approval, firmware security policy and Android’s installer determine whether installation is available. Split packages and app bundles are unsupported. See [platform constraints](docs/PLATFORM.md).
|
||||
|
||||
The current artifacts are development builds. Public distribution requires the checks in [release preparation](docs/RELEASE.md).
|
||||
|
||||
@@ -55,4 +55,4 @@ python3 scripts/test-emulators.py --watch emulator-5554 --small --skip-build
|
||||
|
||||
For browser tests and real Android-Emulator-to-Wear-Emulator uploads, see [development and testing](docs/DEVELOPMENT.md). Results and screenshots are generated under `app/build/reports/validation`, not checked into source control.
|
||||
|
||||
[Architecture](docs/ARCHITECTURE.md) · [Design](docs/DESIGN.md) · [Platform](docs/PLATFORM.md) · [Privacy](docs/PRIVACY.md) · [Release](docs/RELEASE.md) · [Validation](docs/VALIDATION.md)
|
||||
[Restriction audit](docs/RESTRICTIONS.md) · [Architecture](docs/ARCHITECTURE.md) · [Design](docs/DESIGN.md) · [Platform](docs/PLATFORM.md) · [Privacy](docs/PRIVACY.md) · [Release](docs/RELEASE.md) · [Validation](docs/VALIDATION.md)
|
||||
@@ -14,16 +14,17 @@ import org.junit.runner.RunWith
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class LocalReceiveTest : WatchTest() {
|
||||
@Test
|
||||
fun authenticatedUploadVerifiesPackageAndStopRevokesPrivateLink() {
|
||||
fun watchApprovedBrowserCanUploadAndStoppingRevokesAccess() {
|
||||
openWatch()
|
||||
context.startForegroundService(Intent(context, ReceiveService::class.java))
|
||||
await(30_000) { Receiving.state.url != null }
|
||||
val url = URI(requireNotNull(Receiving.state.url))
|
||||
val sessions = context.packageManager.packageInstaller.mySessions.map { it.sessionId }
|
||||
var browserCredential: String? = null
|
||||
fun request(
|
||||
method: String,
|
||||
path: String,
|
||||
token: String? = url.fragment,
|
||||
credential: String? = browserCredential,
|
||||
origin: String = "http://${url.authority}",
|
||||
host: String = url.authority,
|
||||
body: ByteArray? = null,
|
||||
@@ -33,8 +34,8 @@ class LocalReceiveTest : WatchTest() {
|
||||
socket.soTimeout = 10_000
|
||||
val headers =
|
||||
"$method $path HTTP/1.1\r\nHost: $host\r\n" +
|
||||
(token?.let { "Authorization: Bearer $it\r\n" } ?: "") +
|
||||
"Origin: $origin\r\n" +
|
||||
(credential?.let { "Authorization: Bearer $it\r\n" } ?: "") +
|
||||
"Origin: $origin\r\nUser-Agent: Chrome Android\r\n" +
|
||||
(contentLength?.let {
|
||||
"Content-Type: application/octet-stream\r\nContent-Length: $it\r\n"
|
||||
} ?: "") +
|
||||
@@ -67,11 +68,26 @@ class LocalReceiveTest : WatchTest() {
|
||||
head.toString() + bytes.toString(Charsets.UTF_8)
|
||||
}
|
||||
}
|
||||
fun assertUploadWakeReleased() {
|
||||
await { Receiving.state.total == 0L }
|
||||
val dump =
|
||||
instrumentation.uiAutomation.executeShellCommand("dumpsys power").use { descriptor
|
||||
->
|
||||
android.os.ParcelFileDescriptor.AutoCloseInputStream(descriptor).use {
|
||||
it.readBytes().toString(Charsets.UTF_8)
|
||||
}
|
||||
}
|
||||
assertTrue("Power state must be observable", dump.contains("Wake Locks:"))
|
||||
assertFalse(
|
||||
"Completed requests must not hold an upload wake lock",
|
||||
Regex("(?m)^\\s*PARTIAL_WAKE_LOCK.*pakkit:upload.*$").containsMatchIn(dump),
|
||||
)
|
||||
}
|
||||
assertTrue(request("GET", "/").contains("Pack it."))
|
||||
assertTrue(request("GET", "/api/status", token = null).startsWith("HTTP/1.1 403"))
|
||||
assertTrue(request("GET", "/api/status", token = "wrong").startsWith("HTTP/1.1 403"))
|
||||
assertTrue(request("GET", "/api/status", credential = null).startsWith("HTTP/1.1 403"))
|
||||
assertTrue(request("GET", "/api/status", credential = "wrong").startsWith("HTTP/1.1 403"))
|
||||
assertTrue(
|
||||
request("GET", "/api/status", host = "attacker.example").startsWith("HTTP/1.1 403"),
|
||||
request("GET", "/api/status", host = "attacker.example").startsWith("HTTP/1.1 403")
|
||||
)
|
||||
assertTrue(
|
||||
request(
|
||||
@@ -80,23 +96,33 @@ class LocalReceiveTest : WatchTest() {
|
||||
origin = "https://attacker.example",
|
||||
body = byteArrayOf(1),
|
||||
)
|
||||
.startsWith("HTTP/1.1 403"),
|
||||
.startsWith("HTTP/1.1 403")
|
||||
)
|
||||
val connection = request("POST", "/api/connect")
|
||||
browserCredential =
|
||||
org.json.JSONObject(connection.substringAfter("\r\n\r\n")).getString("credential")
|
||||
assertFalse(connection.contains("Set-Cookie:"))
|
||||
assertTrue(request("POST", "/api/upload", body = byteArrayOf(1)).startsWith("HTTP/1.1 403"))
|
||||
assertTrue(request("GET", "/api/status").contains("pending"))
|
||||
assertTrue(Receiving.answerBrowser(requireNotNull(Receiving.state.browserRequest).id, true))
|
||||
assertTrue(request("GET", "/api/status").startsWith("HTTP/1.1 200"))
|
||||
assertFalse(request("GET", "/api/status").contains("expiresIn"))
|
||||
assertTrue(
|
||||
request("POST", "/api/upload", contentLength = 52_428_801).startsWith("HTTP/1.1 400"),
|
||||
request("POST", "/api/upload", contentLength = Long.MAX_VALUE).contains("storage")
|
||||
)
|
||||
assertTrue(
|
||||
request("POST", "/api/upload", body = "invalid APK".toByteArray())
|
||||
.startsWith("HTTP/1.1 400"),
|
||||
.startsWith("HTTP/1.1 400")
|
||||
)
|
||||
assertNull(store.pending())
|
||||
assertTrue(
|
||||
request("POST", "/api/upload", body = "short".toByteArray(), contentLength = 100)
|
||||
.startsWith("HTTP/1.1 400"),
|
||||
.startsWith("HTTP/1.1 400")
|
||||
)
|
||||
assertNull(store.pending())
|
||||
assertEquals(0L, Receiving.state.total)
|
||||
assertEquals("Ready to receive", Receiving.state.detail)
|
||||
assertUploadWakeReleased()
|
||||
val fixture = instrumentation.context.assets.open("fixture.apk").use { it.readBytes() }
|
||||
assertTrue(request("POST", "/api/upload", body = fixture).startsWith("HTTP/1.1 200"))
|
||||
assertEquals(InstallState.READY, store.pending()?.state)
|
||||
@@ -107,10 +133,48 @@ class LocalReceiveTest : WatchTest() {
|
||||
)
|
||||
assertTrue(request("POST", "/api/upload", body = byteArrayOf(1)).startsWith("HTTP/1.1 409"))
|
||||
assertTrue(request("GET", "/api/status").contains("ready"))
|
||||
assertUploadWakeReleased()
|
||||
// A finished install does not require a separate Done tap before the next upload.
|
||||
for (terminal in listOf(InstallState.INSTALLED, InstallState.FAILED)) {
|
||||
store.update(requireNotNull(store.pending()).id, terminal, "Finished")
|
||||
assertTrue(request("POST", "/api/upload", body = fixture).startsWith("HTTP/1.1 200"))
|
||||
assertEquals(InstallState.READY, store.pending()?.state)
|
||||
}
|
||||
context.stopService(Intent(context, ReceiveService::class.java))
|
||||
await { !Receiving.state.active }
|
||||
assertNull(Receiving.state.url)
|
||||
assertTrue(runCatching { Socket(url.host, url.port).close() }.isFailure)
|
||||
context.startForegroundService(Intent(context, ReceiveService::class.java))
|
||||
await(30_000) { Receiving.state.url != null }
|
||||
assertEquals(url.toString(), Receiving.state.url)
|
||||
assertTrue(request("GET", "/api/status").startsWith("HTTP/1.1 403"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun losingWifiWaitsForReconnectionWithoutEndingReceiving() {
|
||||
openWatch()
|
||||
context.startForegroundService(Intent(context, ReceiveService::class.java))
|
||||
await(30_000) { Receiving.state.url != null }
|
||||
fun shell(command: String) {
|
||||
instrumentation.uiAutomation.executeShellCommand(command).use { descriptor ->
|
||||
android.os.ParcelFileDescriptor.AutoCloseInputStream(descriptor).use {
|
||||
it.readBytes()
|
||||
}
|
||||
}
|
||||
}
|
||||
try {
|
||||
shell("cmd wifi set-wifi-enabled disabled")
|
||||
await(15_000) { Receiving.state.url == null }
|
||||
assertTrue(Receiving.state.active)
|
||||
shell("cmd wifi set-wifi-enabled enabled")
|
||||
shell("cmd wifi connect-network AndroidWifi open")
|
||||
await(30_000) { Receiving.state.url != null }
|
||||
assertTrue(Receiving.state.active)
|
||||
assertEquals(8787, URI(requireNotNull(Receiving.state.url)).port)
|
||||
} finally {
|
||||
shell("cmd wifi set-wifi-enabled enabled")
|
||||
shell("cmd wifi connect-network AndroidWifi open")
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -7,16 +7,30 @@ import java.util.zip.ZipEntry
|
||||
import java.util.zip.ZipOutputStream
|
||||
import meghdad.pakkit.apk.ApkRules
|
||||
import meghdad.pakkit.apk.PackageInspector
|
||||
import meghdad.pakkit.apk.userMessage
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class PackageInspectionTest : WatchTest() {
|
||||
@Test
|
||||
fun runningOutOfSpaceHasActionableFeedbackWithoutRawPaths() {
|
||||
val failure =
|
||||
java.io.IOException(
|
||||
"/data/private/file.apk",
|
||||
android.system.ErrnoException("write", android.system.OsConstants.ENOSPC),
|
||||
)
|
||||
assertEquals(
|
||||
"Free some space on your watch, then try again.",
|
||||
failure.userMessage("Try again."),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun selfUpdateIsRejectedBeforeCreatingAnInstallSession() {
|
||||
val ownApk = File(context.applicationInfo.sourceDir)
|
||||
val digest = ownApk.inputStream().use { ApkRules.copyBounded(it).second }
|
||||
val digest = ownApk.inputStream().use { ApkRules.copyAndHash(it).second }
|
||||
val result = runCatching { PackageInspector.inspect(context, ownApk, digest) }
|
||||
assertTrue(result.isFailure)
|
||||
assertTrue(result.exceptionOrNull()?.message.orEmpty().contains("Google Play"))
|
||||
@@ -31,7 +45,7 @@ class PackageInspectionTest : WatchTest() {
|
||||
it.write("Not an app".toByteArray())
|
||||
it.closeEntry()
|
||||
}
|
||||
val digest = file.inputStream().use { ApkRules.copyBounded(it).second }
|
||||
val digest = file.inputStream().use { ApkRules.copyAndHash(it).second }
|
||||
assertTrue(runCatching { PackageInspector.inspect(context, file, digest) }.isFailure)
|
||||
} finally {
|
||||
file.delete()
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package meghdad.pakkit
|
||||
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import meghdad.pakkit.apk.ApkRules
|
||||
import meghdad.pakkit.apk.InstallState
|
||||
import meghdad.pakkit.data.PackageStore
|
||||
import org.junit.Assert.*
|
||||
@@ -10,6 +9,49 @@ import org.junit.runner.RunWith
|
||||
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class PackageStoreTest : WatchTest() {
|
||||
@Test
|
||||
fun failedMetadataWriteRestoresThePreviousReview() {
|
||||
val apk = fixture()
|
||||
store.stage(apk)
|
||||
var failNext = true
|
||||
val real = store.preferences
|
||||
val faulty =
|
||||
object : android.content.SharedPreferences by real {
|
||||
override fun edit(): android.content.SharedPreferences.Editor {
|
||||
val editor = real.edit()
|
||||
return object : android.content.SharedPreferences.Editor by editor {
|
||||
override fun putString(
|
||||
key: String,
|
||||
value: String?,
|
||||
): android.content.SharedPreferences.Editor {
|
||||
editor.putString(key, value)
|
||||
return this
|
||||
}
|
||||
|
||||
override fun commit(): Boolean {
|
||||
val written = editor.commit()
|
||||
if (failNext) {
|
||||
failNext = false
|
||||
return false
|
||||
}
|
||||
return written
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
val wrapped =
|
||||
object : android.content.ContextWrapper(context) {
|
||||
override fun getSharedPreferences(name: String, mode: Int) = faulty
|
||||
}
|
||||
assertTrue(
|
||||
runCatching {
|
||||
PackageStore(wrapped).update(apk.id, InstallState.INSTALLING, "Preparing")
|
||||
}
|
||||
.isFailure
|
||||
)
|
||||
assertEquals(apk, store.pending())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun persistsReviewAcrossStoreInstancesAndRejectsReplacement() {
|
||||
val apk = fixture()
|
||||
@@ -20,14 +62,14 @@ class PackageStoreTest : WatchTest() {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun expiredReviewAndOrphanedFileAreRemoved() {
|
||||
val apk = fixture().copy(created = System.currentTimeMillis() - ApkRules.TTL_MS)
|
||||
fun oldReviewsRemainAvailableAndUncommittedFilesAreCleaned() {
|
||||
val apk = fixture().copy(created = 1L)
|
||||
store.stage(apk)
|
||||
val orphan = fixture()
|
||||
store.file(orphan.id).setLastModified(System.currentTimeMillis() - ApkRules.TTL_MS - 1000)
|
||||
store.file(orphan.id).setLastModified(System.currentTimeMillis())
|
||||
store.clean()
|
||||
assertNull(store.pending())
|
||||
assertFalse(store.file(apk.id).exists())
|
||||
assertEquals(apk, store.pending())
|
||||
assertTrue(store.file(apk.id).exists())
|
||||
assertFalse(store.file(orphan.id).exists())
|
||||
}
|
||||
|
||||
|
||||
@@ -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()
|
||||
try {
|
||||
Receiving.begin(owner)
|
||||
Receiving.update(owner) { it.copy(url = "http://10.0.2.16:8080/#test-display-link") }
|
||||
Receiving.update(owner) { it.copy(url = "http://10.0.2.16:8787/") }
|
||||
openWatch()
|
||||
capture("scan")
|
||||
instrumentation.runOnMainSync {
|
||||
screen().filterIsInstance<Button>().single { it.text == "View link" }.performClick()
|
||||
assertActionsReachable()
|
||||
Receiving.update(owner) {
|
||||
it.copy(
|
||||
browserRequest =
|
||||
meghdad.pakkit.transfer.BrowserAccess.Request(
|
||||
"test-browser",
|
||||
"Chrome on Android",
|
||||
"10.0.2.17",
|
||||
)
|
||||
)
|
||||
}
|
||||
instrumentation.waitForIdleSync()
|
||||
assertActionsReachable()
|
||||
capture("link")
|
||||
instrumentation.runOnMainSync {
|
||||
screen()
|
||||
.filterIsInstance<Button>()
|
||||
.single { it.text == "Back to code" }
|
||||
.performClick()
|
||||
}
|
||||
capture("browser-approval")
|
||||
Receiving.update(owner) { it.copy(browserRequest = null) }
|
||||
Receiving.update(owner) { it.copy(total = 1000, received = 420) }
|
||||
instrumentation.waitForIdleSync()
|
||||
capture("sending")
|
||||
|
||||
@@ -34,7 +34,7 @@ abstract class WatchTest {
|
||||
val monitor = instrumentation.addMonitor(WatchActivity::class.java.name, null, false)
|
||||
context.startActivity(
|
||||
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))
|
||||
instrumentation.removeMonitor(monitor)
|
||||
@@ -46,7 +46,7 @@ abstract class WatchTest {
|
||||
val file = store.file(id)
|
||||
val digest =
|
||||
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(
|
||||
id,
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE" />
|
||||
|
||||
<application
|
||||
android:name=".PakkitApplication"
|
||||
android:allowBackup="false"
|
||||
android:dataExtractionRules="@xml/pakkit_data_rules"
|
||||
android:icon="@mipmap/pakkit_launcher"
|
||||
|
||||
@@ -1,18 +1,25 @@
|
||||
'use strict';
|
||||
const $ = (id) => document.getElementById(id);
|
||||
let token = location.hash.slice(1),
|
||||
file = null,
|
||||
let file = null,
|
||||
upload = null,
|
||||
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';
|
||||
document.documentElement.dataset.theme = initialTheme;
|
||||
$('theme').onclick = () => {
|
||||
document.documentElement.dataset.theme =
|
||||
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) {
|
||||
if ($(id).textContent !== value) $(id).textContent = value;
|
||||
}
|
||||
@@ -27,25 +34,21 @@ function panel(id) {
|
||||
item.classList.toggle('complete', index < step);
|
||||
});
|
||||
$('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),
|
||||
);
|
||||
}
|
||||
function selected(next) {
|
||||
if (!online || pending || upload) return;
|
||||
message();
|
||||
if (
|
||||
!next ||
|
||||
!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.');
|
||||
if (!next || next.size === 0) {
|
||||
message('This file is empty. Choose an app to send.');
|
||||
return;
|
||||
}
|
||||
file = next;
|
||||
$('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');
|
||||
$('send').focus({ preventScroll: true });
|
||||
}
|
||||
@@ -100,9 +103,9 @@ $('send').onclick = () => {
|
||||
const xhr = new XMLHttpRequest();
|
||||
upload = xhr;
|
||||
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.timeout = 300000;
|
||||
// No total upload timeout. A slow, progressing transfer is allowed to finish.
|
||||
xhr.upload.onprogress = (e) => {
|
||||
if (!e.lengthComputable) return;
|
||||
const percent = Math.floor((e.loaded / e.total) * 100);
|
||||
@@ -133,14 +136,13 @@ $('send').onclick = () => {
|
||||
return;
|
||||
}
|
||||
pending = true;
|
||||
choosingNext = false;
|
||||
file = null;
|
||||
result('Made it to your watch', 'Review ' + data.label + ' on your watch.');
|
||||
poll();
|
||||
};
|
||||
xhr.onerror = () =>
|
||||
failed('Connection lost. Check that both devices are on the same Wi-Fi, then try again.');
|
||||
xhr.ontimeout = () =>
|
||||
failed('That took too long. Open a fresh link from your watch and try again.');
|
||||
failed('Connection lost. Your file is ready to send again when your watch reconnects.');
|
||||
xhr.onabort = () => failed('Transfer cancelled. Your app may have arrived—check your watch.');
|
||||
xhr.send(file);
|
||||
};
|
||||
@@ -148,54 +150,88 @@ $('cancel').onclick = () => upload?.abort();
|
||||
$('again').onclick = () => {
|
||||
if (!pending) {
|
||||
file = null;
|
||||
choosingNext = true;
|
||||
panel('dropzone');
|
||||
message();
|
||||
}
|
||||
};
|
||||
$('access-form').onsubmit = (e) => {
|
||||
e.preventDefault();
|
||||
token = $('access').value.trim().replace(/^.*#/, '');
|
||||
$('access').value = '';
|
||||
poll();
|
||||
function formatSize(bytes) {
|
||||
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
|
||||
const unit = Math.min(Math.floor(Math.log10(Math.max(bytes, 1)) / 3), units.length - 1);
|
||||
return (
|
||||
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;
|
||||
async function poll() {
|
||||
if (polling || !token) return;
|
||||
if (polling) return;
|
||||
polling = true;
|
||||
try {
|
||||
const response = await fetch('/api/status', {
|
||||
headers: { Authorization: 'Bearer ' + token },
|
||||
headers: accessHeaders(),
|
||||
cache: 'no-store',
|
||||
signal: AbortSignal.timeout ? AbortSignal.timeout(5000) : undefined,
|
||||
});
|
||||
if (response.status === 403) {
|
||||
online = false;
|
||||
document.querySelector('.connection').dataset.online = 'false';
|
||||
$('access-form').hidden = false;
|
||||
$('choose').disabled = true;
|
||||
$('connection').textContent = 'Let’s connect';
|
||||
message('Scan the code on your watch to reconnect.');
|
||||
const data = await response.json();
|
||||
if (data.connection === 'unknown') await connect();
|
||||
else pairing(data.connection);
|
||||
return;
|
||||
}
|
||||
if (!response.ok) throw new Error('disconnected');
|
||||
const data = await response.json();
|
||||
if (!online) message();
|
||||
if (!online) {
|
||||
message();
|
||||
if (!pending && !upload) panel(file ? 'selection' : 'dropzone');
|
||||
}
|
||||
online = true;
|
||||
$('send').disabled = false;
|
||||
$('access-form').hidden = true;
|
||||
setText('connection', 'Connected to your watch');
|
||||
document.querySelector('.connection').dataset.online = 'true';
|
||||
$('expiry').textContent =
|
||||
'· ' +
|
||||
Math.floor(data.expiresIn / 60) +
|
||||
':' +
|
||||
String(data.expiresIn % 60).padStart(2, '0') +
|
||||
' remaining';
|
||||
$('choose').disabled = false;
|
||||
if (upload) return;
|
||||
const waiting = data.state === 'waiting';
|
||||
if (!waiting) {
|
||||
pending = true;
|
||||
if (['installed', 'failed'].includes(data.state) && choosingNext) return;
|
||||
pending = !['installed', 'failed'].includes(data.state);
|
||||
const states = {
|
||||
ready: ['Made it to your watch', 'Review ' + data.label + ' 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];
|
||||
result(content[0], content[1], data.state === 'installed');
|
||||
$('result').dataset.state = data.state;
|
||||
if (['installed', 'failed'].includes(data.state)) $('again').hidden = false;
|
||||
if (data.state === 'failed') $('result-icon').textContent = '!';
|
||||
} else if (pending) {
|
||||
pending = false;
|
||||
((pending = false), (choosingNext = false));
|
||||
result('Ready for another?', 'Your watch is ready to receive a new app.', true);
|
||||
$('again').hidden = false;
|
||||
}
|
||||
@@ -220,17 +257,13 @@ async function poll() {
|
||||
$('choose').disabled = true;
|
||||
if (!upload)
|
||||
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 {
|
||||
polling = false;
|
||||
}
|
||||
}
|
||||
if (!token) {
|
||||
$('access-form').hidden = false;
|
||||
$('choose').disabled = true;
|
||||
$('connection').textContent = 'Let’s connect';
|
||||
}
|
||||
panel('pairing');
|
||||
poll();
|
||||
setInterval(() => {
|
||||
if (!document.hidden) poll();
|
||||
|
||||
@@ -145,18 +145,12 @@
|
||||
</div>
|
||||
<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>
|
||||
<form id="access-form" hidden>
|
||||
<label for="access">Connect your watch</label>
|
||||
<p>Scan the code on your watch, or paste its full link here.</p>
|
||||
<input
|
||||
id="access"
|
||||
type="password"
|
||||
aria-label="Watch link"
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
required
|
||||
/><button class="primary" type="submit">Connect to watch</button>
|
||||
</form>
|
||||
<div id="pairing" role="status" aria-live="polite">
|
||||
<div class="pairing-symbol" aria-hidden="true">↗</div>
|
||||
<h3 id="pairing-title">A quick hello</h3>
|
||||
<p id="pairing-detail">Tap Allow browser on your watch.</p>
|
||||
<button id="retry-connection" class="secondary" type="button" hidden>Try again</button>
|
||||
</div>
|
||||
<ol class="steps" aria-label="Transfer steps">
|
||||
<li aria-current="step">Choose</li>
|
||||
<li>Send</li>
|
||||
@@ -173,7 +167,7 @@
|
||||
type="file"
|
||||
accept=".apk,application/vnd.android.package-archive"
|
||||
hidden
|
||||
/><small>APK files · up to 50 MB</small>
|
||||
/><small>APK files · sent directly to your watch</small>
|
||||
</div>
|
||||
<div id="selection" hidden>
|
||||
<div class="file-row">
|
||||
@@ -214,12 +208,11 @@
|
||||
><details class="connection-help">
|
||||
<summary>About this connection</summary>
|
||||
<p>
|
||||
Use Wi-Fi you trust. Files travel across your network without encryption. Keep your
|
||||
watch’s link private.
|
||||
Use Wi-Fi you trust. Files travel across your network without encryption. Approve only
|
||||
browsers you recognize.
|
||||
</p>
|
||||
</details>
|
||||
<span id="expiry"></span
|
||||
></span>
|
||||
</span>
|
||||
</footer>
|
||||
</div>
|
||||
</body>
|
||||
|
||||
@@ -532,20 +532,6 @@ h3 {
|
||||
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']) {
|
||||
width: 100%;
|
||||
background: var(--bg);
|
||||
@@ -667,10 +653,6 @@ input:not([type='file']) {
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
#expiry {
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.dropzone > span,
|
||||
small {
|
||||
font-size: 12px;
|
||||
@@ -886,3 +868,25 @@ small {
|
||||
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
|
||||
|
||||
object ApkRules {
|
||||
const val MAX_BYTES = 50L * 1024 * 1024
|
||||
const val TTL_MS = 24L * 60 * 60 * 1000
|
||||
|
||||
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)
|
||||
|
||||
fun fresh(created: Long, now: Long) = created <= now + 60_000 && now - created < TTL_MS
|
||||
|
||||
fun compatibleAbis(packageAbis: Set<String>, deviceAbis: Set<String>) =
|
||||
packageAbis.isEmpty() || packageAbis.any { it in deviceAbis }
|
||||
|
||||
fun copyBounded(
|
||||
fun copyAndHash(
|
||||
input: InputStream,
|
||||
output: OutputStream? = null,
|
||||
max: Long = MAX_BYTES,
|
||||
): Pair<Long, String> {
|
||||
val hash = MessageDigest.getInstance("SHA-256")
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
@@ -29,7 +23,6 @@ object ApkRules {
|
||||
if (count < 0) break
|
||||
if (count == 0) continue
|
||||
total += count
|
||||
requireUser(total <= max) { "Choose an APK up to 50 MB." }
|
||||
hash.update(buffer, 0, count)
|
||||
output?.write(buffer, 0, count)
|
||||
}
|
||||
|
||||
@@ -9,28 +9,14 @@ import java.util.zip.ZipFile
|
||||
object PackageInspector {
|
||||
@Suppress("DEPRECATION")
|
||||
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>()
|
||||
ZipFile(file).use { zip ->
|
||||
requireUser(zip.getEntry("AndroidManifest.xml") != null) {
|
||||
"This file is not an Android APK."
|
||||
}
|
||||
requireUser(zip.size() < 100_000) {
|
||||
"This file is too complex to open. Try another APK."
|
||||
}
|
||||
var expanded = 0L
|
||||
// Inspect directory metadata only; never inflate the package into memory.
|
||||
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('/')
|
||||
if (parts.size >= 3 && parts[0] == "lib" && entry.name.endsWith(".so"))
|
||||
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) {
|
||||
"This app needs a newer version of Android. Check your watch for updates."
|
||||
}
|
||||
requireUser(ApkRules.compatibleAbis(apk.abis, abis)) {
|
||||
"This version doesn’t work on your watch. Try a version made for it."
|
||||
}
|
||||
requireSpace(apk.bytes, free)
|
||||
}
|
||||
|
||||
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."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,4 +8,11 @@ inline fun requireUser(value: Boolean, message: () -> 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.InstallState
|
||||
import meghdad.pakkit.apk.PendingApk
|
||||
import meghdad.pakkit.apk.UserMessage
|
||||
import org.json.JSONObject
|
||||
|
||||
/** One private package and its review, stored atomically under a stable on-disk schema. */
|
||||
@@ -38,7 +39,7 @@ class PackageStore(context: Context) {
|
||||
state = state,
|
||||
detail = detail,
|
||||
sessionId = sessionId ?: current.sessionId,
|
||||
),
|
||||
)
|
||||
)
|
||||
true
|
||||
}
|
||||
@@ -50,19 +51,27 @@ class PackageStore(context: Context) {
|
||||
check(preferences.edit().remove(PENDING_KEY).commit())
|
||||
}
|
||||
|
||||
/** Expiry prevents installation; disk cleanup is intentionally lazy, on the next app launch. */
|
||||
fun clean(now: Long = System.currentTimeMillis()) =
|
||||
/** Called at process startup, before any transfer can own an uncommitted file. */
|
||||
fun clean() =
|
||||
synchronized(lock) {
|
||||
pending()?.takeUnless { ApkRules.fresh(it.created, now) }?.let { dismiss(it.id) }
|
||||
val keep = pending()?.id
|
||||
directory.listFiles()?.forEach { file ->
|
||||
if (file.name != "$keep.apk" && now - file.lastModified() >= ApkRules.TTL_MS)
|
||||
file.delete()
|
||||
if (file.name != "$keep.apk") file.delete()
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
|
||||
@@ -31,21 +31,19 @@ class ApkInstaller(private val context: Context) {
|
||||
requireUser(context.packageManager.canRequestPackageInstalls()) {
|
||||
"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 digest = file.inputStream().use { ApkRules.copyBounded(it).second }
|
||||
val digest = file.inputStream().use { ApkRules.copyAndHash(it).second }
|
||||
requireUser(digest == apk.apk.sha256) {
|
||||
"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(
|
||||
inspected,
|
||||
Build.VERSION.SDK_INT,
|
||||
Build.SUPPORTED_ABIS.toSet(),
|
||||
PackageInspector.free(context),
|
||||
)
|
||||
PackageInspector.requireSpace(file.length(), PackageInspector.free(context))
|
||||
apk.sessionId?.let { runCatching { installer.abandonSession(it) } }
|
||||
val params =
|
||||
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
|
||||
|
||||
import java.io.InputStream
|
||||
import java.security.MessageDigest
|
||||
import meghdad.pakkit.apk.ApkRules
|
||||
import java.net.InetAddress
|
||||
import java.net.URI
|
||||
import meghdad.pakkit.apk.requireUser
|
||||
|
||||
/** Deliberately small HTTP/1.1 subset: one request per socket, no pipelining or chunked uploads. */
|
||||
object HttpProtocol {
|
||||
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
|
||||
fun line(): String {
|
||||
val out = StringBuilder()
|
||||
while (true) {
|
||||
require(clock() - started <= 5_000_000_000L) { "Request headers stalled" }
|
||||
val b = input.read()
|
||||
require(b >= 0 && ++total <= 8192) { "Invalid request headers" }
|
||||
if (b == 13) {
|
||||
@@ -41,18 +44,47 @@ object HttpProtocol {
|
||||
return Request(first[0], first[1], headers)
|
||||
}
|
||||
|
||||
fun authorized(header: String?, token: String): Boolean =
|
||||
MessageDigest.isEqual(
|
||||
(header ?: "").toByteArray(Charsets.UTF_8),
|
||||
"Bearer $token".toByteArray(Charsets.UTF_8),
|
||||
/** Accept only this listener's literal address/port, including equivalent IPv6 spellings. */
|
||||
fun sameAuthority(authority: String?, address: InetAddress, port: Int): Boolean = runCatching {
|
||||
if (authority == null) return false
|
||||
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 {
|
||||
require(headers["content-type"] == "application/octet-stream") { "Send a complete APK" }
|
||||
val raw = headers["content-length"] ?: error("Content length required")
|
||||
require(raw.matches(Regex("[0-9]+"))) { "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
|
||||
}
|
||||
}
|
||||
@@ -1,19 +1,19 @@
|
||||
package meghdad.pakkit.transfer
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import android.os.SystemClock
|
||||
import android.util.Base64
|
||||
import android.os.PowerManager
|
||||
import java.io.BufferedInputStream
|
||||
import java.io.Closeable
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.io.InputStream
|
||||
import java.net.Inet4Address
|
||||
import java.net.Inet6Address
|
||||
import java.net.InetAddress
|
||||
import java.net.InetSocketAddress
|
||||
import java.net.ServerSocket
|
||||
import java.net.Socket
|
||||
import java.security.SecureRandom
|
||||
import java.util.UUID
|
||||
import java.util.concurrent.ArrayBlockingQueue
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
@@ -22,8 +22,10 @@ import java.util.concurrent.ThreadPoolExecutor
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import meghdad.pakkit.apk.ApkRules
|
||||
import meghdad.pakkit.apk.InstallState
|
||||
import meghdad.pakkit.apk.PackageInspector
|
||||
import meghdad.pakkit.apk.PendingApk
|
||||
import meghdad.pakkit.apk.requireUser
|
||||
import meghdad.pakkit.apk.userMessage
|
||||
import meghdad.pakkit.data.PackageStore
|
||||
import org.json.JSONObject
|
||||
@@ -31,27 +33,32 @@ import org.json.JSONObject
|
||||
/** Bounded HTTP endpoint. Wi-Fi acquisition, notifications and power belong to ReceiveService. */
|
||||
class LocalHttpServer(
|
||||
private val context: Context,
|
||||
address: Inet4Address,
|
||||
private val deadline: Long,
|
||||
private val address: InetAddress,
|
||||
private val owner: Any,
|
||||
private val access: BrowserAccess = BrowserAccess(),
|
||||
) : Closeable {
|
||||
private val store = PackageStore(context)
|
||||
private val listener =
|
||||
ServerSocket().apply {
|
||||
reuseAddress = true
|
||||
bind(InetSocketAddress(address, 0), 4)
|
||||
ServerSocket().also { socket ->
|
||||
try {
|
||||
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 sockets = ConcurrentHashMap.newKeySet<Socket>()
|
||||
private val uploading = AtomicBoolean(false)
|
||||
private val closed = AtomicBoolean(false)
|
||||
private val token =
|
||||
Base64.encodeToString(
|
||||
ByteArray(24).also { SecureRandom().nextBytes(it) },
|
||||
Base64.URL_SAFE or Base64.NO_WRAP or Base64.NO_PADDING,
|
||||
)
|
||||
private val authority = "${address.hostAddress}:${listener.localPort}"
|
||||
val url = "http://$authority/#$token"
|
||||
private val commitLock = Any()
|
||||
private val host =
|
||||
address.hostAddress.orEmpty().substringBefore('%').let {
|
||||
if (address is Inet6Address) "[$it]" else it
|
||||
}
|
||||
private val authority = "$host:${listener.localPort}"
|
||||
val url = "http://$authority/"
|
||||
|
||||
fun start() {
|
||||
Thread(
|
||||
@@ -93,11 +100,11 @@ class LocalHttpServer(
|
||||
val response = Response(socket)
|
||||
try {
|
||||
val input = BufferedInputStream(socket.getInputStream(), 8192)
|
||||
socket.soTimeout = 5_000
|
||||
val request = HttpProtocol.read(input)
|
||||
check(!closed.get() && SystemClock.elapsedRealtime() < deadline) {
|
||||
"Receiving has ended. Open a fresh link from your watch."
|
||||
}
|
||||
if (request.headers["host"] != authority) {
|
||||
socket.soTimeout = 15_000
|
||||
requireUser(!closed.get()) { "Receiving has stopped. Open Pakkit to start again." }
|
||||
if (!HttpProtocol.sameAuthority(request.headers["host"], address, PORT)) {
|
||||
response.error(403, "Open the address shown on your watch.")
|
||||
return
|
||||
}
|
||||
@@ -110,18 +117,37 @@ class LocalHttpServer(
|
||||
)
|
||||
return
|
||||
}
|
||||
if (!HttpProtocol.authorized(request.headers["authorization"], token)) {
|
||||
response.error(403, "Open the private link or scan the QR code on your watch.")
|
||||
if (request.method == "POST" && !validOrigin(request.headers["origin"])) {
|
||||
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
|
||||
}
|
||||
when {
|
||||
request.method == "GET" && request.path == "/api/status" ->
|
||||
response.json(200, status())
|
||||
request.method == "POST" && request.path == "/api/upload" -> {
|
||||
if (request.headers["origin"] != "http://$authority")
|
||||
response.error(403, "Open the link shown on your watch to send an app.")
|
||||
else upload(request, input, response)
|
||||
}
|
||||
request.method == "POST" && request.path == "/api/upload" ->
|
||||
upload(request, input, response)
|
||||
else -> response.error(404, "Not found")
|
||||
}
|
||||
} 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 {
|
||||
val pending = store.pending()
|
||||
val live = Receiving.state
|
||||
@@ -144,9 +174,12 @@ class LocalHttpServer(
|
||||
.put("label", pending?.apk?.label.orEmpty())
|
||||
.put("received", live.received)
|
||||
.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) {
|
||||
val length = HttpProtocol.uploadLength(request.headers)
|
||||
if (!uploading.compareAndSet(false, true)) {
|
||||
@@ -154,16 +187,26 @@ class LocalHttpServer(
|
||||
return
|
||||
}
|
||||
var partial: File? = null
|
||||
val wake =
|
||||
context
|
||||
.getSystemService(PowerManager::class.java)
|
||||
.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "pakkit:upload")
|
||||
try {
|
||||
store
|
||||
.pending()
|
||||
?.takeIf { it.state in setOf(InstallState.INSTALLED, InstallState.FAILED) }
|
||||
?.let { store.dismiss(it.id) }
|
||||
if (store.pending() != null) {
|
||||
response.error(409, "Finish with the app on your watch before sending another.")
|
||||
return
|
||||
}
|
||||
PackageInspector.requireSpace(length, PackageInspector.free(context))
|
||||
wake.acquire()
|
||||
try {
|
||||
val id = UUID.randomUUID().toString()
|
||||
val file = store.file(id)
|
||||
partial = file
|
||||
Receiving.update(owner) {
|
||||
updateLive {
|
||||
it.copy(detail = "Your app is on its way…", total = length, received = 0)
|
||||
}
|
||||
val body =
|
||||
@@ -171,29 +214,33 @@ class LocalHttpServer(
|
||||
input,
|
||||
length,
|
||||
progress = { received ->
|
||||
Receiving.update(owner) { it.copy(received = received) }
|
||||
updateLive { it.copy(received = received) }
|
||||
},
|
||||
)
|
||||
val digest = file.outputStream().use { ApkRules.copyBounded(body, it).second }
|
||||
Receiving.update(owner) { it.copy(detail = "Getting your app ready…") }
|
||||
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(),
|
||||
PackageInspector.free(context),
|
||||
)
|
||||
check(!closed.get() && SystemClock.elapsedRealtime() < deadline) {
|
||||
"Receiving has ended. Open a fresh link from your watch."
|
||||
synchronized(commitLock) {
|
||||
requireUser(!closed.get()) {
|
||||
"Receiving has stopped. Start again to send this app."
|
||||
}
|
||||
store.stage(PendingApk(id, System.currentTimeMillis(), apk))
|
||||
}
|
||||
partial = null
|
||||
Receiving.update(owner) { it.copy(detail = "Ready to install") }
|
||||
updateLive { it.copy(detail = "Ready to install") }
|
||||
response.json(200, JSONObject().put("label", apk.label).put("state", "ready"))
|
||||
} finally {
|
||||
wake.release()
|
||||
}
|
||||
} finally {
|
||||
partial?.delete()
|
||||
uploading.set(false)
|
||||
Receiving.update(owner) {
|
||||
updateLive {
|
||||
it.copy(
|
||||
received = 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() {
|
||||
synchronized(commitLock) {
|
||||
if (!closed.compareAndSet(false, true)) return
|
||||
}
|
||||
try {
|
||||
listener.close()
|
||||
} finally {
|
||||
@@ -252,6 +307,7 @@ class LocalHttpServer(
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val PORT = 8787
|
||||
private val ASSETS =
|
||||
mapOf(
|
||||
"/" to ("index.html" to "text/html; charset=utf-8"),
|
||||
|
||||
@@ -14,48 +14,58 @@ import android.net.NetworkCapabilities
|
||||
import android.net.NetworkRequest
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.PowerManager
|
||||
import android.os.SystemClock
|
||||
import java.net.BindException
|
||||
import java.net.Inet4Address
|
||||
import java.net.InetAddress
|
||||
import meghdad.pakkit.R
|
||||
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() {
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
private val connectivity by lazy { getSystemService(ConnectivityManager::class.java) }
|
||||
private var server: LocalHttpServer? = null
|
||||
private var network: Network? = null
|
||||
private var address: Inet4Address? = null
|
||||
private var address: InetAddress? = null
|
||||
private var registered = false
|
||||
private var ended = false
|
||||
private var deadline = 0L
|
||||
private var wake: PowerManager.WakeLock? = null
|
||||
private val access = BrowserAccess { request ->
|
||||
Receiving.update(this) { it.copy(browserRequest = request) }
|
||||
}
|
||||
private val callback =
|
||||
object : ConnectivityManager.NetworkCallback() {
|
||||
override fun onLinkPropertiesChanged(network: Network, properties: LinkProperties) {
|
||||
main.post {
|
||||
if (ended) return@post
|
||||
if (this@ReceiveService.network == null) {
|
||||
if (properties.linkAddresses.isNotEmpty()) open(network, properties)
|
||||
} else if (
|
||||
this@ReceiveService.network == network &&
|
||||
properties.linkAddresses.none { it.address == address }
|
||||
) {
|
||||
finish("Wi-Fi changed. Ready to reconnect?")
|
||||
val candidates =
|
||||
properties.linkAddresses
|
||||
.map { it.address }
|
||||
.filter {
|
||||
!it.isLoopbackAddress &&
|
||||
!it.isAnyLocalAddress &&
|
||||
!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) {
|
||||
main.post {
|
||||
if (network == this@ReceiveService.network)
|
||||
finish("Wi-Fi disconnected. Ready to reconnect?")
|
||||
if (!ended && network == this@ReceiveService.network) suspendListener()
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
if (intent?.action == STOP) {
|
||||
finish("Session ended")
|
||||
finish("Receiving stopped")
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
if (registered || ended) return START_NOT_STICKY
|
||||
val manager = getSystemService(NotificationManager::class.java)
|
||||
manager.createNotificationChannel(
|
||||
NotificationChannel(
|
||||
"receive",
|
||||
"App transfers",
|
||||
NotificationManager.IMPORTANCE_LOW,
|
||||
),
|
||||
NotificationChannel("receive", "App transfers", NotificationManager.IMPORTANCE_LOW)
|
||||
)
|
||||
val open =
|
||||
PendingIntent.getActivity(
|
||||
@@ -92,20 +98,18 @@ class ReceiveService : Service() {
|
||||
val notification =
|
||||
Notification.Builder(this, "receive")
|
||||
.setSmallIcon(R.drawable.pakkit_mark)
|
||||
.setContentTitle("Ready for your next app")
|
||||
.setContentTitle("Receiving is on")
|
||||
.setContentText("Open Pakkit to connect your browser.")
|
||||
.setContentIntent(open)
|
||||
.setOngoing(true)
|
||||
.addAction(Notification.Action.Builder(null, "End session", stop).build())
|
||||
.addAction(Notification.Action.Builder(null, "Stop receiving", stop).build())
|
||||
.build()
|
||||
startForeground(
|
||||
NOTIFICATION,
|
||||
notification,
|
||||
ServiceInfo.FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE,
|
||||
)
|
||||
Receiving.begin(this)
|
||||
deadline = SystemClock.elapsedRealtime() + DURATION_MS
|
||||
main.postDelayed({ finish("Time’s up. Ready for another app?") }, DURATION_MS)
|
||||
Receiving.begin(this, access)
|
||||
try {
|
||||
registered = true
|
||||
connectivity.requestNetwork(
|
||||
@@ -114,35 +118,41 @@ class ReceiveService : Service() {
|
||||
.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
|
||||
.build(),
|
||||
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.")
|
||||
}
|
||||
// A killed process does not silently reopen network access. The user starts it again.
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
|
||||
private fun open(network: Network, properties: LinkProperties) {
|
||||
try {
|
||||
val address =
|
||||
properties.linkAddresses
|
||||
.map { it.address }
|
||||
.filterIsInstance<Inet4Address>()
|
||||
.firstOrNull { it.isSiteLocalAddress }
|
||||
?: error("A private IPv4 Wi-Fi address is required")
|
||||
private fun open(network: Network, address: InetAddress) {
|
||||
suspendListener()
|
||||
this.network = network
|
||||
this.address = address
|
||||
val listener = LocalHttpServer(applicationContext, address, deadline, this)
|
||||
try {
|
||||
val listener = LocalHttpServer(applicationContext, address, this, access)
|
||||
server = listener
|
||||
wake =
|
||||
getSystemService(PowerManager::class.java)
|
||||
.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "pakkit:receive")
|
||||
.apply { acquire((deadline - SystemClock.elapsedRealtime()).coerceAtLeast(1)) }
|
||||
listener.start()
|
||||
Receiving.update(this) { it.copy(url = listener.url, detail = "Ready to receive") }
|
||||
} catch (error: Exception) {
|
||||
android.util.Log.w("PakkitReceive", "Cannot open receiving session", error)
|
||||
finish("Couldn’t connect. Check Wi-Fi and try again.")
|
||||
android.util.Log.w("PakkitReceive", "Cannot open receiver", error)
|
||||
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
|
||||
if (registered) runCatching { connectivity.unregisterNetworkCallback(callback) }
|
||||
registered = false
|
||||
wake?.let { if (it.isHeld) it.release() }
|
||||
wake = null
|
||||
access.close()
|
||||
Receiving.end(this, message)
|
||||
}
|
||||
|
||||
override fun onTimeout(startId: Int, fgsType: Int) {
|
||||
finish("Your watch paused receiving. Open Pakkit to start again.")
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
ended = true
|
||||
release("Session ended")
|
||||
release("Receiving stopped")
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val DURATION_MS = 10 * 60 * 1000L
|
||||
const val STOP = "stop"
|
||||
private const val NOTIFICATION = 81
|
||||
}
|
||||
|
||||
@@ -4,14 +4,13 @@ import android.os.Handler
|
||||
import android.os.Looper
|
||||
import java.util.concurrent.CopyOnWriteArraySet
|
||||
|
||||
/**
|
||||
* Live session state is never persisted: process death immediately invalidates its private link.
|
||||
*/
|
||||
/** Live session state is never persisted: process death revokes browser approvals. */
|
||||
object Receiving {
|
||||
data class State(
|
||||
val active: Boolean = false,
|
||||
val url: String? = null,
|
||||
val detail: String = "Connect your watch and browser to the same Wi-Fi.",
|
||||
val browserRequest: BrowserAccess.Request? = null,
|
||||
val received: Long = 0,
|
||||
val total: Long = 0,
|
||||
)
|
||||
@@ -21,6 +20,7 @@ object Receiving {
|
||||
private set
|
||||
|
||||
private var owner: Any? = null
|
||||
private var access: BrowserAccess? = null
|
||||
private val listeners = CopyOnWriteArraySet<() -> Unit>()
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
private val notify = Runnable { listeners.forEach { it() } }
|
||||
@@ -34,7 +34,8 @@ object Receiving {
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun begin(owner: Any) {
|
||||
fun begin(owner: Any, access: BrowserAccess? = null) {
|
||||
this.access = access
|
||||
this.owner = owner
|
||||
publish(State(active = true, detail = "Connecting to Wi-Fi…"))
|
||||
}
|
||||
@@ -48,9 +49,15 @@ object Receiving {
|
||||
fun end(owner: Any, detail: String) {
|
||||
if (this.owner !== owner) return
|
||||
this.owner = null
|
||||
this.access = null
|
||||
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) {
|
||||
this.state = state
|
||||
main.removeCallbacks(notify)
|
||||
|
||||
@@ -19,12 +19,13 @@ import android.widget.TextClock
|
||||
import java.util.concurrent.Executors
|
||||
import kotlin.math.roundToInt
|
||||
import meghdad.pakkit.R
|
||||
import meghdad.pakkit.apk.ApkRules
|
||||
import meghdad.pakkit.apk.InstallState
|
||||
import meghdad.pakkit.apk.PendingApk
|
||||
import meghdad.pakkit.apk.userMessage
|
||||
import meghdad.pakkit.data.PackageStore
|
||||
import meghdad.pakkit.install.ApkInstaller
|
||||
import meghdad.pakkit.install.PendingApproval
|
||||
import meghdad.pakkit.transfer.BrowserAccess
|
||||
import meghdad.pakkit.transfer.ReceiveService
|
||||
import meghdad.pakkit.transfer.Receiving
|
||||
|
||||
@@ -38,31 +39,26 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
|
||||
private var busy = false
|
||||
private var error: String? = null
|
||||
private var renderedState = ""
|
||||
private var showingLink = false
|
||||
private var backRegistered = false
|
||||
private val linkBack =
|
||||
if (Build.VERSION.SDK_INT >= 33)
|
||||
android.window.OnBackInvokedCallback {
|
||||
showingLink = false
|
||||
refresh()
|
||||
}
|
||||
else null
|
||||
private var resumed = false
|
||||
private var approvalLaunched: Int? = null
|
||||
private var requestedInstallId: String? = null
|
||||
private var qrUrl = ""
|
||||
private var qrBitmap: android.graphics.Bitmap? = null
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
store = PackageStore(this)
|
||||
store.clean()
|
||||
acceptIntent(intent)
|
||||
showingLink = savedInstanceState?.getBoolean("showingLink") ?: false
|
||||
requestedInstallId = savedInstanceState?.getString("requestedInstallId")
|
||||
approvalLaunched = savedInstanceState?.getInt("approvalLaunched", -1)?.takeIf { it >= 0 }
|
||||
refresh()
|
||||
savedInstanceState?.getInt("scroll")?.let { y -> scroll.post { scroll.scrollTo(0, y) } }
|
||||
}
|
||||
|
||||
override fun onSaveInstanceState(outState: Bundle) {
|
||||
outState.putInt("scroll", scroll.scrollY)
|
||||
outState.putBoolean("showingLink", showingLink)
|
||||
outState.putString("requestedInstallId", requestedInstallId)
|
||||
approvalLaunched?.let { outState.putInt("approvalLaunched", it) }
|
||||
super.onSaveInstanceState(outState)
|
||||
}
|
||||
|
||||
@@ -89,21 +85,25 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
resumed = true
|
||||
store.preferences.registerOnSharedPreferenceChangeListener(this)
|
||||
Receiving.observe(sessionObserver)
|
||||
refresh()
|
||||
val requested = requestedInstallId
|
||||
requestedInstallId = null
|
||||
if (requested != null && packageManager.canRequestPackageInstalls()) {
|
||||
store.pending()?.takeIf { it.id == requested }?.let { install(it) }
|
||||
}
|
||||
}
|
||||
|
||||
override fun onPause() {
|
||||
resumed = false
|
||||
Receiving.removeObserver(sessionObserver)
|
||||
store.preferences.unregisterOnSharedPreferenceChangeListener(this)
|
||||
super.onPause()
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
if (Build.VERSION.SDK_INT >= 33 && backRegistered) {
|
||||
onBackInvokedDispatcher.unregisterOnBackInvokedCallback(requireNotNull(linkBack))
|
||||
}
|
||||
io.shutdown()
|
||||
super.onDestroy()
|
||||
}
|
||||
@@ -198,29 +198,17 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
|
||||
if (isDestroyed || isFinishing) return
|
||||
val job = store.pending()
|
||||
val live = Receiving.state
|
||||
if (live.url == null || job != null || live.total > 0) showingLink = false
|
||||
val stateKey =
|
||||
job?.let { "${it.id}:${it.state}" }
|
||||
live.browserRequest?.let { "browser:${it.id}" }
|
||||
?: job?.let { "${it.id}:${it.state}" }
|
||||
?: when {
|
||||
showingLink && live.url != null -> "link"
|
||||
live.total > 0 -> "uploading"
|
||||
live.url != null -> "receiving"
|
||||
live.active -> "connecting"
|
||||
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
|
||||
if (stateKey != previousState) error = null
|
||||
val y = if (::scroll.isInitialized && stateKey == renderedState) scroll.scrollY else 0
|
||||
renderedState = stateKey
|
||||
scroll = RoundScrollView(this).apply { setBackgroundColor(colors.canvas) }
|
||||
@@ -247,16 +235,20 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
|
||||
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 {
|
||||
incoming(job)
|
||||
if (Receiving.state.url != null)
|
||||
if (live.active) {
|
||||
button(getString(R.string.watch_end_session), false) {
|
||||
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.isFocusableInTouchMode = true
|
||||
setContentView(scroll)
|
||||
@@ -269,17 +261,31 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
|
||||
column.alpha = 0f
|
||||
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() {
|
||||
val live = Receiving.state
|
||||
val url = live.url
|
||||
if (url != null) {
|
||||
if (showingLink && live.total == 0L) {
|
||||
showLink(url)
|
||||
return
|
||||
}
|
||||
if (live.total > 0) {
|
||||
parcel(48)
|
||||
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_description), 13f, colors.secondary), 8)
|
||||
add(line(getString(R.string.watch_ready_for_10_minutes), 12f, colors.mint), 10)
|
||||
button(getString(R.string.watch_view_link), false) {
|
||||
showingLink = true
|
||||
refresh()
|
||||
}
|
||||
add(
|
||||
line(url, 12f, colors.mint).apply {
|
||||
textDirection = View.TEXT_DIRECTION_LTR
|
||||
setTextIsSelectable(true)
|
||||
},
|
||||
10,
|
||||
)
|
||||
}
|
||||
button(getString(R.string.watch_end_session), false) {
|
||||
stopService(Intent(this, ReceiveService::class.java))
|
||||
@@ -387,22 +395,16 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
|
||||
)
|
||||
if (live.active) {
|
||||
badge(getString(R.string.watch_finding_wi_fi))
|
||||
add(line(getString(R.string.watch_connecting_description), 13f, colors.secondary), 12)
|
||||
button(getString(R.string.watch_cancel), false) {
|
||||
add(line(live.detail, 13f, colors.secondary), 12)
|
||||
button(getString(R.string.watch_end_session), false) {
|
||||
stopService(Intent(this, ReceiveService::class.java))
|
||||
}
|
||||
} else {
|
||||
button(getString(R.string.watch_start_receiving)) {
|
||||
error = null
|
||||
runCatching { startForegroundService(Intent(this, ReceiveService::class.java)) }
|
||||
.onFailure {
|
||||
error = getString(R.string.watch_connection_error)
|
||||
refresh()
|
||||
}
|
||||
}
|
||||
button(getString(R.string.watch_start_receiving)) { startReceiving() }
|
||||
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)
|
||||
}
|
||||
button(getString(R.string.watch_wi_fi), false) {
|
||||
runCatching {
|
||||
startActivity(Intent(android.provider.Settings.ACTION_WIFI_SETTINGS))
|
||||
@@ -413,34 +415,29 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun showLink(url: String) {
|
||||
add(line(getString(R.string.watch_your_watch_link), 20f, bold = true), 14)
|
||||
add(line(getString(R.string.watch_link_description), 13f, colors.secondary), 12)
|
||||
add(
|
||||
line(url, 12f, colors.mint).apply {
|
||||
textDirection = View.TEXT_DIRECTION_LTR
|
||||
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
|
||||
private fun startReceiving() {
|
||||
error = null
|
||||
runCatching { startForegroundService(Intent(this, ReceiveService::class.java)) }
|
||||
.onFailure {
|
||||
error = getString(R.string.watch_connection_error)
|
||||
refresh()
|
||||
}
|
||||
}
|
||||
|
||||
// Android 12 uses this callback; Android 13+ registers the platform callback above.
|
||||
@Suppress("DEPRECATION")
|
||||
@android.annotation.SuppressLint("GestureBackNavigation")
|
||||
@Deprecated("Legacy callback for Android 12")
|
||||
override fun onBackPressed() {
|
||||
if (showingLink) {
|
||||
showingLink = false
|
||||
refresh()
|
||||
} else super.onBackPressed()
|
||||
private fun browserRequest(request: BrowserAccess.Request) {
|
||||
add(line(getString(R.string.watch_connect_browser), 21f, bold = true), 8)
|
||||
add(line(request.label, 15f, colors.secondary), 10)
|
||||
add(line(request.address, 12f, colors.secondary), 5)
|
||||
button(getString(R.string.watch_allow_browser)) {
|
||||
Receiving.answerBrowser(request.id, true)
|
||||
}
|
||||
button(getString(R.string.watch_not_now), false) {
|
||||
Receiving.answerBrowser(request.id, false)
|
||||
}
|
||||
button(getString(R.string.watch_end_session), false) {
|
||||
stopService(Intent(this, ReceiveService::class.java))
|
||||
}
|
||||
}
|
||||
|
||||
private fun incoming(job: PendingApk) {
|
||||
@@ -481,25 +478,7 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
|
||||
when (state) {
|
||||
InstallState.READY,
|
||||
InstallState.FAILED -> {
|
||||
if (!ApkRules.fresh(job.created, System.currentTimeMillis())) {
|
||||
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 (store.file(job.id).exists()) {
|
||||
if (packageManager.canRequestPackageInstalls())
|
||||
button(
|
||||
if (state == InstallState.FAILED) getString(R.string.watch_try_again)
|
||||
@@ -516,11 +495,13 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
|
||||
),
|
||||
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() }
|
||||
}
|
||||
}
|
||||
add(line(getString(R.string.watch_trust_notice), 12f, colors.secondary), 10)
|
||||
button(getString(R.string.watch_remove_file), false) { dismiss(job) }
|
||||
}
|
||||
InstallState.CONFIRM -> {
|
||||
@@ -589,6 +570,7 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
|
||||
private fun settings() {
|
||||
runCatching { startActivity(ApkInstaller.settings(this)) }
|
||||
.onFailure {
|
||||
requestedInstallId = null
|
||||
error = getString(R.string.watch_permission_unavailable)
|
||||
refresh()
|
||||
}
|
||||
@@ -604,8 +586,11 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
|
||||
error = null
|
||||
refresh()
|
||||
io.execute {
|
||||
ApkInstaller(applicationContext).install(job)
|
||||
val result = runCatching { ApkInstaller(applicationContext).install(job) }
|
||||
runOnUiThread {
|
||||
result.exceptionOrNull()?.let {
|
||||
error = it.userMessage(getString(R.string.watch_save_error))
|
||||
}
|
||||
busy = false
|
||||
refresh()
|
||||
}
|
||||
|
||||
@@ -1,32 +1,21 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<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_on_its_way">On its way</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_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_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_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_connection_error">Couldn’t connect. Check Wi-Fi and try again.</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_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_couldn_t_install">Couldn’t install</string>
|
||||
<string name="watch_getting_ready">Getting ready…</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_install">Install</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_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="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_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>
|
||||
@@ -9,7 +9,7 @@ class ApkRulesTest {
|
||||
@Test
|
||||
fun copyComputesKnownDigest() {
|
||||
val output = ByteArrayOutputStream()
|
||||
val result = ApkRules.copyBounded(ByteArrayInputStream("abc".toByteArray()), output)
|
||||
val result = ApkRules.copyAndHash(ByteArrayInputStream("abc".toByteArray()), output)
|
||||
assertEquals(3L, result.first)
|
||||
assertEquals(
|
||||
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
|
||||
@@ -18,14 +18,29 @@ class ApkRulesTest {
|
||||
assertEquals("abc", output.toString("UTF-8"))
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException::class)
|
||||
fun stopsBeforeWritingOverLimit() {
|
||||
ApkRules.copyBounded(ByteArrayInputStream(ByteArray(1025)), ByteArrayOutputStream(), 1024)
|
||||
@Test
|
||||
fun streamsBeyondThePreviousFileLimitWithABoundedBuffer() {
|
||||
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)
|
||||
fun refusesEmptyFiles() {
|
||||
ApkRules.copyBounded(ByteArrayInputStream(byteArrayOf()), ByteArrayOutputStream())
|
||||
ApkRules.copyAndHash(ByteArrayInputStream(byteArrayOf()), ByteArrayOutputStream())
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -35,14 +50,6 @@ class ApkRulesTest {
|
||||
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
|
||||
fun nativeLibrariesNeedMatchingProcessor() {
|
||||
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)
|
||||
|
||||
@Test
|
||||
fun acceptsCompatibleSdkAbiAndStorage() {
|
||||
PackageInspector.checkForWatch(apk, 36, setOf("arm64-v8a"), 100L * 1024 * 1024)
|
||||
fun acceptsCompatibleSdkAndProcessor() {
|
||||
PackageInspector.checkForWatch(apk, 36, setOf("arm64-v8a"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun rejectsIncompatibleSdkProcessorAndInsufficientStorage() {
|
||||
fun rejectsActualPlatformIncompatibility() {
|
||||
assertTrue(
|
||||
runCatching {
|
||||
PackageInspector.checkForWatch(apk, 30, setOf("arm64-v8a"), Long.MAX_VALUE)
|
||||
}
|
||||
.isFailure,
|
||||
runCatching { PackageInspector.checkForWatch(apk, 30, setOf("arm64-v8a")) }.isFailure
|
||||
)
|
||||
assertTrue(
|
||||
runCatching { PackageInspector.checkForWatch(apk, 36, setOf("x86_64"), Long.MAX_VALUE) }
|
||||
.isFailure,
|
||||
)
|
||||
assertTrue(
|
||||
runCatching { PackageInspector.checkForWatch(apk, 36, setOf("arm64-v8a"), 1024) }
|
||||
.isFailure,
|
||||
runCatching { PackageInspector.checkForWatch(apk, 36, setOf("x86_64")) }.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 {
|
||||
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
|
||||
fun acceptsBoundedRawUpload() {
|
||||
val r =
|
||||
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("/api/upload", r.path)
|
||||
@@ -27,41 +46,57 @@ class HttpProtocolTest {
|
||||
"Long: " + "a".repeat(9000),
|
||||
)) {
|
||||
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
|
||||
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(
|
||||
runCatching {
|
||||
HttpProtocol.uploadLength(
|
||||
mapOf(
|
||||
"content-type" to "application/octet-stream",
|
||||
"content-length" to length,
|
||||
),
|
||||
)
|
||||
)
|
||||
}
|
||||
.isFailure,
|
||||
.isFailure
|
||||
)
|
||||
}
|
||||
assertTrue(
|
||||
runCatching {
|
||||
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
|
||||
fun requiresExactBearerToken() {
|
||||
assertTrue(HttpProtocol.authorized("Bearer secret", "secret"))
|
||||
assertFalse(HttpProtocol.authorized(null, "secret"))
|
||||
assertFalse(HttpProtocol.authorized("Bearer secretX", "secret"))
|
||||
assertFalse(HttpProtocol.authorized("bearer secret", "secret"))
|
||||
fun slowHeadersCannotHoldAWorkerIndefinitely() {
|
||||
var time = 0L
|
||||
val result = runCatching {
|
||||
HttpProtocol.read("GET / HTTP/1.1\r\n\r\n".byteInputStream()) {
|
||||
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")
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
+23
-23
@@ -1,45 +1,45 @@
|
||||
# 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.
|
||||
|
||||
## Ownership
|
||||
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.
|
||||
|
||||
| Package | Responsibility |
|
||||
| ---------- | -------------------------------------------------------------------------------------------- |
|
||||
| `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 |
|
||||
| --- | --- |
|
||||
| `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 |
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
## 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
|
||||
|
||||
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
@@ -13,9 +13,9 @@
|
||||
|
||||
## 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
|
||||
|
||||
@@ -32,7 +32,7 @@ Write for the person wearing the watch: short, warm, specific and calm. Let the
|
||||
| Moment | Watch | Browser |
|
||||
| --- | --- | --- |
|
||||
| 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 |
|
||||
| Check | Just checking… | Just checking… |
|
||||
| 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. |
|
||||
| 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.
|
||||
+14
-3
@@ -33,7 +33,7 @@ npm test --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.
|
||||
|
||||
@@ -45,9 +45,20 @@ Complete Chrome’s first-run setup in the Android Emulator, leave Chrome open,
|
||||
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
|
||||
|
||||
|
||||
+3
-3
@@ -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.
|
||||
|
||||
[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.
|
||||
|
||||
@@ -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.
|
||||
|
||||
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
|
||||
|
||||
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.
|
||||
|
||||
|
||||
+5
-3
@@ -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.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
@@ -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
@@ -8,10 +8,10 @@ See DEVELOPMENT.md for the commands and environment setup. Results are generated
|
||||
|
||||
| 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 |
|
||||
| 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 |
|
||||
| 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 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 |
|
||||
| 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 |
|
||||
| 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
|
||||
|
||||
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.
|
||||
- **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.
|
||||
- **27 JVM tests passed**, with zero failures/errors.
|
||||
- **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.
|
||||
- **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.
|
||||
- **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.
|
||||
- **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 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.
|
||||
- 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.
|
||||
|
||||
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
|
||||
|
||||
- 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.
|
||||
- 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.
|
||||
|
||||
@@ -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)
|
||||
@@ -61,15 +61,13 @@ def tap_text(serial, label, attempts=6):
|
||||
|
||||
|
||||
def session_url(serial):
|
||||
tap_text(serial, "View link")
|
||||
for _ in range(6):
|
||||
tree = ui(serial)
|
||||
for node in tree.iter("node"):
|
||||
value = node.get("text", "")
|
||||
if value.startswith("http://") and "#" in value:
|
||||
tap_text(serial, "Back to code")
|
||||
if value.startswith("http://") and ":8787" in value:
|
||||
return value
|
||||
bounds = next(tree.iter("node")).get("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")
|
||||
raise RuntimeError("No private session link found. Check source approval and emulator Wi-Fi.")
|
||||
raise RuntimeError("No receiving address found. Check emulator Wi-Fi.")
|
||||
@@ -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("--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("--large", action="store_true", help="Use app/build/qa/large-fixture.apk for the real browser upload")
|
||||
args = parser.parse_args()
|
||||
if args.browser == args.watch:
|
||||
parser.error("Use distinct Wear OS and Android browser emulator serials.")
|
||||
@@ -51,7 +52,7 @@ try:
|
||||
print(output, flush=True)
|
||||
screenshots = report_dir / ("watch-product-small" if args.small else "watch-product")
|
||||
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")
|
||||
(screenshots / f"{name}.png").write_bytes(image)
|
||||
|
||||
@@ -78,10 +79,28 @@ if args.browser:
|
||||
tap_text(args.watch, "Start receiving")
|
||||
url = session_url(args.watch)
|
||||
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")
|
||||
tap_text(args.watch, "Remove file")
|
||||
tap_text(args.watch, "End session")
|
||||
tap_text(args.watch, "Stop receiving")
|
||||
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.watch, "shell", "am", "force-stop", "meghdad.pakkit")
|
||||
+84
-17
@@ -11,7 +11,9 @@ let state = 'waiting',
|
||||
failure = false,
|
||||
hold = false,
|
||||
bytesReceived = 0,
|
||||
disconnected = false;
|
||||
disconnected = false,
|
||||
approved = true,
|
||||
denied = false;
|
||||
const server = http.createServer(async (request, response) => {
|
||||
response.setHeader('Cache-Control', 'no-store');
|
||||
const routes = {
|
||||
@@ -26,8 +28,18 @@ const server = http.createServer(async (request, response) => {
|
||||
return;
|
||||
}
|
||||
response.setHeader('Content-Type', 'application/json');
|
||||
if (request.headers.authorization !== 'Bearer test-key') {
|
||||
response.writeHead(403).end('{}');
|
||||
if (request.url === '/api/connect' || request.url === '/api/retry') {
|
||||
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') {
|
||||
if (disconnected) {
|
||||
response.writeHead(503).end('{}');
|
||||
@@ -38,11 +50,11 @@ const server = http.createServer(async (request, response) => {
|
||||
state,
|
||||
label: 'Test app',
|
||||
detail: 'Please review your watch.',
|
||||
expiresIn: 500,
|
||||
connection: 'approved',
|
||||
}),
|
||||
);
|
||||
} else if (request.url === '/api/upload') {
|
||||
((bytesReceived = 0), (disconnected = false));
|
||||
bytesReceived = 0;
|
||||
for await (const chunk of request) bytesReceived += chunk.length;
|
||||
if (hold) return; // Cancellation while awaiting a response.
|
||||
if (failure)
|
||||
@@ -76,7 +88,7 @@ const server = http.createServer(async (request, response) => {
|
||||
colorScheme: theme,
|
||||
reducedMotion: 'reduce',
|
||||
});
|
||||
await page.goto(`${origin}/#test-key`);
|
||||
await page.goto(origin);
|
||||
await page.getByText('Connected to your watch', { exact: true }).waitFor();
|
||||
assert.equal(
|
||||
await page.evaluate(() => document.documentElement.scrollWidth > innerWidth),
|
||||
@@ -84,7 +96,7 @@ const server = http.createServer(async (request, response) => {
|
||||
`${width}px/${theme} overflow`,
|
||||
);
|
||||
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)
|
||||
await page.screenshot({
|
||||
path: path.join(reports, `web-${width}-${theme}.png`),
|
||||
@@ -94,20 +106,53 @@ const server = http.createServer(async (request, response) => {
|
||||
await page.close();
|
||||
}
|
||||
}
|
||||
const page = await browser.newPage();
|
||||
const context = await browser.newContext();
|
||||
const page = await context.newPage();
|
||||
const errors = [];
|
||||
page.on('pageerror', (error) => errors.push(error.message));
|
||||
approved = false;
|
||||
await page.goto(origin);
|
||||
await page.locator('#access').fill('test-key');
|
||||
await page.getByRole('button', { name: 'Connect to watch' }).click();
|
||||
await page.getByText('Tap Allow browser on your watch.', { exact: false }).waitFor();
|
||||
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();
|
||||
checks++;
|
||||
await page.locator('#file').setInputFiles({
|
||||
name: 'wrong.txt',
|
||||
mimeType: 'text/plain',
|
||||
buffer: Buffer.from('test'),
|
||||
assert.deepEqual(await page.context().cookies(origin), [], 'No host-wide authorization cookie');
|
||||
let peerAuthorization;
|
||||
const peer = http.createServer((request, response) => {
|
||||
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++;
|
||||
const file = {
|
||||
name: 'test.apk',
|
||||
@@ -136,8 +181,15 @@ const server = http.createServer(async (request, response) => {
|
||||
checks++;
|
||||
state = 'installed';
|
||||
await page.getByRole('heading', { name: 'Looks good on you.' }).waitFor();
|
||||
state = 'waiting';
|
||||
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++;
|
||||
await page.locator('#file').setInputFiles(file);
|
||||
hold = true;
|
||||
@@ -148,7 +200,7 @@ const server = http.createServer(async (request, response) => {
|
||||
disconnected = true;
|
||||
await page.getByText('Watch out of reach', { exact: true }).waitFor();
|
||||
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();
|
||||
checks++;
|
||||
await page.getByRole('button', { name: 'Change color theme' }).click();
|
||||
@@ -177,6 +229,21 @@ const server = http.createServer(async (request, response) => {
|
||||
);
|
||||
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, []);
|
||||
const result = {
|
||||
browser: await browser.version(),
|
||||
|
||||
@@ -19,6 +19,8 @@ const path = require('node:path');
|
||||
page.on('pageerror', (error) => errors.push(error.message));
|
||||
await page.goto(session.href, { 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(
|
||||
await page.evaluate(() => document.documentElement.scrollWidth > innerWidth),
|
||||
false,
|
||||
@@ -27,25 +29,37 @@ const path = require('node:path');
|
||||
path: path.join(reports, 'android-browser.png'),
|
||||
fullPage: true,
|
||||
});
|
||||
const fixture =
|
||||
process.env.PAKKIT_TEST_APK ||
|
||||
path.resolve(__dirname, '../qa/fixture/build/outputs/apk/debug/qaFixture-debug.apk');
|
||||
if (process.env.PAKKIT_BROWSER_FILE) {
|
||||
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(
|
||||
path.resolve(__dirname, '../qa/fixture/build/outputs/apk/debug/qaFixture-debug.apk'),
|
||||
),
|
||||
buffer: fs.readFileSync(fixture),
|
||||
});
|
||||
}
|
||||
await page.getByRole('button', { name: 'Send to watch' }).click();
|
||||
await page.getByRole('heading', { name: 'Made it to your watch' }).waitFor({ timeout: 30000 });
|
||||
await page.screenshot({
|
||||
path: path.join(reports, 'android-browser-review.png'),
|
||||
fullPage: true,
|
||||
});
|
||||
const status = await page.evaluate(async (token) => {
|
||||
const status = await page.evaluate(async () => {
|
||||
const response = await fetch('/api/status', {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
headers: { Authorization: 'Bearer ' + localStorage.getItem('pakkitAccess') },
|
||||
});
|
||||
return response.json();
|
||||
}, session.hash.slice(1));
|
||||
});
|
||||
assert.equal(status.state, 'ready');
|
||||
assert.equal(status.label, 'Pakkit QA fixture');
|
||||
assert.deepEqual(errors, []);
|
||||
@@ -54,6 +68,7 @@ const path = require('node:path');
|
||||
directEmulatorWifi: true,
|
||||
upload: 'ready',
|
||||
javascriptErrors: errors,
|
||||
uploadedBytes: fs.statSync(fixture).size,
|
||||
};
|
||||
fs.writeFileSync(
|
||||
path.join(reports, 'android-browser.json'),
|
||||
|
||||
Reference in new issue
Block a user