refactor: consolidate Pakkit into a standalone Wear OS app

- Remove obsolete modules, dependencies, assets, and documentation
- Separate UI, receiving sessions, HTTP serving, storage, and installation
- Introduce typed package state and guard against stale callbacks
- Add reproducible emulator and browser tests
- Update build, signing, and release configuration
This commit is contained in:
Meghdad committed 2026-10-15 18:38:52 +03:30
1 parent 4d5d0b4165
commit 7d01d57e6f
136 files changed
+4820 -1771

No files matched your search

+18
View File
@@ -0,0 +1,18 @@
root = true
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
indent_style = space
indent_size = 4
[*.{html,css,js,cjs,json,yml,yaml}]
indent_size = 2
[*.md]
trim_trailing_whitespace = false
[*.bat]
end_of_line = crlf
+10 -15
View File
@@ -1,19 +1,14 @@
*.iml /.idea/
.gradle /.gradle/
/.kotlin/
/local.properties /local.properties
/.idea/caches
/.idea/libraries
/.idea/modules.xml
/.idea/workspace.xml
/.idea/navEditor.xml
/.idea/assetWizardSettings.xml
.DS_Store
/build
/captures
.externalNativeBuild
.cxx
local.properties
**/build/ **/build/
**/node_modules/
*.iml
*.jks *.jks
*.keystore *.keystore
.DS_Store
.externalNativeBuild/
.cxx/
**/__pycache__/
*.pyc
-3
View File
@@ -1,3 +0,0 @@
# Default ignored files
/shelf/
/workspace.xml
-6
View File
@@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<bytecodeTargetLevel target="21" />
</component>
</project>
+1
View File
@@ -5,6 +5,7 @@
<GradleProjectSettings> <GradleProjectSettings>
<option name="testRunner" value="CHOOSE_PER_TEST" /> <option name="testRunner" value="CHOOSE_PER_TEST" />
<option name="externalProjectPath" value="$PROJECT_DIR$" /> <option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="gradleJvm" value="jbr-21" />
<option name="modules"> <option name="modules">
<set> <set>
<option value="$PROJECT_DIR$" /> <option value="$PROJECT_DIR$" />
-6
View File
@@ -1,10 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project version="4"> <project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" /> <component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="ProjectRootManager" version="2" languageLevel="JDK_21" project-jdk-name="jbr-21" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build/classes" />
</component>
<component name="ProjectType">
<option name="id" value="Android" />
</component>
</project> </project>
+4
View File
@@ -0,0 +1,4 @@
{
"singleQuote": true,
"printWidth": 100
}
+40 -22
View File
@@ -1,40 +1,58 @@
# Pakkit — Pocket to Wrist. # Pakkit
One standalone Wear OS app. A browser on your Wi-Fi. No companion app. **Pocket to Wrist.** A standalone Wear OS application for sending an APK from any browser on your Wi-Fi to your watch, then approving installation on your wrist.
Pakkit starts a ten-minute receiving session on the watch, shows a private URL and QR code, and serves its own responsive web interface. Select a complete APK in the browser, send it directly to the watch, review it there, and approve the official Android installer. No ADB, root or developer options are used by the application. Play publication remains subject to permission declaration and review. Pack it. Send it. Wear it.
## Use ## Use
1. Install Pakkit on a supported Wear OS watch. The current build is a development APK; a Play listing has not been published. 1. Open Pakkit on a supported watch and allow it to request installations through the system settings screen.
2. Allow Pakkit to request installations using the watch’s system permission screen. If firmware does not expose this permission, use Google Play instead. 2. Connect the watch and browser device to the same trusted Wi-Fi.
3. Connect the watch and browser device to the same trusted Wi-Fi, then tap **Start receiving**. 3. Tap **Start receiving** and scan the QR code or type the complete private link. Opening only the address lets you enter the session key separately.
4. Scan the QR code or enter the full private link. If you enter just the address, enter the session key shown after `#` on the watch. 4. Select one complete `.apk` up to **50 MiB**. Watch transfer progress in the browser and on the watch.
5. Select one complete `.apk` up to 50 MiB. Transfer progress is shown on both devices. Review the package and approve installation on the watch. 5. Review the package on the watch, tap **Install**, and complete Android’s system approval.
6. End the session or let it expire. A fresh session has a new address/key. Turn off development wireless debugging after testing; it is unrelated to Pakkit’s receiving session. 6. End the receiving session when finished. Sessions automatically end after ten minutes or on Wi-Fi loss.
Local HTTP is **not encrypted**. The private link restricts access but does not protect against an attacker on the network. Use trusted Wi-Fi, keep the link private and install only apps you trust. Guest/client-isolated networks, VPNs and browser local-network restrictions can prevent access. Internet access and a paired phone are not needed for the transfer itself. 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 current artifacts are development builds. Public distribution requires the checks in [release preparation](docs/RELEASE.md).
## Project
| Path | Responsibility |
| ------------ | ------------------------------------------------------------------------------------------------------------------ |
| `app` | The Wear OS application: native watch UI, bundled web interface, private storage, Wi-Fi receiving and installation |
| `qa/fixture` | Small signed test APK, included only in instrumentation assets |
| `web-tests` | Optional browser test tooling; nothing from this directory ships in the app |
| `scripts` | Emulator-only test runner and ADB helpers |
| `docs` | Architecture, design, development, platform, privacy and release guidance |
There is one production module and one test-fixture module. Production has one explicit library dependency: ZXing Core for local QR generation. Kotlin’s standard library is supplied by the Android Gradle plugin.
## Build ## Build
Java 21, Android SDK 36.1, min SDK 31, target SDK 36. Application ID `meghdad.pakkit`, version `0.2.0` / `100003`. Use **JDK 21**, Android SDK **36.1**, Build Tools installed by the SDK, and the Gradle wrapper. Open the project in Android Studio and run the `app` configuration on a Wear OS Emulator. Minimum Android API is 31; target is 36.
```sh ```sh
./gradlew :wear:assembleDebug :shared:testDebugUnitTest :wear:lint :wear:bundleRelease ./gradlew :app:assembleDebug :app:testDebugUnitTest :app:lint :app:bundleRelease
``` ```
Optional mirror when Google Maven is unavailable: `-PpakkitGoogleMavenMirror=https://maven.aliyun.com/repository/google`. Review dependency provenance in your release environment. - APK: `app/build/outputs/apk/debug/app-debug.apk`
- AAB: `app/build/outputs/bundle/release/app-release.aab`
- Signing: set all four documented `PAKKIT_*` variables or leave them all unset for unsigned release output.
- Debug APK: `wear/build/outputs/apk/debug/wear-debug.apk` If Google Maven is inaccessible in your environment, the optional build property `-PpakkitGoogleMavenMirror=https://maven.aliyun.com/repository/google` selects a mirror. Official Google Maven is the default; use a trusted dependency source for release builds.
- Release AAB: `wear/build/outputs/bundle/release/wear-release.aab`
- Release signing: see [release preparation](docs/RELEASE.md). No signing secrets are included.
## Structure ## Test
- `wear`: foreground Wi-Fi session, local HTTP server, bundled web assets, round watch UI, source approval and PackageInstaller consent. Routine development uses emulators. No physical watch is required.
- `shared`: bounded HTTP parsing, package inspection, integrity, storage, native design primitives and unit tests.
- `qa/fixture`: harmless signed test app, staged only into instrumentation assets; never included in the consumer app.
The former phone module and Data Layer/WorkManager transport have been removed. Historical companion screenshots are retained as design history; current screenshots are in `docs/screenshots/standalone`. ```sh
./gradlew :app:assembleDebug :app:assembleDebugAndroidTest :app:testDebugUnitTest
python 3 scripts/test-emulators.py --watch emulator-5554 --skip-build
python 3 scripts/test-emulators.py --watch emulator-5554 --small --skip-build
```
[Feasibility and platform evidence](docs/FEASIBILITY.md) · [Architecture/security](docs/ARCHITECTURE.md) · [Validation](docs/VALIDATION.md) · [Brand](design/README.md) · [Privacy](docs/PRIVACY.md) 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)
+80
View File
@@ -0,0 +1,80 @@
plugins { alias(libs.plugins.android.application) }
android {
namespace = "meghdad.pakkit"
compileSdk { version = release(36) { minorApiLevel = 1 } }
defaultConfig {
applicationId = "meghdad.pakkit"
minSdk = 31
targetSdk = 36
versionCode = 100004
versionName = "0.3.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
val releaseKey = providers.environmentVariable("PAKKIT_KEYSTORE").orNull
val releaseStorePassword = providers.environmentVariable("PAKKIT_KEYSTORE_PASSWORD").orNull
val releaseAlias = providers.environmentVariable("PAKKIT_KEY_ALIAS").orNull
val releaseKeyPassword = providers.environmentVariable("PAKKIT_KEY_PASSWORD").orNull
val signingInputs = listOf(releaseKey, releaseStorePassword, releaseAlias, releaseKeyPassword)
require(signingInputs.all { it == null } || signingInputs.all { !it.isNullOrBlank() }) {
"Set all four PAKKIT signing variables, or leave all unset for an unsigned bundle."
}
if (signingInputs.all { it != null }) {
signingConfigs.create("production") {
storeFile = file(requireNotNull(releaseKey))
storePassword = releaseStorePassword
keyAlias = releaseAlias
keyPassword = releaseKeyPassword
}
}
buildTypes {
release {
signingConfig = signingConfigs.findByName("production")
isMinifyEnabled = true
isShrinkResources = true
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"))
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
}
dependencies {
implementation(libs.zxing)
testImplementation(libs.junit)
androidTestImplementation(libs.androidx.junit)
androidTestImplementation(libs.androidx.runner)
}
abstract class StageFixtureApk : DefaultTask() {
@get:InputFile abstract val fixtureFile: RegularFileProperty
@get:OutputDirectory abstract val outputDirectory: DirectoryProperty
@TaskAction
fun stage() {
val output = outputDirectory.file("fixture.apk").get().asFile
output.parentFile.mkdirs()
fixtureFile.get().asFile.copyTo(output, overwrite = true)
}
}
val stageTestFixture by
tasks.registering(StageFixtureApk::class) {
dependsOn(":qaFixture:assembleDebug")
fixtureFile.set(
project(":qaFixture")
.layout
.buildDirectory
.file("outputs/apk/debug/qaFixture-debug.apk"),
)
outputDirectory.set(layout.buildDirectory.dir("generated/testAssets"))
}
androidComponents.onVariants(androidComponents.selector().withBuildType("debug")) { variant ->
variant.androidTest
?.sources
?.assets
?.addGeneratedSourceDirectory(stageTestFixture, StageFixtureApk::outputDirectory)
}
@@ -0,0 +1,72 @@
package meghdad.pakkit
import android.content.Intent
import android.content.pm.PackageInstaller
import androidx.test.ext.junit.runners.AndroidJUnit4
import meghdad.pakkit.apk.InstallState
import meghdad.pakkit.install.ApkInstaller
import meghdad.pakkit.install.InstallReceiver
import meghdad.pakkit.install.PendingApproval
import org.junit.Assert.*
import org.junit.Assume.assumeTrue
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class InstallSafetyTest : WatchTest() {
@Test
fun receiptAndForgedCallbacksCannotMarkPackageInstalled() {
val apk = fixture()
store.stage(apk)
val sessions = context.packageManager.packageInstaller.mySessions.map { it.sessionId }
for ((job, session) in listOf(apk.id to -1, "wrong-job" to 42, apk.id to 42)) {
val intent =
Intent()
.putExtra("job", job)
.putExtra(PackageInstaller.EXTRA_SESSION_ID, session)
.putExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_SUCCESS)
instrumentation.runOnMainSync { InstallReceiver().onReceive(context, intent) }
assertEquals(InstallState.READY, store.pending()?.state)
}
assertEquals(
sessions,
context.packageManager.packageInstaller.mySessions.map { it.sessionId },
)
}
@Test
fun changedPackageCannotCreateAnInstallSession() {
assumeTrue(
"Enable source approval through the emulator's system UI",
context.packageManager.canRequestPackageInstalls(),
)
val apk = fixture()
store.stage(apk)
val before = context.packageManager.packageInstaller.mySessions.map { it.sessionId }
store.file(apk.id).appendText("changed")
ApkInstaller(context).install(apk)
assertEquals(InstallState.FAILED, store.pending()?.state)
assertTrue(store.pending()!!.detail.contains("changed"))
assertEquals(
before,
context.packageManager.packageInstaller.mySessions.map { it.sessionId },
)
}
@Test
fun officialInstallerRequiresSystemUserConsent() {
assumeTrue(
"Enable source approval through the emulator's system UI",
context.packageManager.canRequestPackageInstalls(),
)
val apk = fixture()
store.stage(apk)
openWatch()
ApkInstaller(context).install(apk)
await(10_000) { store.pending()?.state in setOf(InstallState.CONFIRM, InstallState.FAILED) }
assertEquals(store.pending()?.detail, InstallState.CONFIRM, store.pending()?.state)
assertEquals(apk.id, PendingApproval.id)
assertNotNull(PendingApproval.intent)
assertNotNull(store.pending()?.sessionId)
}
}
@@ -0,0 +1,132 @@
package meghdad.pakkit
import android.content.Intent
import androidx.test.ext.junit.runners.AndroidJUnit4
import java.net.Socket
import java.net.URI
import meghdad.pakkit.apk.InstallState
import meghdad.pakkit.transfer.ReceiveService
import meghdad.pakkit.transfer.Receiving
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class LocalReceiveTest : WatchTest() {
@Test
fun authenticatedUploadVerifiesPackageAndStopRevokesPrivateLink() {
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 }
fun request(
method: String,
path: String,
token: String? = url.fragment,
origin: String = "http://${url.authority}",
host: String = url.authority,
body: ByteArray? = null,
contentLength: Long? = body?.size?.toLong(),
): String {
return Socket(url.host, url.port).use { socket ->
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" +
(contentLength?.let {
"Content-Type: application/octet-stream\r\nContent-Length: $it\r\n"
} ?: "") +
"\r\n"
socket.getOutputStream().apply {
write(headers.toByteArray())
body?.let { write(it) }
flush()
}
socket.shutdownOutput()
val input = socket.getInputStream().buffered()
val head = StringBuilder()
while (!head.endsWith("\r\n\r\n")) {
val byte = input.read()
check(byte >= 0)
head.append(byte.toChar())
}
val length =
Regex("Content-Length: (\\d+)", RegexOption.IGNORE_CASE)
.find(head)!!
.groupValues[1]
.toInt()
val bytes = ByteArray(length)
var position = 0
while (position < length) {
val read = input.read(bytes, position, length - position)
check(read > 0)
position += read
}
head.toString() + bytes.toString(Charsets.UTF_8)
}
}
assertTrue(request("GET", "/").contains("Pocket"))
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", host = "attacker.example").startsWith("HTTP/1.1 403"),
)
assertTrue(
request(
"POST",
"/api/upload",
origin = "https://attacker.example",
body = byteArrayOf(1),
)
.startsWith("HTTP/1.1 403"),
)
assertTrue(
request("POST", "/api/upload", contentLength = 52_428_801).startsWith("HTTP/1.1 400"),
)
assertTrue(
request("POST", "/api/upload", body = "invalid APK".toByteArray())
.startsWith("HTTP/1.1 400"),
)
assertNull(store.pending())
assertTrue(
request("POST", "/api/upload", body = "short".toByteArray(), contentLength = 100)
.startsWith("HTTP/1.1 400"),
)
assertNull(store.pending())
assertEquals(0L, Receiving.state.total)
assertEquals("Ready to receive", Receiving.state.detail)
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)
assertEquals("meghdad.pakkit.fixture", store.pending()?.apk?.packageName)
assertEquals(
sessions,
context.packageManager.packageInstaller.mySessions.map { it.sessionId },
)
assertTrue(request("POST", "/api/upload", body = byteArrayOf(1)).startsWith("HTTP/1.1 409"))
assertTrue(request("GET", "/api/status").contains("ready"))
context.stopService(Intent(context, ReceiveService::class.java))
await { !Receiving.state.active }
assertNull(Receiving.state.url)
assertTrue(runCatching { Socket(url.host, url.port).close() }.isFailure)
}
@Test
fun staleWorkersCannotChangeANewReceivingSession() {
val old = Any()
val current = Any()
try {
Receiving.begin(old)
Receiving.begin(current)
Receiving.update(old) { it.copy(url = "stale link", received = 500) }
Receiving.end(old, "late shutdown")
assertTrue(Receiving.state.active)
assertNull(Receiving.state.url)
assertEquals(0L, Receiving.state.received)
} finally {
Receiving.end(current, "Session ended")
}
}
}
@@ -0,0 +1,40 @@
package meghdad.pakkit
import androidx.test.ext.junit.runners.AndroidJUnit4
import java.io.File
import java.util.UUID
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
import meghdad.pakkit.apk.ApkRules
import meghdad.pakkit.apk.PackageInspector
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class PackageInspectionTest : WatchTest() {
@Test
fun selfUpdateIsRejectedBeforeCreatingAnInstallSession() {
val ownApk = File(context.applicationInfo.sourceDir)
val digest = ownApk.inputStream().use { ApkRules.copyBounded(it).second }
val result = runCatching { PackageInspector.inspect(context, ownApk, digest) }
assertTrue(result.isFailure)
assertTrue(result.exceptionOrNull()?.message.orEmpty().contains("Google Play"))
}
@Test
fun zipWithoutAndroidManifestIsRejected() {
val file = store.file(UUID.randomUUID().toString())
try {
ZipOutputStream(file.outputStream()).use {
it.putNextEntry(ZipEntry("readme.txt"))
it.write("Not an app".toByteArray())
it.closeEntry()
}
val digest = file.inputStream().use { ApkRules.copyBounded(it).second }
assertTrue(runCatching { PackageInspector.inspect(context, file, digest) }.isFailure)
} finally {
file.delete()
}
}
}
@@ -0,0 +1,54 @@
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.*
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class PackageStoreTest : WatchTest() {
@Test
fun persistsReviewAcrossStoreInstancesAndRejectsReplacement() {
val apk = fixture()
store.stage(apk)
assertEquals(apk, PackageStore(context).pending())
assertTrue(runCatching { store.stage(apk.copy(detail = "replacement")) }.isFailure)
assertEquals(apk, store.pending())
}
@Test
fun expiredReviewAndOrphanedFileAreRemoved() {
val apk = fixture().copy(created = System.currentTimeMillis() - ApkRules.TTL_MS)
store.stage(apk)
val orphan = fixture()
store.file(orphan.id).setLastModified(System.currentTimeMillis() - ApkRules.TTL_MS - 1000)
store.clean()
assertNull(store.pending())
assertFalse(store.file(apk.id).exists())
assertFalse(store.file(orphan.id).exists())
}
@Test
fun lateUpdatesCannotResurrectDismissedReview() {
val apk = fixture()
store.stage(apk)
store.dismiss(apk.id)
assertFalse(store.update(apk.id, InstallState.INSTALLED, "late callback"))
assertNull(store.pending())
assertFalse(store.file(apk.id).exists())
}
@Test
fun readsStableSavedReviewFormatAndIgnoresMalformedData() {
val apk = fixture()
store.preferences.edit().putString(PackageStore.PENDING_KEY, apk.json().toString()).commit()
assertEquals(apk, store.pending())
store.dismiss(apk.id)
store.preferences.edit().putString(PackageStore.PENDING_KEY, "malformed").commit()
assertNull(store.pending())
store.preferences.edit().remove(PackageStore.PENDING_KEY).commit()
}
}
@@ -0,0 +1,35 @@
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("session ended"))
assertNull(store.pending())
}
}
}
@@ -0,0 +1,50 @@
package meghdad.pakkit
import android.graphics.Rect
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.test.ext.junit.runners.AndroidJUnit4
import meghdad.pakkit.ui.RoundScrollView
import meghdad.pakkit.ui.WatchDesign
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class WatchReviewTest : WatchTest() {
@Test
fun reviewActionsAreReachableAndReceiptDoesNotInstall() {
val apk = fixture()
store.stage(apk)
val before = context.packageManager.packageInstaller.mySessions.map { it.sessionId }
openWatch()
instrumentation.runOnMainSync {
fun views(view: View): List<View> =
listOf(view) +
if (view is ViewGroup)
(0 until view.childCount).flatMap { views(view.getChildAt(it)) }
else emptyList()
val all = views(requireNotNull(activity).window.decorView)
assertTrue(all.filterIsInstance<TextView>().any { it.text == apk.apk.label })
val scroll = all.filterIsInstance<RoundScrollView>().single()
val buttons = all.filterIsInstance<Button>()
assertTrue(buttons.any { it.text == "Install" || it.text == "Allow installs" })
for (button in buttons) {
assertTrue(button.height >= WatchDesign.dp(context, 48))
scroll.scrollTo(
0,
(button.top + button.height / 2 - scroll.height / 2).coerceAtLeast(0),
)
val visible = Rect()
assertTrue(button.getGlobalVisibleRect(visible))
assertEquals(button.height, visible.height())
}
}
assertEquals(
before,
context.packageManager.packageInstaller.mySessions.map { it.sessionId },
)
}
}
@@ -0,0 +1,63 @@
package meghdad.pakkit
import android.content.Intent
import android.graphics.Rect
import android.graphics.drawable.BitmapDrawable
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.google.zxing.BinaryBitmap
import com.google.zxing.MultiFormatReader
import com.google.zxing.RGBLuminanceSource
import com.google.zxing.common.HybridBinarizer
import kotlin.math.hypot
import kotlin.math.min
import meghdad.pakkit.transfer.ReceiveService
import meghdad.pakkit.transfer.Receiving
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class WatchSessionTest : WatchTest() {
@Test
fun receivingQrDecodesAndFitsWithinCircularDisplay() {
openWatch()
context.startForegroundService(Intent(context, ReceiveService::class.java))
await(30_000) { Receiving.state.url != null }
instrumentation.waitForIdleSync()
instrumentation.runOnMainSync {
fun views(view: View): List<View> =
listOf(view) +
if (view is ViewGroup)
(0 until view.childCount).flatMap { views(view.getChildAt(it)) }
else emptyList()
val screen = requireNotNull(activity).window.decorView
val image =
views(screen).filterIsInstance<ImageView>().single {
it.contentDescription?.startsWith("QR code") == true
}
val visible = Rect()
assertTrue(image.getGlobalVisibleRect(visible))
val size = min(image.width, image.height)
val radius = min(screen.width, screen.height) / 2.0
for (x in listOf(visible.centerX() - size / 2.0, visible.centerX() + size / 2.0)) {
for (y in listOf(visible.centerY() - size / 2.0, visible.centerY() + size / 2.0)) {
assertTrue(
"Full QR square stays within the bezel",
hypot(x - screen.width / 2.0, y - screen.height / 2.0) < radius,
)
}
}
val bitmap = (image.drawable as BitmapDrawable).bitmap
val pixels = IntArray(bitmap.width * bitmap.height)
bitmap.getPixels(pixels, 0, bitmap.width, 0, 0, bitmap.width, bitmap.height)
val source = RGBLuminanceSource(bitmap.width, bitmap.height, pixels)
assertEquals(
Receiving.state.url,
MultiFormatReader().decode(BinaryBitmap(HybridBinarizer(source))).text,
)
}
}
}
@@ -0,0 +1,78 @@
package meghdad.pakkit
import android.app.Activity
import android.app.NotificationManager
import android.content.Intent
import androidx.test.platform.app.InstrumentationRegistry
import java.util.UUID
import meghdad.pakkit.apk.ApkRules
import meghdad.pakkit.apk.PackageInspector
import meghdad.pakkit.apk.PendingApk
import meghdad.pakkit.data.PackageStore
import meghdad.pakkit.install.PendingApproval
import meghdad.pakkit.transfer.ReceiveService
import meghdad.pakkit.transfer.Receiving
import meghdad.pakkit.ui.WatchActivity
import org.junit.After
import org.junit.Before
abstract class WatchTest {
protected val instrumentation = InstrumentationRegistry.getInstrumentation()
protected val context = instrumentation.targetContext
protected val store = PackageStore(context)
protected var activity: Activity? = null
@Before
fun prepare() {
context.stopService(Intent(context, ReceiveService::class.java))
await { !Receiving.state.active }
store.pending()?.let { store.dismiss(it.id) }
PendingApproval.clear()
}
protected fun openWatch() {
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),
)
activity = requireNotNull(monitor.waitForActivityWithTimeout(5000))
instrumentation.removeMonitor(monitor)
instrumentation.waitForIdleSync()
}
protected fun fixture(): PendingApk {
val id = UUID.randomUUID().toString()
val file = store.file(id)
val digest =
instrumentation.context.assets.open("fixture.apk").use { input ->
file.outputStream().use { ApkRules.copyBounded(input, it).second }
}
return PendingApk(
id,
System.currentTimeMillis(),
PackageInspector.inspect(context, file, digest),
)
}
protected fun await(timeout: Long = 5000, condition: () -> Boolean) {
val end = System.currentTimeMillis() + timeout
while (!condition() && System.currentTimeMillis() < end) Thread.sleep(25)
check(condition()) { "Condition did not become true within ${timeout}ms" }
}
@After
fun clean() {
context.stopService(Intent(context, ReceiveService::class.java))
await { !Receiving.state.active }
store.pending()?.let { pending ->
pending.sessionId?.let {
runCatching { context.packageManager.packageInstaller.abandonSession(it) }
}
store.dismiss(pending.id)
}
PendingApproval.clear()
context.getSystemService(NotificationManager::class.java).cancelAll()
instrumentation.runOnMainSync { activity?.finish() }
}
}
+37
View File
@@ -0,0 +1,37 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-feature android:name="android.hardware.type.watch" android:required="true" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE" />
<application
android:allowBackup="false"
android:dataExtractionRules="@xml/pakkit_data_rules"
android:icon="@mipmap/pakkit_launcher"
android:label="@string/pakkit_name"
android:supportsRtl="true"
android:theme="@style/Theme.Pakkit">
<meta-data android:name="com.google.android.wearable.standalone" android:value="true" />
<activity
android:name=".ui.WatchActivity"
android:exported="true"
android:launchMode="singleTop"
android:taskAffinity="">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".transfer.ReceiveService"
android:exported="false"
android:foregroundServiceType="connectedDevice" />
<receiver android:name=".install.InstallReceiver" android:exported="false" />
</application>
</manifest>
+228
View File
@@ -0,0 +1,228 @@
'use strict';
const $ = (id) => document.getElementById(id);
let token = location.hash.slice(1),
file = null,
upload = null,
online = false,
pending = false;
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 message(text = '') {
$('message').textContent = text;
}
function panel(id) {
['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 complete .apk file up to 50 MiB. App bundles and split packages aren’t supported.',
);
return;
}
file = next;
$('filename').textContent = file.name;
$('filesize').textContent =
(file.size / 1048576).toFixed(2) + ' MiB · ready for its next adventure';
panel('selection');
}
$('choose').onclick = () => $('file').click();
$('file').onchange = () => {
selected($('file').files[0]);
$('file').value = '';
};
$('remove').onclick = () => {
file = null;
panel('dropzone');
message();
};
const zone = $('dropzone');
['dragenter', 'dragover'].forEach((name) =>
zone.addEventListener(name, (e) => {
e.preventDefault();
if (online) zone.classList.add('dragging');
}),
);
['dragleave', 'drop'].forEach((name) =>
zone.addEventListener(name, (e) => {
e.preventDefault();
zone.classList.remove('dragging');
}),
);
zone.addEventListener('drop', (e) => {
if (e.dataTransfer.files.length !== 1) message('Choose one APK at a time.');
else selected(e.dataTransfer.files[0]);
});
window.addEventListener('dragover', (e) => e.preventDefault());
window.addEventListener('drop', (e) => e.preventDefault());
function result(title, detail, success = false) {
panel('result');
$('result-title').textContent = title;
$('result-detail').textContent = detail;
$('result-icon').textContent = success ? '✓' : '↗';
$('again').hidden = true;
}
$('send').onclick = () => {
if (!file || !online || upload) return;
message();
panel('progress-panel');
$('progress').value = 0;
$('percentage').textContent = '0%';
$('progress-title').textContent = 'On its way.';
$('cancel').hidden = false;
const xhr = new XMLHttpRequest();
upload = xhr;
xhr.open('POST', '/api/upload');
xhr.setRequestHeader('Authorization', 'Bearer ' + token);
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
xhr.timeout = 300000;
xhr.upload.onprogress = (e) => {
if (!e.lengthComputable) return;
const percent = Math.floor((e.loaded / e.total) * 100);
$('progress').value = percent;
$('percentage').textContent = percent + '%';
if (percent === 100) {
$('progress-title').textContent = 'A final check.';
$('progress-detail').textContent =
'Your watch is checking the package. Installation still needs your approval.';
}
};
const failed = (text) => {
upload = null;
panel('selection');
message(text);
};
xhr.onload = () => {
upload = null;
let data;
try {
data = JSON.parse(xhr.responseText);
} catch {
failed('The watch returned an unexpected response. Try a new session.');
return;
}
if (xhr.status !== 200) {
failed(data.error || 'The file could not be transferred. Try again.');
return;
}
pending = true;
file = null;
result(
'Over to your wrist.',
'Review ' + data.label + ' and approve installation on your watch.',
);
poll();
};
xhr.onerror = () =>
failed('The connection was interrupted. Keep both devices on the same Wi-Fi and try again.');
xhr.ontimeout = () => failed('The transfer timed out. Start a new watch session and try again.');
xhr.onabort = () => failed('Transfer cancelled. Check your watch before trying again.');
xhr.send(file);
};
$('cancel').onclick = () => upload?.abort();
$('again').onclick = () => {
if (!pending) {
file = null;
panel('dropzone');
message();
}
};
$('access-form').onsubmit = (e) => {
e.preventDefault();
token = $('access').value.trim().replace(/^.*#/, '');
$('access').value = '';
poll();
};
let polling = false;
async function poll() {
if (polling || !token) return;
polling = true;
try {
const response = await fetch('/api/status', {
headers: { Authorization: 'Bearer ' + token },
cache: 'no-store',
signal: AbortSignal.timeout ? AbortSignal.timeout(5000) : undefined,
});
if (response.status === 403) {
online = false;
$('access-form').hidden = false;
$('choose').disabled = true;
$('connection').textContent = 'Private link needed';
message('Use the current QR code or private session key shown on your watch.');
return;
}
if (!response.ok) throw new Error('disconnected');
const data = await response.json();
if (!online) message();
online = true;
$('send').disabled = false;
$('access-form').hidden = true;
$('connection').textContent = 'Connected to your watch';
$('expiry').textContent =
'· ' +
Math.floor(data.expiresIn / 60) +
':' +
String(data.expiresIn % 60).padStart(2, '0') +
' left';
$('choose').disabled = false;
if (upload) return;
const waiting = data.state === 'waiting';
if (!waiting) {
pending = true;
const states = {
ready: ['Over to your wrist.', 'Review ' + data.label + ' and tap Install on your watch.'],
confirm: [
'Your watch. Your call.',
'Continue to the system approval screen on your watch.',
],
installing: ['One last step.', 'Follow the system installer on your watch.'],
installed: ['Looks good on you.', data.label + ' is installed. Open it on your watch.'],
failed: ['A small detour.', data.detail],
};
const content = states[data.state] || ['Check your watch.', data.detail];
result(content[0], content[1], data.state === 'installed');
} else if (pending) {
pending = false;
result('Ready for another?', 'Your watch is ready to receive a new app.', true);
$('again').hidden = false;
}
} catch {
online = false;
$('send').disabled = true;
$('connection').textContent = 'Watch connection paused';
$('choose').disabled = true;
if (!upload)
message(
'Keep your watch on Wi-Fi. If the session ended, start a new one and open its new link.',
);
} finally {
polling = false;
}
}
if (!token) {
$('access-form').hidden = false;
$('choose').disabled = true;
$('connection').textContent = 'Private link needed';
}
poll();
setInterval(() => {
if (!document.hidden) poll();
}, 1500);
document.addEventListener('visibilitychange', () => {
if (!document.hidden) poll();
});
+228
View File
@@ -0,0 +1,228 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<meta name="color-scheme" content="dark light" />
<meta name="referrer" content="no-referrer" />
<title>Pakkit — Pocket to Wrist.</title>
<link rel="stylesheet" href="/style.css" />
<script src="/app.js" defer></script>
</head>
<body>
<div class="ambient" aria-hidden="true"></div>
<div class="shell">
<header>
<a class="wordmark" href="/" aria-label="Pakkit home"
><span class="brand-icon" aria-hidden="true"
><svg viewBox="0 0 40 40" fill="none">
<path d="M9 20L20 25L31 20V31L20 36L9 31Z" fill="#C9B8FF" />
<path d="M20 25V36M9 20L20 15L31 20" stroke="white" stroke-width="1.3" />
<path
d="M9 20L3 16L14 11L20 15L26 11L37 16L31 20L37 24L26 29L20 25L14 29L3 24Z"
fill="#9CF1E4"
/>
<rect
x="17"
y="3"
width="10"
height="10"
rx="3"
transform="rotate(20 22 8)"
fill="white"
/></svg></span
>Pakkit<span class="brand-dot">.</span></a
>
<div class="connection">
<span></span><span id="connection">Connecting to your watch</span>
</div>
<button id="theme" class="icon-button" aria-label="Change color theme">◐</button>
</header>
<main>
<section class="intro">
<p class="eyebrow">A LITTLE MAGIC. RIGHT ON YOUR WRIST.</p>
<h1>Pocket<br />to <em>Wrist.</em></h1>
<p class="lede">
Your favorite apps, with a shorter journey.<br />One watch. Any browser. All yours.
</p>
<div class="parcel-stage" aria-hidden="true">
<div class="orbit orbit-one"></div>
<div class="orbit orbit-two"></div>
<svg class="parcel" viewBox="0 0 360 340" fill="none">
<defs>
<linearGradient
gradientUnits="userSpaceOnUse"
id="left"
x1="90"
y1="150"
x2="220"
y2="290"
>
<stop stop-color="#45E8EF" />
<stop offset=".52" stop-color="#7851FF" />
<stop offset="1" stop-color="#B676FF" />
</linearGradient>
<linearGradient
gradientUnits="userSpaceOnUse"
id="right"
x1="175"
y1="150"
x2="290"
y2="280"
>
<stop stop-color="#C784FF" />
<stop offset=".6" stop-color="#FF91BB" />
<stop offset="1" stop-color="#FFC38B" />
</linearGradient>
<linearGradient
gradientUnits="userSpaceOnUse"
id="lid"
x1="85"
y1="95"
x2="220"
y2="175"
>
<stop stop-color="#90F4F2" />
<stop offset="1" stop-color="#A786FF" />
</linearGradient>
<linearGradient
gradientUnits="userSpaceOnUse"
id="tile"
x1="160"
y1="40"
x2="225"
y2="110"
>
<stop stop-color="#77F3EF" />
<stop offset="1" stop-color="#9B61FF" />
</linearGradient>
</defs>
<path d="M99 166L180 198V285L99 250Z" fill="url(#left)" />
<path d="M180 198L262 166V250L180 285Z" fill="url(#right)" />
<path d="M99 166L180 132L262 166L180 201Z" fill="#302252" />
<path
d="M99 166L56 137Q52 133 58 130L138 98L180 132Z"
fill="url(#lid)"
stroke="#B5FFFF"
/>
<path
d="M180 132L223 99L301 131Q308 134 302 139L262 166Z"
fill="url(#right)"
stroke="#FFE1DF"
/>
<path
d="M99 166L180 201L139 231L58 196Q52 192 58 188Z"
fill="url(#lid)"
stroke="#BDFFFF"
/>
<path
d="M180 201L262 166L302 188Q308 192 302 196L221 231Z"
fill="url(#right)"
stroke="#F3D5FF"
/>
<g class="app-tile">
<rect
x="160"
y="33"
width="62"
height="72"
rx="15"
transform="rotate(24 190 70)"
fill="url(#tile)"
stroke="#D8D3FF"
stroke-width="2"
/>
<path d="M176 64L188 60L201 70L190 75L176 64Z" fill="white" opacity=".8" />
</g>
<path d="M69 86L72 78L75 86L83 89L75 92L72 100L69 92L61 89Z" fill="#87F6E3" />
<path d="M284 69L287 61L290 69L298 72L290 75L287 83L284 75L276 72Z" fill="#BA9BFF" />
<circle cx="278" cy="246" r="3" fill="#77EFD8" /></svg
><span class="stage-caption">PACK IT. SEND IT. WEAR IT.</span>
</div>
</section>
<section class="transfer-card" aria-labelledby="card-title">
<div class="card-top">
<span class="pill">DIRECT TO YOUR WATCH</span
><span class="private-label">↗ On your Wi-Fi</span>
</div>
<h2 id="card-title">A new home<br />for your next app.</h2>
<p class="card-description">Choose a compatible APK. We’ll take it from here.</p>
<form id="access-form" hidden>
<label for="access">Private session key</label>
<p>Scan the QR code or enter the key after # in your watch’s link.</p>
<input id="access" autocomplete="off" spellcheck="false" required /><button
class="primary"
type="submit"
>
Connect to watch
</button>
</form>
<div id="dropzone" class="dropzone">
<div class="upload-symbol" aria-hidden="true">↑</div>
<strong>Drop a little possibility.</strong
><span>Drag your APK here, or choose a file below.</span
><button id="choose" class="primary" type="button">
Choose an APK <span aria-hidden="true">↗</span></button
><input
id="file"
type="file"
accept=".apk,application/vnd.android.package-archive"
hidden
/><small>Single .apk file · up to 50 MiB</small>
</div>
<div id="selection" hidden>
<div class="file-row">
<div class="file-icon" aria-hidden="true">◇</div>
<div><strong id="filename"></strong><small id="filesize"></small></div>
<button id="remove" class="icon-button" aria-label="Remove selected file">×</button>
</div>
<button id="send" class="primary" type="button">
Send to my watch <span aria-hidden="true">→</span>
</button>
</div>
<div id="progress-panel" hidden>
<div class="progress-heading">
<strong id="progress-title">On its way.</strong><span id="percentage">0%</span>
</div>
<progress id="progress" max="100" value="0" aria-label="APK upload progress"></progress>
<p id="progress-detail">Keep this page open while your app travels.</p>
<button id="cancel" class="secondary" type="button">Cancel transfer</button>
</div>
<div id="result" hidden>
<div id="result-icon" aria-hidden="true">✓</div>
<h3 id="result-title">Over to your wrist.</h3>
<p id="result-detail">Review the app and confirm installation on your watch.</p>
<button id="again" class="secondary" type="button" hidden>Choose another APK</button>
</div>
<p id="message" role="status" aria-live="polite"></p>
<div class="consent-note">
<span aria-hidden="true">✧</span>
<p>
Your watch. Your call.<br /><span
>Nothing installs until you approve it on your watch.</span
>
</p>
</div>
</section>
</main>
<section class="journey" aria-label="How it works">
<div>
<span>01</span>
<p><strong>Pick your app.</strong><br />A complete APK you trust.</p>
</div>
<div>
<span>02</span>
<p><strong>Send it over.</strong><br />Straight across your Wi-Fi.</p>
</div>
<div>
<span>03</span>
<p><strong>Make it yours.</strong><br />Approve it on your wrist.</p>
</div>
</section>
<footer>
<span>Pakkit <span class="muted">/ A lighter way to wear your apps.</span></span
><span>Local HTTP session · trusted Wi-Fi only <span id="expiry"></span></span>
</footer>
</div>
</body>
</html>
+685
View File
@@ -0,0 +1,685 @@
:root {
color-scheme: dark;
--bg: #090b17;
--surface: #131524;
--text: #f5f3ff;
--muted: #a9abc2;
--border: #ffffff15;
--violet: #aa96ff;
--mint: #80efd8;
--soft: #ffffff05;
--shadow: #02030d55;
--error: #ffadb9;
font-family:
Inter,
ui-sans-serif,
system-ui,
-apple-system,
BlinkMacSystemFont,
'Segoe UI',
sans-serif;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
background: var(--bg);
color: var(--text);
min-width: 300px;
}
button,
input {
font: inherit;
}
button,
a,
input {
-webkit-tap-highlight-color: transparent;
}
button {
cursor: pointer;
}
button:disabled {
cursor: default;
opacity: 0.5;
}
button:focus-visible,
a:focus-visible,
input:focus-visible,
.dropzone:focus-within {
outline: 3px solid var(--mint);
outline-offset: 5px;
}
[hidden] {
display: none !important;
}
.ambient {
position: absolute;
top: 0;
left: 0;
right: 0;
height: 850px;
pointer-events: none;
background:
radial-gradient(ellipse at 10% 40%, #7145ec19, transparent 50%),
radial-gradient(ellipse at 95% 10%, #28e0d60b, transparent 45%);
}
.shell {
max-width: 1260px;
margin: auto;
padding: 34px 52px 24px;
position: relative;
}
header {
display: flex;
align-items: center;
gap: 20px;
}
.wordmark {
font-size: 30px;
font-weight: 780;
letter-spacing: -1.2px;
color: var(--text);
text-decoration: none;
display: flex;
align-items: center;
gap: 9px;
}
.brand-icon {
background: linear-gradient(140deg, #bda8ff, #7049ed);
border-radius: 11px;
width: 35px;
height: 35px;
display: grid;
place-items: center;
color: white;
font-size: 31px;
line-height: 1;
}
.brand-dot {
color: var(--mint);
margin-left: -9px;
}
.connection {
margin-left: auto;
display: flex;
align-items: center;
gap: 9px;
font-size: 12px;
color: var(--muted);
}
.connection > span:first-child {
width: 6px;
height: 6px;
background: var(--mint);
border-radius: 50%;
box-shadow: 0 0 12px #80efd855;
}
.icon-button {
border: 1px solid var(--border);
border-radius: 50%;
background: var(--soft);
color: var(--text);
width: 40px;
height: 40px;
font-size: 22px;
flex-shrink: 0;
}
main {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 70px;
align-items: center;
padding: 76px 0 54px;
}
.eyebrow {
font-size: 10px;
letter-spacing: 2.6px;
color: var(--violet);
font-weight: 750;
margin: 0 0 24px;
}
h1 {
font-size: clamp(66px, 7.6vw, 104px);
line-height: 0.99;
letter-spacing: -6px;
font-weight: 740;
margin: 0;
}
h1 em {
font-style: normal;
background: linear-gradient(110deg, #bd9fff, #91befc 60%, #79e7d6);
background-clip: text;
color: transparent;
}
.lede {
font-size: 16px;
line-height: 1.8;
color: var(--muted);
margin: 24px 0 0;
}
.parcel-stage {
position: relative;
height: 250px;
max-width: 390px;
margin: 0 auto;
display: flex;
align-items: center;
justify-content: center;
}
.parcel-stage:before {
content: '';
position: absolute;
inset: 18% 12%;
background: radial-gradient(ellipse, #8752ff29, transparent 65%);
border-radius: 50%;
}
.parcel {
width: 285px;
height: 270px;
position: relative;
filter: drop-shadow(0 16px 26px #8560e522);
animation: arrive 0.8s ease-out both;
}
.orbit {
position: absolute;
width: 300px;
height: 75px;
border: 1px solid #a997ff24;
border-radius: 50%;
transform: rotate(-13deg);
bottom: 36px;
}
.orbit-two {
width: 340px;
bottom: 26px;
border-color: #8df2de0c;
}
.stage-caption {
position: absolute;
bottom: -5px;
font-size: 9px;
letter-spacing: 3px;
color: var(--muted);
}
.transfer-card {
background: linear-gradient(145deg, var(--surface), var(--bg));
border: 1px solid var(--border);
border-radius: 30px;
padding: 30px;
box-shadow: 0 24px 80px var(--shadow);
position: relative;
overflow: hidden;
}
.transfer-card:before {
content: '';
height: 2px;
position: absolute;
left: 40px;
right: 40px;
top: 0;
background: linear-gradient(90deg, transparent, #a088ff77, transparent);
}
.card-top {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.pill {
font-size: 9px;
font-weight: 750;
letter-spacing: 1px;
background: #9e82ff12;
color: var(--violet);
border: 1px solid #a88bff1a;
border-radius: 30px;
padding: 8px 10px;
}
.private-label {
font-size: 10px;
color: var(--muted);
}
h2 {
font-size: 34px;
line-height: 1.13;
letter-spacing: -1.5px;
margin: 28px 0 12px;
font-weight: 650;
}
.card-description {
color: var(--muted);
font-size: 13px;
line-height: 1.7;
margin: 0 0 24px;
}
.dropzone {
border: 1px dashed #a596d047;
background: var(--soft);
border-radius: 18px;
display: flex;
align-items: center;
flex-direction: column;
padding: 26px 16px 20px;
transition:
background 0.2s,
border-color 0.2s,
transform 0.2s;
}
.dropzone.dragging {
border-color: var(--mint);
background: #7aefd513;
transform: scale(1.01);
}
.upload-symbol {
width: 45px;
height: 45px;
border: 1px solid #a58aff40;
border-radius: 14px;
background: linear-gradient(140deg, #b294ff20, #6941d309);
color: var(--violet);
display: grid;
place-items: center;
font-size: 28px;
margin-bottom: 18px;
}
.dropzone strong {
font-size: 16px;
font-weight: 600;
letter-spacing: -0.3px;
}
.dropzone > span {
font-size: 11px;
color: var(--muted);
margin: 8px 0 20px;
text-align: center;
}
.primary {
border: 1px solid #c3abff40;
border-radius: 12px;
background: linear-gradient(115deg, #835bf1, #6540db);
color: #fff;
min-height: 48px;
padding: 13px 20px;
font-size: 13px;
font-weight: 650;
box-shadow: 0 5px 20px #6840db20;
transition:
transform 0.18s,
box-shadow 0.18s;
display: flex;
justify-content: center;
align-items: center;
gap: 25px;
width: 100%;
}
.dropzone .primary {
width: 90%;
max-width: 255px;
}
.primary:hover:enabled {
transform: translateY(-2px);
box-shadow: 0 9px 28px #6840db40;
}
.primary:active:enabled {
transform: translateY(0);
}
small {
color: var(--muted);
font-size: 10px;
display: block;
}
.dropzone small {
margin-top: 14px;
}
.consent-note {
display: flex;
gap: 12px;
align-items: center;
border-top: 1px solid var(--border);
margin-top: 24px;
padding-top: 20px;
}
.consent-note > span {
color: var(--mint);
font-size: 24px;
}
.consent-note p {
font-size: 11px;
line-height: 1.8;
margin: 0;
}
.consent-note p span {
color: var(--muted);
font-size: 10px;
}
#message {
font-size: 12px;
line-height: 1.65;
color: var(--error);
margin: 12px 0 0;
}
#message:empty {
display: none;
}
.journey {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 30px;
border-top: 1px solid var(--border);
padding: 29px 0;
}
.journey > div {
display: flex;
gap: 17px;
align-items: center;
}
.journey > div > span {
color: var(--violet);
font-size: 11px;
font-variant-numeric: tabular-nums;
border: 1px solid var(--border);
border-radius: 50%;
width: 34px;
height: 34px;
display: grid;
place-items: center;
flex-shrink: 0;
}
.journey p {
margin: 0;
font-size: 11px;
color: var(--muted);
line-height: 1.9;
}
.journey strong {
color: var(--text);
font-size: 12px;
font-weight: 600;
}
footer {
display: flex;
justify-content: space-between;
gap: 20px;
border-top: 1px solid var(--border);
padding-top: 22px;
color: var(--muted);
font-size: 9px;
line-height: 1.8;
}
.muted {
opacity: 0.7;
}
.file-row {
display: flex;
align-items: center;
gap: 12px;
background: var(--soft);
border: 1px solid var(--border);
border-radius: 14px;
padding: 16px;
margin-bottom: 18px;
}
.file-row > div:nth-child(2) {
min-width: 0;
flex: 1;
}
.file-row strong {
font-size: 13px;
overflow-wrap: anywhere;
}
.file-row small {
margin-top: 7px;
}
.file-icon {
color: var(--mint);
font-size: 30px;
}
.secondary {
color: var(--text);
border: 1px solid var(--border);
border-radius: 12px;
background: var(--soft);
min-height: 44px;
padding: 12px 18px;
width: 100%;
font-size: 12px;
}
.progress-heading {
display: flex;
justify-content: space-between;
font-size: 14px;
margin-top: 30px;
}
progress {
width: 100%;
height: 8px;
border: 0;
border-radius: 8px;
overflow: hidden;
accent-color: var(--mint);
margin: 20px 0 6px;
}
progress::-webkit-progress-bar {
background: #a09abd22;
border-radius: 8px;
}
progress::-webkit-progress-value {
background: linear-gradient(90deg, #8560ed, #7be6da);
border-radius: 8px;
}
progress::-moz-progress-bar {
background: #80efd8;
}
#progress-detail,
#result-detail {
font-size: 12px;
line-height: 1.8;
color: var(--muted);
}
#result {
text-align: center;
padding: 18px 4px;
}
#result-icon {
border-radius: 50%;
width: 55px;
height: 55px;
margin: 8px auto 18px;
background: #80efd815;
color: var(--mint);
font-size: 29px;
display: grid;
place-items: center;
}
h3 {
font-size: 24px;
letter-spacing: -0.8px;
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);
border: 1px solid var(--border);
border-radius: 10px;
color: var(--text);
padding: 12px;
margin: 4px 0 12px;
}
[data-theme='light'] {
color-scheme: light;
--bg: #f6f5fc;
--surface: #fff;
--text: #171526;
--muted: #686478;
--border: #26144318;
--violet: #6440bc;
--mint: #087866;
--soft: #7150ef04;
--shadow: #4420800c;
--error: #a52445;
}
[data-theme='light'] h1 em {
background: linear-gradient(110deg, #7144d7, #3669ba 65%, #16866f);
background-clip: text;
}
[data-theme='light'] .parcel-stage:before {
background: radial-gradient(ellipse, #8158e51c, transparent 70%);
}
@keyframes arrive {
from {
opacity: 0;
transform: translateY(12px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@media (prefers-reduced-motion: reduce) {
*,
*:before,
*:after {
animation: none !important;
transition: none !important;
scroll-behavior: auto !important;
}
}
@media (max-width: 900px) {
.shell {
padding: 26px 30px;
}
main {
gap: 30px;
padding-top: 55px;
}
h1 {
font-size: 78px;
}
.transfer-card {
padding: 24px;
}
.private-label {
display: none;
}
}
@media (max-width: 680px) {
.shell {
padding: 22px;
}
header {
gap: 12px;
}
.wordmark {
font-size: 26px;
}
.connection {
font-size: 10px;
max-width: 145px;
}
main {
display: flex;
flex-direction: column;
gap: 32px;
padding: 48px 0 32px;
}
.intro {
width: 100%;
}
.eyebrow {
font-size: 9px;
margin-bottom: 18px;
}
h1 {
font-size: 76px;
letter-spacing: -4px;
}
.lede {
font-size: 14px;
}
.parcel-stage {
position: absolute;
right: 12px;
top: 170px;
width: 160px;
height: 180px;
opacity: 0.65;
pointer-events: none;
}
.parcel {
width: 170px;
}
.orbit {
width: 145px;
height: 40px;
bottom: 30px;
}
.orbit-two {
width: 160px;
}
.stage-caption {
display: none;
}
.intro .lede {
position: relative;
max-width: 75%;
}
.transfer-card {
width: 100%;
border-radius: 24px;
}
.journey {
gap: 18px;
grid-template-columns: 1fr;
}
.journey > div {
gap: 14px;
}
.journey p br {
display: none;
}
.journey p strong {
margin-right: 8px;
}
footer {
flex-direction: column;
gap: 8px;
}
.card-top .private-label {
display: block;
}
h2 {
font-size: 32px;
}
}
@media (max-width: 370px) {
.parcel-stage {
opacity: 0.25;
}
.connection {
max-width: 100px;
}
.shell {
padding: 17px;
}
.card-top .private-label {
display: none;
}
}
.brand-icon svg {
width: 29px;
height: 29px;
}
@@ -0,0 +1,39 @@
package meghdad.pakkit.apk
import org.json.JSONObject
data class Apk(
val label: String,
val packageName: String,
val version: String,
val minSdk: Int,
val bytes: Long,
val sha256: String,
val abis: Set<String>,
val wear: Boolean,
) {
fun json() =
JSONObject()
.put("label", label)
.put("package", packageName)
.put("version", version)
.put("minSdk", minSdk)
.put("bytes", bytes)
.put("sha256", sha256)
.put("abis", abis.joinToString(","))
.put("wear", wear)
companion object {
fun from(j: JSONObject) =
Apk(
j.getString("label"),
j.getString("package"),
j.getString("version"),
j.getInt("minSdk"),
j.getLong("bytes"),
j.getString("sha256"),
j.getString("abis").split(',').filter { it.isNotBlank() }.toSet(),
j.getBoolean("wear"),
)
}
}
@@ -1,16 +1,26 @@
package meghdad.pakkit.core package meghdad.pakkit.apk
import java.io.InputStream import java.io.InputStream
import java.io.OutputStream import java.io.OutputStream
import java.security.MessageDigest import java.security.MessageDigest
object TransferRules { object ApkRules {
const val MAX_BYTES = 50L * 1024 * 1024 const val MAX_BYTES = 50L * 1024 * 1024
const val TTL_MS = 24L * 60 * 60 * 1000 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 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 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(input: InputStream, output: OutputStream, max: Long = MAX_BYTES): Pair<Long, String> { fun compatibleAbis(packageAbis: Set<String>, deviceAbis: Set<String>) =
packageAbis.isEmpty() || packageAbis.any { it in deviceAbis }
fun copyBounded(
input: InputStream,
output: OutputStream? = null,
max: Long = MAX_BYTES,
): Pair<Long, String> {
val hash = MessageDigest.getInstance("SHA-256") val hash = MessageDigest.getInstance("SHA-256")
val buffer = ByteArray(64 * 1024) val buffer = ByteArray(64 * 1024)
var total = 0L var total = 0L
@@ -19,9 +29,9 @@ object TransferRules {
if (count < 0) break if (count < 0) break
if (count == 0) continue if (count == 0) continue
total += count total += count
require(total <= max) { "Choose an APK smaller than 50 MB." } require(total <= max) { "Choose an APK up to 50 MiB." }
hash.update(buffer, 0, count) hash.update(buffer, 0, count)
output.write(buffer, 0, count) output?.write(buffer, 0, count)
} }
require(total > 0) { "This file is empty." } require(total > 0) { "This file is empty." }
return total to hash.digest().joinToString("") { "%02x".format(it) } return total to hash.digest().joinToString("") { "%02x".format(it) }
@@ -0,0 +1,108 @@
package meghdad.pakkit.apk
import android.content.Context
import android.content.pm.PackageManager
import android.os.StatFs
import java.io.File
import java.util.zip.ZipFile
object PackageInspector {
@Suppress("DEPRECATION")
fun inspect(context: Context, file: File, hash: String): Apk {
require(file.length() in 1..ApkRules.MAX_BYTES) { "Choose an APK up to 50 MiB." }
val abis = mutableSetOf<String>()
ZipFile(file).use { zip ->
require(zip.getEntry("AndroidManifest.xml") != null) {
"This file is not an Android APK."
}
require(zip.size() < 100_000) { "This archive contains too many entries." }
var expanded = 0L
zip.entries().asSequence().forEach { entry ->
require(entry.size >= 0 && entry.size <= 128L * 1024 * 1024) {
"This APK contains an unusually large archive entry."
}
expanded += entry.size
require(expanded <= 200L * 1024 * 1024) {
"This APK expands beyond Pakkit’s package limit."
}
if (entry.name == "AndroidManifest.xml")
require(entry.size <= 2 * 1024 * 1024) { "This APK manifest is too large." }
val parts = entry.name.split('/')
if (parts.size >= 3 && parts[0] == "lib" && entry.name.endsWith(".so"))
abis += parts[1]
}
}
val info =
context.packageManager.getPackageArchiveInfo(
file.path,
PackageManager.GET_SIGNING_CERTIFICATES or PackageManager.GET_CONFIGURATIONS,
)
?: error(
"Android could not read this APK. Split packages and bundles are not supported.",
)
require(info.splitNames.isNullOrEmpty()) {
"Choose a complete, single APK rather than a split package."
}
require(info.signingInfo?.apkContentsSigners?.isNotEmpty() == true) {
"This APK has no readable signing certificate."
}
require(info.packageName != context.packageName) { "Update Pakkit through Google Play." }
val app = requireNotNull(info.applicationInfo)
app.sourceDir = file.path
app.publicSourceDir = file.path
context.packageManager
.getResourcesForApplication(app)
.assets
.openXmlResourceParser("AndroidManifest.xml")
.use { xml ->
while (xml.next() != org.xmlpull.v1.XmlPullParser.END_DOCUMENT) {
if (xml.eventType != org.xmlpull.v1.XmlPullParser.START_TAG) continue
require(xml.name != "uses-split") {
"Choose a complete APK; this file requires other splits."
}
if (xml.name == "manifest")
require(xml.getAttributeValue(null, "split").isNullOrEmpty()) {
"This is a split APK. Choose a complete APK."
}
if (xml.name == "application")
require(
!xml.getAttributeBooleanValue(
"http://schemas.android.com/apk/res/android",
"isSplitRequired",
false,
),
) {
"This APK requires additional splits."
}
}
}
return Apk(
app.loadLabel(context.packageManager).toString().take(100),
info.packageName,
info.versionName.orEmpty().take(64),
app.minSdkVersion,
file.length(),
hash,
abis,
info.reqFeatures?.any { it.name == PackageManager.FEATURE_WATCH } == true,
)
}
fun checkForWatch(apk: Apk, sdk: Int, abis: Set<String>, free: Long) {
require(apk.minSdk <= sdk) {
"This APK needs Android API ${apk.minSdk}; your watch runs API $sdk."
}
require(ApkRules.compatibleAbis(apk.abis, abis)) {
"This APK was built for a different processor."
}
requireSpace(apk.bytes, free)
}
fun requireSpace(bytes: Long, free: Long) {
require(free > bytes * 3 + 20 * 1024 * 1024) {
"Free more storage on your watch, then try again."
}
}
fun free(context: Context) = StatFs(context.filesDir.path).availableBytes
}
@@ -0,0 +1,46 @@
package meghdad.pakkit.apk
import org.json.JSONObject
/** Durable review/installation state. Network sessions have a separate, in-memory lifetime. */
data class PendingApk(
val id: String,
val created: Long,
val apk: Apk,
val state: InstallState = InstallState.READY,
val detail: String = "Review this app and approve installation on your watch.",
val sessionId: Int? = null,
) {
init {
require(ApkRules.validId(id))
}
fun json(): JSONObject =
JSONObject()
.put("id", id)
.put("created", created)
.put("apk", apk.json())
.put("state", state.wireValue)
.put("detail", detail)
.apply { sessionId?.let { put("session", it) } }
companion object {
fun from(json: JSONObject) =
PendingApk(
id = json.getString("id"),
created = json.getLong("created"),
apk = Apk.from(json.getJSONObject("apk")),
state = InstallState.entries.first { it.wireValue == json.getString("state") },
detail = json.optString("detail"),
sessionId = json.optInt("session", -1).takeIf { it >= 0 },
)
}
}
enum class InstallState(val wireValue: String) {
READY("ready"),
INSTALLING("installing"),
CONFIRM("confirm"),
INSTALLED("installed"),
FAILED("failed"),
}
@@ -0,0 +1,72 @@
package meghdad.pakkit.data
import android.content.Context
import android.content.SharedPreferences
import java.io.File
import meghdad.pakkit.apk.ApkRules
import meghdad.pakkit.apk.InstallState
import meghdad.pakkit.apk.PendingApk
import org.json.JSONObject
/** One private package and its review, stored atomically under a stable on-disk schema. */
class PackageStore(context: Context) {
val preferences: SharedPreferences =
context.getSharedPreferences("pakkit", Context.MODE_PRIVATE)
private val directory = File(context.filesDir, "packages").apply { mkdirs() }
fun file(id: String): File {
require(ApkRules.validId(id))
return File(directory, "$id.apk")
}
fun pending(): PendingApk? =
preferences.getString(PENDING_KEY, null)?.let { value ->
runCatching { PendingApk.from(JSONObject(value)) }.getOrNull()
}
fun stage(apk: PendingApk) =
synchronized(lock) {
check(pending() == null) { "Finish or dismiss the current app on your watch first." }
persist(apk)
}
fun update(id: String, state: InstallState, detail: String, sessionId: Int? = null): Boolean =
synchronized(lock) {
val current = pending()?.takeIf { it.id == id } ?: return false
persist(
current.copy(
state = state,
detail = detail,
sessionId = sessionId ?: current.sessionId,
),
)
true
}
fun dismiss(id: String) =
synchronized(lock) {
if (pending()?.id != id) return@synchronized
file(id).delete()
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()) =
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()
}
}
private fun persist(apk: PendingApk) {
check(preferences.edit().putString(PENDING_KEY, apk.json().toString()).commit())
}
companion object {
const val PENDING_KEY = "incoming"
private val lock = Any()
}
}
@@ -0,0 +1,98 @@
package meghdad.pakkit.install
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageInstaller
import android.net.Uri
import android.os.Build
import android.provider.Settings
import meghdad.pakkit.apk.ApkRules
import meghdad.pakkit.apk.InstallState
import meghdad.pakkit.apk.PackageInspector
import meghdad.pakkit.apk.PendingApk
import meghdad.pakkit.data.PackageStore
/** Called only after the watch's explicit Install action, on a worker thread. */
class ApkInstaller(private val context: Context) {
private val store = PackageStore(context)
fun install(apk: PendingApk) {
val installer = context.packageManager.packageInstaller
var sessionId: Int? = null
try {
PendingApproval.clear()
context
.getSystemService(NotificationManager::class.java)
.cancel(InstallReceiver.NOTIFICATION)
check(context.packageManager.canRequestPackageInstalls()) {
"Allow Pakkit to request installs first."
}
require(ApkRules.fresh(apk.created, System.currentTimeMillis())) {
"This APK expired. Upload it again."
}
val file = store.file(apk.id)
val digest = file.inputStream().use { ApkRules.copyBounded(it).second }
require(digest == apk.apk.sha256) { "This APK changed. Upload it again." }
val inspected = PackageInspector.inspect(context, file, digest)
PackageInspector.checkForWatch(
inspected,
Build.VERSION.SDK_INT,
Build.SUPPORTED_ABIS.toSet(),
PackageInspector.free(context),
)
apk.sessionId?.let { runCatching { installer.abandonSession(it) } }
val params =
PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL)
.apply {
setAppPackageName(inspected.packageName)
setSize(file.length())
setRequireUserAction(PackageInstaller.SessionParams.USER_ACTION_REQUIRED)
if (Build.VERSION.SDK_INT >= 33)
setPackageSource(PackageInstaller.PACKAGE_SOURCE_LOCAL_FILE)
}
sessionId = installer.createSession(params)
check(
store.update(
apk.id,
InstallState.INSTALLING,
"Waiting for the watch’s system installer.",
sessionId,
),
) {
"This package review is no longer available."
}
installer.openSession(sessionId).use { session ->
session.openWrite("base.apk", 0, file.length()).use { output ->
file.inputStream().use { it.copyTo(output, 64 * 1024) }
session.fsync(output)
}
val callback = Intent(context, InstallReceiver::class.java).putExtra("job", apk.id)
val pending =
PendingIntent.getBroadcast(
context,
sessionId,
callback,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE,
)
session.commit(pending.intentSender)
}
} catch (error: Exception) {
sessionId?.let { runCatching { installer.abandonSession(it) } }
store.update(
apk.id,
InstallState.FAILED,
error.message ?: "Could not open the system installer. Use Google Play.",
)
}
}
companion object {
fun settings(context: Context) =
Intent(
Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES,
Uri.parse("package:${context.packageName}"),
)
}
}
@@ -0,0 +1,125 @@
package meghdad.pakkit.install
import android.Manifest
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.pm.PackageInstaller
import android.content.pm.PackageManager
import android.os.Build
import meghdad.pakkit.R
import meghdad.pakkit.apk.InstallState
import meghdad.pakkit.data.PackageStore
import meghdad.pakkit.ui.WatchActivity
import meghdad.pakkit.ui.WatchDesign
/** Explicit mutable installer callback, kept non-exported and matched to the active session. */
class InstallReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val store = PackageStore(context)
val apk = store.pending() ?: return
if (
apk.sessionId == null ||
intent.getStringExtra("job") != apk.id ||
intent.getIntExtra(PackageInstaller.EXTRA_SESSION_ID, -1) != apk.sessionId
)
return
if (apk.state !in setOf(InstallState.INSTALLING, InstallState.CONFIRM)) return
val manager = context.getSystemService(NotificationManager::class.java)
when (
val status =
intent.getIntExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE)
) {
PackageInstaller.STATUS_PENDING_USER_ACTION -> {
@Suppress("DEPRECATION")
val confirmation = intent.getParcelableExtra<Intent>(Intent.EXTRA_INTENT)
if (confirmation == null) {
store.update(
apk.id,
InstallState.FAILED,
"The system did not provide an approval screen.",
)
return
}
PendingApproval.id = apk.id
PendingApproval.intent = confirmation
store.update(
apk.id,
InstallState.CONFIRM,
"Continue the system approval on your watch.",
)
manager.createNotificationChannel(
NotificationChannel(
"installation",
"Installation approval",
NotificationManager.IMPORTANCE_DEFAULT,
),
)
if (
Build.VERSION.SDK_INT < 33 ||
context.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) ==
PackageManager.PERMISSION_GRANTED
) {
val open =
Intent(context, WatchActivity::class.java)
.putExtra("approval", confirmation)
.putExtra("job", apk.id)
val pending =
PendingIntent.getActivity(
context,
apk.sessionId,
open,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
manager.notify(
NOTIFICATION,
Notification.Builder(context, "installation")
.setSmallIcon(R.drawable.pakkit_mark)
.setColor(WatchDesign.PURPLE)
.setContentTitle("Approve installation")
.setContentText("Open Pakkit to continue on your watch.")
.setContentIntent(pending)
.setAutoCancel(true)
.build(),
)
}
}
PackageInstaller.STATUS_SUCCESS -> {
PendingApproval.clear()
store.update(apk.id, InstallState.INSTALLED, "Installed on your watch.")
store.file(apk.id).delete()
manager.cancel(NOTIFICATION)
}
else -> {
PendingApproval.clear()
val detail =
when (status) {
PackageInstaller.STATUS_FAILURE_ABORTED ->
"Installation was cancelled. You can try again."
PackageInstaller.STATUS_FAILURE_BLOCKED ->
"The watch’s security policy blocked this installation. Use Google Play or contact the app developer."
PackageInstaller.STATUS_FAILURE_CONFLICT ->
"This APK conflicts with an installed app or its signature. Ask the developer for a compatible version."
PackageInstaller.STATUS_FAILURE_INCOMPATIBLE ->
"This APK is not compatible with your watch."
PackageInstaller.STATUS_FAILURE_INVALID ->
"The system rejected this APK’s format or signature."
PackageInstaller.STATUS_FAILURE_STORAGE ->
"Your watch needs more free storage."
else ->
"The system could not finish installing. Try again or use Google Play."
}
store.update(apk.id, InstallState.FAILED, detail)
manager.cancel(NOTIFICATION)
}
}
}
companion object {
const val NOTIFICATION = 42
}
}
@@ -0,0 +1,14 @@
package meghdad.pakkit.install
import android.content.Intent
/** Ephemeral system intent; interrupted approval is recovered through the notification or retry. */
object PendingApproval {
var id: String? = null
var intent: Intent? = null
fun clear() {
id = null
intent = null
}
}
@@ -1,11 +1,13 @@
package meghdad.pakkit.core package meghdad.pakkit.transfer
import java.io.InputStream import java.io.InputStream
import java.security.MessageDigest import java.security.MessageDigest
import meghdad.pakkit.apk.ApkRules
/** Deliberately small HTTP/1.1 subset: one request per socket, no pipelining or chunked uploads. */ /** Deliberately small HTTP/1.1 subset: one request per socket, no pipelining or chunked uploads. */
object HttpProtocol { object HttpProtocol {
data class Request(val method: String, val path: String, val headers: Map<String, String>) data class Request(val method: String, val path: String, val headers: Map<String, String>)
fun read(input: InputStream): Request { fun read(input: InputStream): Request {
var total = 0 var total = 0
fun line(): String { fun line(): String {
@@ -13,7 +15,11 @@ object HttpProtocol {
while (true) { while (true) {
val b = input.read() val b = input.read()
require(b >= 0 && ++total <= 8192) { "Invalid request headers" } require(b >= 0 && ++total <= 8192) { "Invalid request headers" }
if (b == 13) { require(input.read() == 10); total++; return out.toString() } if (b == 13) {
require(input.read() == 10)
total++
return out.toString()
}
require(b in 32..126 && out.length < 4096) { "Invalid request headers" } require(b in 32..126 && out.length < 4096) { "Invalid request headers" }
out.append(b.toChar()) out.append(b.toChar())
} }
@@ -34,12 +40,19 @@ object HttpProtocol {
require("transfer-encoding" !in headers && "expect" !in headers) require("transfer-encoding" !in headers && "expect" !in headers)
return Request(first[0], first[1], headers) 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)) fun authorized(header: String?, token: String): Boolean =
MessageDigest.isEqual(
(header ?: "").toByteArray(Charsets.UTF_8),
"Bearer $token".toByteArray(Charsets.UTF_8),
)
fun uploadLength(headers: Map<String, String>): Long { fun uploadLength(headers: Map<String, String>): Long {
require(headers["content-type"] == "application/octet-stream") { "Send a complete APK" } require(headers["content-type"] == "application/octet-stream") { "Send a complete APK" }
val size = headers["content-length"]?.toLongOrNull() ?: error("Content length required") val raw = headers["content-length"] ?: error("Content length required")
require(size in 1..TransferRules.MAX_BYTES) { "Choose an APK up to 50 MiB" } 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" }
return size return size
} }
} }
@@ -0,0 +1,261 @@
package meghdad.pakkit.transfer
import android.content.Context
import android.os.Build
import android.os.SystemClock
import android.util.Base64
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.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
import java.util.concurrent.RejectedExecutionException
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.PackageInspector
import meghdad.pakkit.apk.PendingApk
import meghdad.pakkit.data.PackageStore
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 owner: Any,
) : Closeable {
private val store = PackageStore(context)
private val listener =
ServerSocket().apply {
reuseAddress = true
bind(InetSocketAddress(address, 0), 4)
}
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"
fun start() {
Thread(
{
while (!closed.get()) {
val socket =
try {
listener.accept()
} catch (_: IOException) {
break
}
socket.soTimeout = 15_000
sockets.add(socket)
if (closed.get()) {
sockets.remove(socket)
socket.close()
break
}
try {
workers.execute {
try {
socket.use { handle(it) }
} finally {
sockets.remove(socket)
}
}
} catch (_: RejectedExecutionException) {
sockets.remove(socket)
socket.close()
}
}
},
"pakkit-http",
)
.start()
}
private fun handle(socket: Socket) {
val response = Response(socket)
try {
val input = BufferedInputStream(socket.getInputStream(), 8192)
val request = HttpProtocol.read(input)
check(!closed.get() && SystemClock.elapsedRealtime() < deadline) {
"The receiving session ended. Start a new one."
}
if (request.headers["host"] != authority) {
response.error(403, "Open the address shown on your watch.")
return
}
if (request.method == "GET" && request.path in ASSETS) {
val asset = ASSETS.getValue(request.path)
response.send(
200,
asset.second,
context.assets.open("web/${asset.first}").use { it.readBytes() },
)
return
}
if (!HttpProtocol.authorized(request.headers["authorization"], token)) {
response.error(403, "Open the private link or scan the QR code on your watch.")
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, "Use Pakkit’s local page.")
else upload(request, input, response)
}
else -> response.error(404, "Not found")
}
} catch (error: Exception) {
if (!response.sent)
runCatching {
response.error(
400,
error.message?.take(180) ?: "Transfer interrupted. Try again.",
)
}
}
}
private fun status(): JSONObject {
val pending = store.pending()
val live = Receiving.state
return JSONObject()
.put("state", pending?.state?.wireValue ?: "waiting")
.put("detail", pending?.detail ?: live.detail)
.put("label", pending?.apk?.label.orEmpty())
.put("received", live.received)
.put("total", live.total)
.put("expiresIn", ((deadline - SystemClock.elapsedRealtime()) / 1000).coerceAtLeast(0))
}
private fun upload(request: HttpProtocol.Request, input: InputStream, response: Response) {
val length = HttpProtocol.uploadLength(request.headers)
if (!uploading.compareAndSet(false, true)) {
response.error(409, "A transfer is already in progress.")
return
}
var partial: File? = null
try {
if (store.pending() != null) {
response.error(409, "Finish or dismiss the current app on your watch first.")
return
}
PackageInspector.requireSpace(length, PackageInspector.free(context))
val id = UUID.randomUUID().toString()
val file = store.file(id)
partial = file
Receiving.update(owner) {
it.copy(detail = "Receiving APK…", total = length, received = 0)
}
val body =
UploadBody(
input,
length,
progress = { received ->
Receiving.update(owner) { it.copy(received = received) }
},
)
val digest = file.outputStream().use { ApkRules.copyBounded(body, it).second }
Receiving.update(owner) { it.copy(detail = "Checking APK…") }
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) {
"The receiving session ended. Try again."
}
store.stage(PendingApk(id, System.currentTimeMillis(), apk))
partial = null
Receiving.update(owner) { it.copy(detail = "Ready to install") }
response.json(200, JSONObject().put("label", apk.label).put("state", "ready"))
} finally {
partial?.delete()
uploading.set(false)
Receiving.update(owner) {
it.copy(
received = 0,
total = 0,
detail =
if (store.pending() == null) "Ready to receive" else "Ready to install",
)
}
}
}
override fun close() {
if (!closed.compareAndSet(false, true)) return
try {
listener.close()
} finally {
sockets.forEach { runCatching { it.close() } }
workers.shutdownNow()
}
}
private class Response(private val socket: Socket) {
var sent = false
private set
fun error(code: Int, message: String) = json(code, JSONObject().put("error", message))
fun json(code: Int, value: JSONObject) =
send(
code,
"application/json; charset=utf-8",
value.toString().toByteArray(Charsets.UTF_8),
)
fun send(code: Int, type: String, bytes: ByteArray) {
sent = true
val reason =
when (code) {
200 -> "OK"
400 -> "Bad Request"
403 -> "Forbidden"
404 -> "Not Found"
409 -> "Conflict"
else -> "Error"
}
val headers =
"HTTP/1.1 $code $reason\r\nContent-Type: $type\r\nContent-Length: ${bytes.size}\r\n" +
"Connection: close\r\nCache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\nReferrer-Policy: no-referrer\r\n" +
"Content-Security-Policy: default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; " +
"connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'\r\n\r\n"
socket.getOutputStream().apply {
write(headers.toByteArray(Charsets.US_ASCII))
write(bytes)
flush()
}
}
}
companion object {
private val ASSETS =
mapOf(
"/" to ("index.html" to "text/html; charset=utf-8"),
"/style.css" to ("style.css" to "text/css; charset=utf-8"),
"/app.js" to ("app.js" to "text/javascript; charset=utf-8"),
)
}
}
@@ -0,0 +1,179 @@
package meghdad.pakkit.transfer
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Intent
import android.content.pm.ServiceInfo
import android.net.ConnectivityManager
import android.net.LinkProperties
import android.net.Network
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.Inet4Address
import meghdad.pakkit.R
import meghdad.pakkit.ui.WatchActivity
/** Owns the user-started session and releases all network/power resources on every exit path. */
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 registered = false
private var ended = false
private var deadline = 0L
private var wake: PowerManager.WakeLock? = null
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 address changed. Start a new session.")
}
}
}
override fun onLost(network: Network) {
main.post {
if (network == this@ReceiveService.network)
finish("Wi-Fi disconnected. Start a new session.")
}
}
override fun onUnavailable() {
main.post { finish("Connect your watch to Wi-Fi, then try again.") }
}
}
override fun onBind(intent: Intent?) = null
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent?.action == STOP) {
finish("Session ended")
return START_NOT_STICKY
}
if (registered || ended) return START_NOT_STICKY
val manager = getSystemService(NotificationManager::class.java)
manager.createNotificationChannel(
NotificationChannel(
"receive",
"Receiving sessions",
NotificationManager.IMPORTANCE_LOW,
),
)
val open =
PendingIntent.getActivity(
this,
0,
Intent(this, WatchActivity::class.java),
PendingIntent.FLAG_IMMUTABLE,
)
val stop =
PendingIntent.getService(
this,
1,
Intent(this, ReceiveService::class.java).setAction(STOP),
PendingIntent.FLAG_IMMUTABLE,
)
val notification =
Notification.Builder(this, "receive")
.setSmallIcon(R.drawable.pakkit_mark)
.setContentTitle("Pakkit is ready to receive")
.setContentText("Private Wi-Fi session · ends in 10 minutes")
.setContentIntent(open)
.setOngoing(true)
.addAction(Notification.Action.Builder(null, "End session", stop).build())
.build()
startForeground(
NOTIFICATION,
notification,
ServiceInfo.FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE,
)
Receiving.begin(this)
deadline = SystemClock.elapsedRealtime() + DURATION_MS
main.postDelayed({ finish("Session expired. Start a new session.") }, DURATION_MS)
try {
registered = true
connectivity.requestNetwork(
NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.build(),
callback,
25_000,
)
} catch (_: Exception) {
finish("Wi-Fi is unavailable. Check watch settings.")
}
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")
this.network = network
this.address = address
val listener = LocalHttpServer(applicationContext, address, deadline, this)
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("Could not open local Wi-Fi. Check the network and try again.")
}
}
private fun finish(message: String) {
if (ended) return
ended = true
release(message)
stopForeground(STOP_FOREGROUND_REMOVE)
stopSelf()
}
private fun release(message: String) {
main.removeCallbacksAndMessages(null)
server?.close()
server = null
if (registered) runCatching { connectivity.unregisterNetworkCallback(callback) }
registered = false
wake?.let { if (it.isHeld) it.release() }
wake = null
Receiving.end(this, message)
}
override fun onDestroy() {
ended = true
release("Session ended")
super.onDestroy()
}
companion object {
const val DURATION_MS = 10 * 60 * 1000L
const val STOP = "stop"
private const val NOTIFICATION = 81
}
}
@@ -0,0 +1,59 @@
package meghdad.pakkit.transfer
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.
*/
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 received: Long = 0,
val total: Long = 0,
)
@Volatile
var state = State()
private set
private var owner: Any? = null
private val listeners = CopyOnWriteArraySet<() -> Unit>()
private val main = Handler(Looper.getMainLooper())
private val notify = Runnable { listeners.forEach { it() } }
fun observe(listener: () -> Unit) {
listeners.add(listener)
}
fun removeObserver(listener: () -> Unit) {
listeners.remove(listener)
}
@Synchronized
fun begin(owner: Any) {
this.owner = owner
publish(State(active = true, detail = "Connecting to Wi-Fi…"))
}
@Synchronized
fun update(owner: Any, change: (State) -> State) {
if (this.owner === owner) publish(change(state))
}
@Synchronized
fun end(owner: Any, detail: String) {
if (this.owner !== owner) return
this.owner = null
publish(State(detail = detail))
}
private fun publish(state: State) {
this.state = state
main.removeCallbacks(notify)
main.post(notify)
}
}
@@ -0,0 +1,34 @@
package meghdad.pakkit.transfer
import java.io.InputStream
/** Exact-length stream: truncation is an error, and extra bytes cannot become another request. */
internal class UploadBody(
private val input: InputStream,
private val length: Long,
private val progress: (Long) -> Unit,
private val clock: () -> Long = System::nanoTime,
) : InputStream() {
private var received = 0L
private var lastUpdate = clock()
override fun read(): Int {
val one = ByteArray(1)
return if (read(one, 0, 1) == -1) -1 else one[0].toInt() and 255
}
override fun read(bytes: ByteArray, offset: Int, count: Int): Int {
require(offset >= 0 && count >= 0 && offset <= bytes.size - count)
if (count == 0) return 0
if (received == length) return -1
val read = input.read(bytes, offset, minOf(count.toLong(), length - received).toInt())
require(read > 0) { "Transfer interrupted. Choose the file again." }
received += read
val now = clock()
if (now - lastUpdate >= 250_000_000 || received == length) {
lastUpdate = now
progress(received)
}
return read
}
}
@@ -0,0 +1,66 @@
package meghdad.pakkit.ui
import android.graphics.Canvas
import android.graphics.ColorFilter
import android.graphics.Paint
import android.graphics.Path
import android.graphics.PixelFormat
import android.graphics.drawable.Drawable
enum class Glyph {
CHECK,
ALERT,
}
/** One stroke family for navigation, metadata and status. No font-dependent symbol icons. */
class GlyphDrawable(private val glyph: Glyph, private val color: Int) : Drawable() {
override fun getIntrinsicWidth() = 24
override fun getIntrinsicHeight() = 24
private val paint =
Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.STROKE
strokeWidth = 1.8f
strokeCap = Paint.Cap.ROUND
strokeJoin = Paint.Join.ROUND
}
private val path = Path()
override fun draw(c: Canvas) {
val save = c.save()
c.translate(bounds.left.toFloat(), bounds.top.toFloat())
c.scale(bounds.width() / 24f, bounds.height() / 24f)
paint.color = color
path.rewind()
when (glyph) {
Glyph.CHECK -> {
path.moveTo(5f, 12f)
path.lineTo(10f, 17f)
path.lineTo(19f, 7f)
}
Glyph.ALERT -> {
path.moveTo(12f, 3f)
path.lineTo(22f, 20f)
path.lineTo(2f, 20f)
path.close()
path.moveTo(12f, 9f)
path.lineTo(12f, 13f)
path.moveTo(12f, 16f)
path.lineTo(12f, 16.2f)
}
}
c.drawPath(path, paint)
c.restoreToCount(save)
}
override fun setAlpha(alpha: Int) {
paint.alpha = alpha
}
override fun setColorFilter(filter: ColorFilter?) {
paint.colorFilter = filter
}
@Deprecated("Drawable API") override fun getOpacity() = PixelFormat.TRANSLUCENT
}
@@ -0,0 +1,69 @@
package meghdad.pakkit.ui
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.view.MotionEvent
import android.widget.ScrollView
/**
* Scroll position indicator follows the circular bezel and redraws only in response to scrolling.
*/
class RoundScrollView(c: Context) : ScrollView(c) {
private val track =
Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.STROKE
strokeWidth = WatchDesign.dp(c, 2).toFloat()
strokeCap = Paint.Cap.ROUND
}
init {
isVerticalScrollBarEnabled = false
isFillViewport = true
clipToPadding = false
}
override fun onDrawForeground(canvas: Canvas) {
super.onDrawForeground(canvas)
val range = computeVerticalScrollRange().toFloat()
val extent = height.toFloat()
if (range <= extent + 1) return
val inset = WatchDesign.dp(context, 4).toFloat()
track.color = 0x3356557F
canvas.drawArc(
inset,
scrollY + inset,
width - inset,
scrollY + height - inset,
-32f,
64f,
false,
track,
)
val sweep = (64f * extent / range).coerceAtLeast(12f)
val position = (scrollY / (range - extent)).coerceIn(0f, 1f)
track.color = 0xFFBAA6FF.toInt()
canvas.drawArc(
inset,
scrollY + inset,
width - inset,
scrollY + height - inset,
-32f + (64f - sweep) * position,
sweep,
false,
track,
)
}
override fun onGenericMotionEvent(event: MotionEvent): Boolean {
if (event.action == MotionEvent.ACTION_SCROLL) {
scrollBy(
0,
(-event.getAxisValue(MotionEvent.AXIS_SCROLL) * WatchDesign.dp(context, 42))
.toInt(),
)
return true
}
return super.onGenericMotionEvent(event)
}
}
@@ -0,0 +1,574 @@
package meghdad.pakkit.ui
import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.ProgressBar
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.data.PackageStore
import meghdad.pakkit.install.ApkInstaller
import meghdad.pakkit.install.PendingApproval
import meghdad.pakkit.transfer.ReceiveService
import meghdad.pakkit.transfer.Receiving
class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeListener {
private lateinit var store: PackageStore
private lateinit var column: LinearLayout
private lateinit var scroll: RoundScrollView
private val colors = WatchColors
private val io = Executors.newSingleThreadExecutor()
private val sessionObserver: () -> Unit = { refresh() }
private var busy = false
private var error: String? = null
private var renderedState = ""
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)
refresh()
savedInstanceState?.getInt("scroll")?.let { y -> scroll.post { scroll.scrollTo(0, y) } }
}
override fun onSaveInstanceState(outState: Bundle) {
outState.putInt("scroll", scroll.scrollY)
super.onSaveInstanceState(outState)
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
acceptIntent(intent)
refresh()
}
private fun acceptIntent(intent: Intent) {
val job = store.pending()
@Suppress("DEPRECATION") val approval = intent.getParcelableExtra<Intent>("approval")
if (
approval != null &&
job != null &&
job.id == intent.getStringExtra("job") &&
job.state == InstallState.CONFIRM
) {
PendingApproval.intent = approval
PendingApproval.id = job.id
}
}
override fun onResume() {
super.onResume()
store.preferences.registerOnSharedPreferenceChangeListener(this)
Receiving.observe(sessionObserver)
refresh()
}
override fun onPause() {
Receiving.removeObserver(sessionObserver)
store.preferences.unregisterOnSharedPreferenceChangeListener(this)
super.onPause()
}
override fun onDestroy() {
io.shutdown()
super.onDestroy()
}
override fun onSharedPreferenceChanged(prefs: SharedPreferences?, key: String?) {
if (key == PackageStore.PENDING_KEY || key == null) runOnUiThread { refresh() }
}
private fun dp(n: Int) = WatchDesign.dp(this, n)
private fun line(
value: String,
size: Float = 14f,
color: Int = colors.text,
bold: Boolean = false,
) =
WatchDesign.text(this, value, size, color, bold).apply {
gravity = Gravity.CENTER
breakStrategy = android.graphics.text.LineBreaker.BREAK_STRATEGY_BALANCED
}
private fun add(v: View, top: Int = 0) {
column.addView(
v,
LinearLayout.LayoutParams(-1, v.layoutParams?.height ?: -2).apply {
topMargin = dp(top)
},
)
}
private fun button(label: String, primary: Boolean = true, action: () -> Unit) {
add(
WatchDesign.button(this, label, primary, action).apply {
textSize = 15f
minHeight = dp(48)
isEnabled = !busy
},
10,
)
}
private fun parcel(size: Int = 48) {
add(
ImageView(this).apply {
setImageResource(R.drawable.pakkit_icon)
scaleType = ImageView.ScaleType.FIT_CENTER
layoutParams = LinearLayout.LayoutParams(-1, dp(size))
importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
},
9,
)
}
private fun statusIcon(glyph: Glyph, success: Boolean) {
add(
FrameLayout(this).apply {
layoutParams = LinearLayout.LayoutParams(-1, dp(56))
addView(
ImageView(this@WatchActivity).apply {
setImageDrawable(
GlyphDrawable(glyph, if (success) colors.mint else colors.error),
)
setPadding(dp(12), dp(12), dp(12), dp(12))
background =
WatchDesign.shape(
if (success) colors.mintSoft else colors.errorSoft,
dp(24).toFloat(),
)
scaleType = ImageView.ScaleType.FIT_CENTER
importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
},
FrameLayout.LayoutParams(dp(48), dp(48), Gravity.CENTER),
)
},
8,
)
}
private fun badge(value: String, positive: Boolean = false) {
val text = WatchDesign.badge(this, value, positive).apply { gravity = Gravity.CENTER }
column.addView(
text,
LinearLayout.LayoutParams(-2, -2).apply {
gravity = Gravity.CENTER_HORIZONTAL
topMargin = dp(10)
},
)
}
fun refresh() {
if (isDestroyed || isFinishing) return
val job = store.pending()
val live = Receiving.state
val stateKey =
job?.let { "${it.id}:${it.state}" }
?: when {
live.total > 0 -> "uploading"
live.url != null -> "receiving"
live.active -> "connecting"
else -> "home"
}
val y = if (::scroll.isInitialized && stateKey == renderedState) scroll.scrollY else 0
renderedState = stateKey
scroll = RoundScrollView(this).apply { setBackgroundColor(colors.canvas) }
val width = resources.configuration.screenWidthDp
val side = (width * .15f).roundToInt().coerceAtLeast(26)
column =
WatchDesign.column(this).apply {
gravity = Gravity.CENTER_HORIZONTAL
setPadding(
dp(side),
dp(12),
dp(side),
dp((width * .24f).roundToInt().coerceAtLeast(44)),
)
}
scroll.addView(column)
add(
TextClock(this).apply {
format12Hour = "h:mm"
format24Hour = "HH:mm"
gravity = Gravity.CENTER
textSize = 12f
setTextColor(colors.secondary)
importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
},
)
if (job == null) home()
else {
incoming(job)
if (Receiving.state.url != null)
button("End Wi-Fi session", false) {
stopService(Intent(this, ReceiveService::class.java))
refresh()
}
}
error?.let { add(line(it, 13f, colors.error), 12) }
scroll.isFocusable = true
scroll.isFocusableInTouchMode = true
setContentView(scroll)
scroll.requestFocus()
scroll.post { scroll.scrollTo(0, y) }
}
private fun home() {
val url = Receiving.state.url
if (url == null) {
parcel(54)
add(line("Pakkit", 25f, bold = true), 4)
add(line(getString(R.string.brand_tagline), 12f, colors.secondary), 5)
}
if (url != null) {
val received = Receiving.state.received
val total = Receiving.state.total
if (total > 0) {
add(
line(
"${(received * 100 / total).coerceAtMost(100)}% received",
21f,
bold = true,
),
12,
)
add(
ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal).apply {
max = 100
progress = (received * 100 / total).toInt()
progressTintList = android.content.res.ColorStateList.valueOf(colors.mint)
},
12,
)
add(line("Keep your browser open.", 12f, colors.secondary), 8)
} else {
if (qrUrl != url || qrBitmap == null) {
val matrix =
com.google.zxing.qrcode
.QRCodeWriter()
.encode(
url,
com.google.zxing.BarcodeFormat.QR_CODE,
420,
420,
mapOf(com.google.zxing.EncodeHintType.MARGIN to 3),
)
val bitmap =
android.graphics.Bitmap.createBitmap(
420,
420,
android.graphics.Bitmap.Config.RGB_565,
)
for (y in 0 until 420) for (x in 0 until 420) bitmap.setPixel(
x,
y,
if (matrix[x, y]) Color.BLACK else Color.WHITE,
)
qrUrl = url
qrBitmap = bitmap
}
add(
ImageView(this).apply {
setImageBitmap(qrBitmap)
scaleType = ImageView.ScaleType.FIT_CENTER
layoutParams =
LinearLayout.LayoutParams(
-1,
dp(
(resources.configuration.screenWidthDp * .6f)
.roundToInt()
.coerceAtMost(138),
),
)
contentDescription =
"QR code for your private receiving link. The full link is below."
},
14,
)
add(line("Scan to send", 18f, bold = true), 12)
badge("Private Wi-Fi session", positive = true)
add(
line(
"Use the same Wi-Fi. Session ends automatically in 10 minutes.",
12f,
colors.secondary,
),
8,
)
add(
line(url, 11f, colors.mint).apply {
textDirection = View.TEXT_DIRECTION_LTR
setTextIsSelectable(true)
},
14,
)
add(
line(
"Local HTTP · use a trusted network. Anyone with this link can send a file; only you can approve installation.",
11f,
colors.secondary,
),
12,
)
}
button("End session", false) {
stopService(Intent(this, ReceiveService::class.java))
refresh()
}
return
}
if (!packageManager.canRequestPackageInstalls()) {
badge("Allow installation")
add(
line(
"Pakkit needs your permission to request installs. You approve every app on your watch.",
13f,
colors.secondary,
),
12,
)
button("Allow installs") { settings() }
add(
line(
"If your watch does not offer this permission, use Google Play. Pakkit cannot bypass its security settings.",
12f,
colors.secondary,
),
12,
)
button("Open Google Play", false) { play() }
} else {
badge("Any device. Any browser.", positive = true)
add(
line(
"Choose an APK in your browser. Review it here before installing.",
14f,
colors.secondary,
),
12,
)
if (!Receiving.state.active)
button("Start receiving") {
error = null
runCatching { startForegroundService(Intent(this, ReceiveService::class.java)) }
.onFailure {
error = "Could not start receiving. Check Wi-Fi and try again."
refresh()
}
}
add(line(Receiving.state.detail, 12f, colors.secondary), 12)
if (Receiving.state.active)
button("Cancel session", false) {
stopService(Intent(this, ReceiveService::class.java))
}
button("Wi-Fi settings", false) {
runCatching {
startActivity(Intent(android.provider.Settings.ACTION_WIFI_SETTINGS))
}
.onFailure {
error = "Open Wi-Fi from your watch’s Settings app."
refresh()
}
}
}
if (
Build.VERSION.SDK_INT >= 33 &&
checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) !=
PackageManager.PERMISSION_GRANTED
) {
button("Enable session alerts", false) {
requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), 52)
}
}
}
private fun incoming(job: PendingApk) {
val apk = job.apk
val state = job.state
when (state) {
InstallState.INSTALLED -> statusIcon(Glyph.CHECK, success = true)
InstallState.FAILED -> statusIcon(Glyph.ALERT, success = false)
else -> parcel(42)
}
when (state) {
InstallState.INSTALLED -> {
add(line("All yours.", 25f, bold = true), 5)
add(line(apk.label, 17f, bold = true), 10)
}
InstallState.FAILED -> {
add(line("A small detour.", 22f, bold = true), 5)
add(line(apk.label, 16f), 10)
}
else -> add(line(apk.label, 21f, bold = true), 5)
}
add(
line(
"${apk.version} · ${"%.1f".format(apk.bytes / 1048576.0)} MiB",
12f,
colors.secondary,
),
7,
)
if (busy) add(line("Preparing installer…", 13f, colors.secondary), 12)
else if (state == InstallState.READY) badge("Ready to install", positive = true)
else add(line(job.detail, 13f, colors.secondary), 12)
when (state) {
InstallState.READY,
InstallState.FAILED -> {
if (!ApkRules.fresh(job.created, System.currentTimeMillis())) {
add(
line(
"This APK expired. Upload it again from your browser.",
13f,
colors.error,
),
12,
)
} else if (store.file(job.id).exists()) {
add(line(apk.packageName, 12f, colors.secondary), 12)
if (!apk.wear)
add(
line(
"Watch support is unverified. The layout may not fit.",
12f,
colors.error,
),
10,
)
add(line("Only install apps you trust.", 13f, colors.secondary), 10)
if (packageManager.canRequestPackageInstalls())
button(
if (state == InstallState.FAILED) "Try installation" else "Install",
) {
install(job)
}
else button("Allow installs") { settings() }
}
button("Dismiss", false) { dismiss(job) }
}
InstallState.CONFIRM -> {
if (PendingApproval.intent != null && PendingApproval.id == job.id)
button("Continue") {
val confirm = PendingApproval.intent ?: return@button
runCatching { startActivity(confirm) }
.onFailure {
error =
"The system approval screen could not open. Try the installation again."
refresh()
}
}
else
add(
line(
"Open the approval notification, or retry if interrupted.",
12f,
colors.secondary,
),
10,
)
button("Retry approval", false) { install(job) }
}
InstallState.INSTALLING -> {
add(
line(
"Follow the system approval. If interrupted, you can retry.",
12f,
colors.secondary,
),
10,
)
button("Retry installation", false) { install(job) }
}
InstallState.INSTALLED -> {
button("Open app") { launch(apk.packageName) }
button("Done", false) {
store.dismiss(job.id)
refresh()
}
}
}
}
private fun settings() {
runCatching { startActivity(ApkInstaller.settings(this)) }
.onFailure {
error =
"This watch does not offer that setting. Install compatible apps through Google Play."
refresh()
}
}
private fun install(job: PendingApk) {
if (busy) return
if (!packageManager.canRequestPackageInstalls()) {
settings()
return
}
busy = true
error = null
refresh()
io.execute {
ApkInstaller(applicationContext).install(job)
runOnUiThread {
busy = false
refresh()
}
}
}
private fun dismiss(job: PendingApk) {
PendingApproval.clear()
store.dismiss(job.id)
refresh()
}
private fun launch(packageName: String) {
runCatching {
if (Build.VERSION.SDK_INT >= 33)
packageManager
.getLaunchIntentSenderForPackage(packageName)
.sendIntent(this, 0, null, null, null)
else
startActivity(
packageManager.getLaunchIntentForPackage(packageName) ?: error("No launcher"),
)
}
.onFailure {
error = "This app has no available watch launcher. Look in your watch’s app list."
refresh()
}
}
private fun play() {
runCatching {
startActivity(
Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q=wear%20os&c=apps")),
)
}
.onFailure {
error = "Open Google Play from your watch’s app list."
refresh()
}
}
}
@@ -0,0 +1,121 @@
package meghdad.pakkit.ui
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.Color
import android.graphics.Typeface
import android.graphics.drawable.GradientDrawable
import android.graphics.drawable.RippleDrawable
import android.widget.Button
import android.widget.LinearLayout
import android.widget.TextView
object WatchColors {
const val canvas = 0xFF090B17.toInt()
const val raised = 0xFF1C2035.toInt()
const val text = 0xFFF4F2FF.toInt()
const val secondary = 0xFFB7B6CE.toInt()
const val border = 0xFF32364E.toInt()
const val accent = 0xFFBAA6FF.toInt()
const val accentSoft = 0xFF30234E.toInt()
const val mint = 0xFF68E9CF.toInt()
const val mintSoft = 0xFF123931.toInt()
const val error = 0xFFFFA7BC.toInt()
const val errorSoft = 0xFF422330.toInt()
}
object WatchDesign {
const val PURPLE = 0xFF7150EF.toInt()
fun dp(c: Context, n: Int) = (n * c.resources.displayMetrics.density).toInt()
fun shape(color: Int, radius: Float = 24f, stroke: Int? = null) =
GradientDrawable().apply {
setColor(color)
cornerRadius = radius
stroke?.let { setStroke(1, it) }
}
fun gradient(colors: IntArray, radius: Float) =
GradientDrawable(GradientDrawable.Orientation.TL_BR, colors).apply { cornerRadius = radius }
fun column(c: Context) = LinearLayout(c).apply { orientation = LinearLayout.VERTICAL }
fun text(
c: Context,
value: String,
size: Float,
color: Int = WatchColors.text,
bold: Boolean = false,
) =
TextView(c).apply {
text = value
textSize = size
setTextColor(color)
typeface =
Typeface.create(
Typeface.create("sans-serif", Typeface.NORMAL),
if (bold) 650 else 400,
false,
)
setLineSpacing(dp(c, 2).toFloat(), 1f)
includeFontPadding = false
}
fun button(c: Context, label: String, primary: Boolean = true, action: () -> Unit) =
Button(c).apply {
val p = WatchColors
text = label
isAllCaps = false
textSize = 15f
minHeight = dp(c, 48)
typeface = Typeface.create(Typeface.create("sans-serif", Typeface.NORMAL), 600, false)
setTextColor(
ColorStateList(
arrayOf(intArrayOf(-android.R.attr.state_enabled), intArrayOf()),
intArrayOf(p.secondary, if (primary) Color.WHITE else p.text),
),
)
val fill =
if (primary)
gradient(
intArrayOf(0xFF7854EE.toInt(), 0xFF6038D6.toInt()),
dp(c, 20).toFloat(),
)
else shape(p.raised, dp(c, 20).toFloat(), p.border)
val states =
android.graphics.drawable.StateListDrawable().apply {
addState(
intArrayOf(-android.R.attr.state_enabled),
shape(p.raised, dp(c, 20).toFloat(), p.border),
)
addState(intArrayOf(), fill)
}
background =
RippleDrawable(
ColorStateList.valueOf(if (primary) 0x33FFFFFF else 0x226F4EF0),
states,
null,
)
stateListAnimator = null
setPadding(dp(c, 18), dp(c, 12), dp(c, 18), dp(c, 12))
setOnClickListener {
performHapticFeedback(android.view.HapticFeedbackConstants.CONFIRM)
action()
}
}
fun badge(c: Context, label: String, positive: Boolean = false) =
text(
c,
label,
12f,
if (positive) WatchColors.mint else WatchColors.accent,
true,
)
.apply {
val p = WatchColors
setPadding(dp(c, 12), dp(c, 7), dp(c, 12), dp(c, 7))
background = shape(if (positive) p.mintSoft else p.accentSoft, dp(c, 16).toFloat())
}
}
+31
View File
@@ -0,0 +1,31 @@
<?xml version="1.0" ?>
<vector xmlns:android="http://schemas.android.com/apk/res/android" xmlns:aapt="http://schemas.android.com/aapt" android:width="108dp" android:height="108dp" android:viewportWidth="108" android:viewportHeight="108">
<path android:pathData="M31,48L54,38L77,48L54,59Z" android:fillColor="#38265F"/>
<path android:pathData="M31,48L54,58L54,81L31,71Z">
<aapt:attr name="android:fillColor">
<gradient android:startX="31" android:startY="48" android:endX="55" android:endY="81" android:startColor="#42DDF1" android:endColor="#8B5CF6" android:type="linear"/>
</aapt:attr>
</path>
<path android:pathData="M54,58L77,48L77,71L54,81Z">
<aapt:attr name="android:fillColor">
<gradient android:startX="54" android:startY="58" android:endX="78" android:endY="76" android:startColor="#7049F2" android:endColor="#D99AE5" android:type="linear"/>
</aapt:attr>
</path>
<path android:pathData="M31,48L54,58L40,65L18,54Z" android:strokeColor="#C8FFF0" android:strokeWidth="0.5">
<aapt:attr name="android:fillColor">
<gradient android:startX="18" android:startY="48" android:endX="54" android:endY="66" android:startColor="#8FF9E1" android:endColor="#7B94FF" android:type="linear"/>
</aapt:attr>
</path>
<path android:pathData="M54,58L77,48L90,54L68,65Z" android:strokeColor="#EAE1FF" android:strokeWidth="0.5">
<aapt:attr name="android:fillColor">
<gradient android:startX="54" android:startY="58" android:endX="90" android:endY="54" android:startColor="#E9D5FF" android:endColor="#AD8AFF" android:type="linear"/>
</aapt:attr>
</path>
<path android:pathData="M31,48L54,38L45,32L23,42Z" android:fillColor="#A79BFF"/>
<path android:pathData="M54,38L77,48L85,42L63,32Z" android:fillColor="#79EBD9"/>
<path android:pathData="M49,21Q50,18 54,19L65,23Q68,24 67,28L63,39Q62,42 58,41L47,37Q44,36 45,32Z" android:strokeColor="#D8FFF8" android:strokeWidth="0.7">
<aapt:attr name="android:fillColor">
<gradient android:startX="46" android:startY="20" android:endX="67" android:endY="41" android:startColor="#83F5DD" android:endColor="#8055F2" android:type="linear"/>
</aapt:attr>
</path>
</vector>
@@ -0,0 +1,8 @@
<?xml version="1.0" ?>
<vector xmlns:android="http://schemas.android.com/apk/res/android" xmlns:aapt="http://schemas.android.com/aapt" android:width="108dp" android:height="108dp" android:viewportWidth="108" android:viewportHeight="108">
<path android:pathData="M0,0H108V108H0Z">
<aapt:attr name="android:fillColor">
<gradient android:type="radial" android:centerX="70" android:centerY="22" android:gradientRadius="100" android:startColor="#302052" android:endColor="#090B17"/>
</aapt:attr>
</path>
</vector>
@@ -0,0 +1,4 @@
<?xml version="1.0" ?>
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="108dp" android:height="108dp" android:viewportWidth="108" android:viewportHeight="108">
<path android:fillColor="#FFFFFF" android:pathData="M30,50L52,60L52,81L30,71ZM56,60L78,50L78,71L56,81ZM30,46L52,56L40,62L18,52ZM56,56L78,46L90,52L68,62ZM31,44L52,35L44,29L23,39ZM56,35L77,44L85,39L64,29ZM49,19Q50,17 53,18L65,22Q68,23 67,26L63,37Q62,40 59,39L47,35Q44,34 45,31Z"/>
</vector>
@@ -0,0 +1,6 @@
<?xml version="1.0" ?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/pakkit_launcher_background"/>
<foreground android:drawable="@drawable/pakkit_icon"/>
<monochrome android:drawable="@drawable/pakkit_mark"/>
</adaptive-icon>
+5
View File
@@ -0,0 +1,5 @@
<?xml version="1.0" ?>
<resources>
<string name="pakkit_name">Pakkit</string>
<string name="brand_tagline">Pocket to Wrist.</string>
</resources>
+11
View File
@@ -0,0 +1,11 @@
<?xml version="1.0" ?>
<resources>
<style name="Theme.Pakkit" parent="android:style/Theme.Material.NoActionBar">
<item name="android:fontFamily">sans</item>
<item name="android:colorAccent">#BAA6FF</item>
<item name="android:windowBackground">#090B17</item>
<item name="android:windowLightStatusBar">false</item>
<item name="android:windowSplashScreenBackground">#090B17</item>
<item name="android:windowSplashScreenAnimatedIcon">@drawable/pakkit_icon</item>
</style>
</resources>
@@ -0,0 +1,17 @@
<?xml version="1.0" ?>
<data-extraction-rules>
<cloud-backup disableIfNoEncryptionCapabilities="true">
<exclude domain="root" path="."/>
<exclude domain="file" path="."/>
<exclude domain="database" path="."/>
<exclude domain="sharedpref" path="."/>
<exclude domain="external" path="."/>
</cloud-backup>
<device-transfer>
<exclude domain="root" path="."/>
<exclude domain="file" path="."/>
<exclude domain="database" path="."/>
<exclude domain="sharedpref" path="."/>
<exclude domain="external" path="."/>
</device-transfer>
</data-extraction-rules>
@@ -0,0 +1,52 @@
package meghdad.pakkit.apk
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import org.junit.Assert.*
import org.junit.Test
class ApkRulesTest {
@Test
fun copyComputesKnownDigest() {
val output = ByteArrayOutputStream()
val result = ApkRules.copyBounded(ByteArrayInputStream("abc".toByteArray()), output)
assertEquals(3L, result.first)
assertEquals(
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
result.second,
)
assertEquals("abc", output.toString("UTF-8"))
}
@Test(expected = IllegalArgumentException::class)
fun stopsBeforeWritingOverLimit() {
ApkRules.copyBounded(ByteArrayInputStream(ByteArray(1025)), ByteArrayOutputStream(), 1024)
}
@Test(expected = IllegalArgumentException::class)
fun refusesEmptyFiles() {
ApkRules.copyBounded(ByteArrayInputStream(byteArrayOf()), ByteArrayOutputStream())
}
@Test
fun rejectsTraversalAndInvalidIdentifiers() {
assertFalse(ApkRules.validId("../apk"))
assertFalse(ApkRules.validId("file.apk"))
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")))
assertTrue(ApkRules.compatibleAbis(setOf("armeabi-v7a", "arm64-v8a"), setOf("arm64-v8a")))
assertFalse(ApkRules.compatibleAbis(setOf("x86_64"), setOf("arm64-v8a")))
}
}
@@ -0,0 +1,31 @@
package meghdad.pakkit.apk
import org.junit.Assert.*
import org.junit.Test
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)
}
@Test
fun rejectsIncompatibleSdkProcessorAndInsufficientStorage() {
assertTrue(
runCatching {
PackageInspector.checkForWatch(apk, 30, setOf("arm64-v8a"), Long.MAX_VALUE)
}
.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,
)
}
}
@@ -0,0 +1,67 @@
package meghdad.pakkit.transfer
import org.junit.Assert.*
import org.junit.Test
class HttpProtocolTest {
private fun request(value: String) = HttpProtocol.read(value.byteInputStream())
@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",
)
assertEquals(42L, HttpProtocol.uploadLength(r.headers))
assertEquals("/api/upload", r.path)
}
@Test
fun rejectsAmbiguousAndOversizedHeaders() {
for (headers in
listOf(
"Content-Length: 1\r\nContent-Length: 2",
"Transfer-Encoding: chunked",
"Expect: 100-continue",
"Host: x\nBad: x",
"Long: " + "a".repeat(9000),
)) {
assertTrue(
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")) {
assertTrue(
runCatching {
HttpProtocol.uploadLength(
mapOf(
"content-type" to "application/octet-stream",
"content-length" to length,
),
)
}
.isFailure,
)
}
assertTrue(
runCatching {
HttpProtocol.uploadLength(
mapOf("content-type" to "text/plain", "content-length" to "42"),
)
}
.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"))
}
}
@@ -0,0 +1,40 @@
package meghdad.pakkit.transfer
import org.junit.Assert.*
import org.junit.Test
class UploadBodyTest {
@Test
fun readsExactlyDeclaredLengthWithoutConsumingExtraBytes() {
val input = "abcdef".byteInputStream()
val events = mutableListOf<Long>()
val body = UploadBody(input, 3, { events.add(it) })
assertArrayEquals("abc".toByteArray(), body.readBytes())
assertEquals('d'.code, input.read())
assertEquals(listOf(3L), events)
}
@Test(expected = IllegalArgumentException::class)
fun refusesTruncatedBodies() {
UploadBody("ab".byteInputStream(), 3, {}).readBytes()
}
@Test
fun zeroLengthReadDoesNotAdvanceOrReportProgress() {
val body = UploadBody("abc".byteInputStream(), 3, { fail("No progress expected") })
assertEquals(0, body.read(ByteArray(1), 0, 0))
assertEquals('a'.code, body.read())
}
@Test
fun progressIsThrottledAndAlwaysReportsCompletion() {
var now = 0L
val events = mutableListOf<Long>()
val body = UploadBody("abc".byteInputStream(), 3, { events.add(it) }, { now })
body.read()
now = 250_000_000
body.read()
body.read()
assertEquals(listOf(2L, 3L), events)
}
}
@@ -0,0 +1,45 @@
package meghdad.pakkit.ui
import kotlin.math.pow
import org.junit.Assert.assertTrue
import org.junit.Test
class WatchColorsTest {
@Test
fun bodyAndSecondaryTextAreReadableOnWatchSurfaces() {
for (surface in listOf(WatchColors.canvas, WatchColors.raised)) {
assertTrue(contrast(WatchColors.text, surface) >= 4.5)
assertTrue(contrast(WatchColors.secondary, surface) >= 4.5)
}
}
@Test
fun semanticColorsAreReadableOnTheirSurfaces() {
for ((text, surface) in
listOf(
WatchColors.accent to WatchColors.accentSoft,
WatchColors.mint to WatchColors.mintSoft,
WatchColors.error to WatchColors.errorSoft,
)) assertTrue(contrast(text, surface) >= 4.5)
}
@Test
fun whiteTextContrastsWithBothActionGradientStops() {
for (stop in listOf(0xFF7854EE.toInt(), 0xFF6038D6.toInt())) assertTrue(
contrast(-1, stop) >= 4.5,
)
}
private fun contrast(a: Int, b: Int): Double {
fun luminance(color: Int): Double {
fun channel(shift: Int): Double {
val value = ((color shr shift) and 255) / 255.0
return if (value <= .04045) value / 12.92 else ((value + .055) / 1.055).pow(2.4)
}
return .2126 * channel(16) + .7152 * channel(8) + .0722 * channel(0)
}
val x = luminance(a)
val y = luminance(b)
return (maxOf(x, y) + .05) / (minOf(x, y) + .05)
}
}
-1
View File
@@ -1,4 +1,3 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins { plugins {
alias(libs.plugins.android.application) apply false alias(libs.plugins.android.application) apply false
} }
-39
View File
@@ -1,39 +0,0 @@
# Pakkit — Pocket to Wrist.
The supplied `brand-concept.png` is a creative reference, not a screen specification or feature promise. The product uses the user's official taglines, **Pocket to Wrist.** and **Pack it. Send it. Wear it.** Copy such as “Apps, on your wrist” or percentages in the reference does not override those decisions or actual platform capabilities.
## Identity
An open parcel and a floating app tile form Pakkit's mark. Cyan and mint illuminate one face; electric violet lights the other. The detached tile suggests a small app making a deliberate journey. The same silhouette appears in the adaptive launcher, monochrome icon, splash, browser illustration and watch header. The work is implemented as vector paths, native shaders and reusable Android components; the reference board is never rendered as application UI.
## Color and typography
`BrandPalette` in `shared/.../Design.kt` provides semantic tokens for light and dark canvas, cards, body text, secondary text, borders, actions, mint statuses and errors. Principal colors: midnight `#090B17`, action purple `#7150EF`, mint `#68E9CF`, cyan `#37D7F2`. Action buttons use a readable violet gradient. Text colors are adapted rather than copying a bright accent onto every surface.
Lavender light uses subtly tinted backgrounds and white cards. Midnight dark uses restrained illumination, deep surfaces and soft lavender text. The web interface follows the browser’s color scheme and offers an in-session light/dark toggle. The watch stays midnight in either system theme to limit lit pixels on OLED displays.
Typography uses Android's native sans family with explicit 400/600/650 weights, slightly tightened large headings and scalable SP sizes. Copy remains real text, not outlined lettering. The scale is deliberate: watch titles 21–25 SP and supporting text 12–14 SP. Small metadata remains scrollable. There are no fixed-height text containers.
## Components and interaction
- `ParcelSceneView`: prebuilt parcel geometry, static radial lighting, a floating app tile and a finite 1.1-second entrance. No bitmap assets, blur layers or continuous particle simulation.
- `GlyphDrawable`: a consistent stroke family for navigation, watch, file, trust and status icons. Icons supplement text; decorative art is excluded from accessibility focus.
- Native buttons: gradient primary, tonal secondary, ripple feedback and platform confirmation haptics. Watch actions have a minimum height of 48 DP.
- Browser cards: quiet borders, violet actions, original parcel SVG, responsive spacing, semantic native controls, drag/drop and keyboard file selection. All assets are served by the watch.
- `RoundScrollView`: symmetric proportional watch margins, generous end padding, rotary scrolling and an on-demand scroll indicator following the bezel. TextClock updates with the platform; no custom clock loop.
- Scroll position is retained during ordinary status refreshes. New transfer stages on the watch return to the heading so the current decision remains discoverable.
- Motion respects system animation settings and battery saver. Decorative watch art is static. Web motion is a finite entrance and short hover/press feedback, respecting prefers-reduced-motion. Byte progress reflects actual socket reads on the watch and XHR progress in the browser; verification and installation are distinct states.
## Product truth
Brand language must never imply a compatibility guarantee or a security bypass. An APK is “Installed” only after Android reports success. Source approval, explicit watch review, system consent, unsupported firmware handling, signature/integrity checks and Google Play policy boundaries remain in force. The reference's installed-app catalog and imagined battery percentages are not implemented features.
## Validation
Automated contrast checks cover normal body and secondary copy on all base surfaces, status badges and both action-gradient endpoints at 4.5:1 or better. Tests exercise HTTP framing, upload authorization, actual streamed APK inspection and the installation consent boundary. Full TalkBack and physical-watch accessibility validation remain release gates.
Design references: [Wear accessibility](https://developer.android.com/training/wearables/accessibility), [round screen guidance](https://developer.android.com/design/ui/wear/guides/get-started/design-for-wearables), [Wear app quality](https://developer.android.com/docs/quality-guidelines/wear-app-quality), and [power guidance](https://developer.android.com/training/wearables/apps/power). These inform the implementation; their requirements are not a substitute for Play review or physical-device testing.
## Standalone web identity
`wear/src/main/assets/web` contains the real HTML/CSS/JS product. A luminous open-parcel SVG complements the native launcher mark. The two-column desktop composition becomes a single-column mobile journey; actual upload, verification, review, system-consent, error and success states use live watch responses. No mock status, screenshot-based control, remote dependency or perpetual animation appears in the browser UI. Historical phone components/screenshots are not current product flows.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 MiB

+31 -21
View File
@@ -1,35 +1,45 @@
# Standalone architecture and security # Architecture
## Components and flow 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.
WatchActivity → explicit Start receiving → ReceiveService → Wi-Fi network request → private IPv4 listener → private URL/QR → browser HTML/CSS/JS from watch → authenticated raw APK POST → bounded private file → Android archive inspection → ready state → watch Install → PackageInstaller → system consent → result receiver → browser status. ## Ownership
`shared` contains protocol/inspection/storage/design code. `wear` owns the server and installer. The phone module, Play Services Data Layer and WorkManager have been removed. No Google services runtime, backend, account, mDNS or WebView is required. ZXing Core encodes the QR locally. | 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 |
## Session ownership 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.
The user starts a connectedDevice foreground service while WatchActivity is visible. Wi-Fi is requested for up to 25 seconds; absent connectivity yields a recoverable message. A socket binds exclusively to the chosen Wi-Fi private IPv4 address and ephemeral port. The service is never exported, restarted automatically or started at boot. The ten-minute deadline starts at user initiation; a timed CPU wake lock covers the session without keeping the screen on. Losing that network ends the session. Stop closes accepted sockets, shuts down the bounded worker pool, unregisters the network callback, removes the URL and releases power resources. ## Receiving lifecycle
The browser may continue watching installation results while the session remains active. Ending the network session does not cancel an already committed Android installation or delete a pending user review. A completed upload remains eligible for review for 24 hours; expired packages are removed when the app next opens. This is lazy cleanup, not a guaranteed background deletion deadline. Partial and rejected uploads are deleted immediately. Reboot/process death requires a new receiving session. No resume tokens are persisted for transfer recovery. 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.
## HTTP boundary 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.
- Independent 192-bit SecureRandom URL-safe key per session, in the URL fragment so the initial HTTP request does not include it. JS removes the fragment from visible history after loading, keeps it only in memory and sends an Authorization bearer header for APIs. Reload without the key requires re-entering it or rescanning. `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.
- All content is local. Strict self-only script/style/connect CSP, no framing, no referrer, no cache, no MIME sniffing, no CORS or external fonts/trackers.
- Exact Host check protects against DNS rebinding. Upload requires the watch page’s exact Origin and bearer token. No browser install/cancel-install endpoint exists.
- Parser limits headers to 8 KiB and lines to 4 KiB, rejects duplicate headers, invalid framing, transfer encoding, expectations and unsupported methods. Each socket serves one request then closes. Only fixed public asset routes are served; there is no user-controlled filesystem lookup.
- Raw octet-stream POST with positive Content-Length <=50 MiB. No multipart buffering, user filenames or extraction into filesystem paths. UUID private filename. One upload at a time; another review must be dismissed/completed first. Free-space preflight, streamed SHA-256, 64 KiB buffer, ZIP expansion/entry limits, full-package/split and self-update rejection, SDK/ABI/storage checks.
- Two workers, four queued connections, 15-second read inactivity deadline and hard session lifetime. CPU/memory/storage are bounded. Early rejected large requests may be observed by a browser as a connection error because the server intentionally does not consume an unauthorized body.
- Progress is bytes actually read on the watch and bytes sent by browser XHR. 100% sent changes to verification wording and never implies installation. Installation success appears only after STATUS_SUCCESS.
## Trust model ## Durable package state
Local HTTP is unencrypted. Link secrecy, Host/Origin checks and SHA-256 do not stop an active LAN attacker, protect against passive capture, or authenticate the server with a certificate. Use a trusted private Wi-Fi and keep the private URL secret. Anyone holding the link can submit a package, but only an explicit watch action can request its installation and Android requires consent. The app does not claim malware scanning or universal app compatibility. Source approval and system restrictions remain authoritative. 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.
ReceiveService has INTERNET, ACCESS_NETWORK_STATE, CHANGE_NETWORK_STATE, WAKE_LOCK and foreground-service permissions; these support the explicit Wi-Fi session. REQUEST_INSTALL_PACKAGES is limited to the watch. Optional notification permission enables visible receiving/approval alerts; denying it does not authorize hidden background starts or bypass the in-app consent flow. The system may still expose the running foreground service in its task UI. 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.
## Installation state ## HTTP and trust
`LocalInstall.status` writes watch-local ready/installing/confirm/installed/failed state. Store persists the current package/review across activity recreation. Session callbacks validate job and session IDs in a non-exported receiver. The pending system intent is kept in process or carried by the app’s immutable notification PendingIntent; interrupted approval can be retried. Installation re-hashes the private file and rechecks compatibility before writing a PackageInstaller session. Dismiss deletes the staged package. Success deletes it and cancels the consent notification. 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.
No appops mutation, permission grant shell command, ADB client, root, hidden installer component, device-owner privilege, automatic installation, browser-driven installation or Pakkit self-update exists in the product. 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.
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.
## 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.
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.
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.
+26
View File
@@ -0,0 +1,26 @@
# Pakkit design
**Pakkit — Pocket to Wrist.** Secondary tagline: **Pack it. Send it. Wear it.** The identity is friendly, playful and polished: an open parcel with a floating app tile, soft geometry, violet lighting and mint/cyan accents.
## Implemented assets
- `app/src/main/res/drawable/pakkit_icon.xml`: gradient parcel artwork used by the watch header, splash and adaptive launcher.
- `pakkit_mark.xml`: monochrome launcher/notification mark.
- `app/src/main/assets/web/index.html`: original inline vector parcel illustration and compact wordmark icon. These are real SVG elements, not screenshots.
- `ui/WatchDesign.kt`: only the native watch’s actual text, action, badge, color and shape primitives.
- `ui/GlyphDrawable.kt`: check/error glyphs, paired with explanatory text.
- `ui/RoundScrollView.kt`: bezel position indication and native rotary/touch scrolling, redrawn in response to scroll changes.
## Themes and layout
The native watch UI uses midnight `#090 B 17` 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 trust disclosure remain scrollable below it.
The browser 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
The watch has static decorative artwork. Browser motion is a finite parcel entrance and short hover/press feedback; prefers-reduced-motion disables these. There are no continuous particle effects or decorative render loops. Polling pauses in hidden tabs.
Upload progress reflects actual XHR bytes sent and socket bytes read. “100% sent” transitions to package checking, never to an installation-success claim. The browser distinguishes upload, verification, watch review, system approval, failure and success. Android STATUS_SUCCESS is the authority for “installed”. Cancelling an HTTP request does not imply a rollback of a file the watch may already have received.
Keep copy precise: preflight does not certify safety or runtime compatibility. Source approval and system consent are explicit decisions. The trust disclosure describes unencrypted local HTTP without claiming encryption.
+61
View File
@@ -0,0 +1,61 @@
# Development and testing
## Environment
- Android Studio with JDK 21 (set JAVA_HOME for shell builds).
- SDK platform 36.1, current platform-tools and Android Emulator 36.5+ for shared virtual Wi-Fi.
- A round Wear OS Emulator (API 31+); an Android Emulator with Chrome is used as a browser device.
- Python 3 for the test runner. Optional Node 22+ and npm for browser tests/formatting.
`local.properties`, IDE files, Gradle/Kotlin caches, node_modules, generated APKs/reports and signing keys are ignored. Android Studio regenerates its local project model. No generated reports or screenshots are committed.
## Build and native tests
```sh
./gradlew :app:assembleDebug :app:assembleDebugAndroidTest :app:testDebugUnitTest :app:lint :app:bundleRelease
adb devices
python 3 scripts/test-emulators.py --watch emulator-5554 --skip-build
python 3 scripts/test-emulators.py --watch emulator-5554 --small --skip-build
```
Use actual serials from `adb devices`. The runner refuses serials that do not start with `emulator-` and requires the watch feature. It never selects a physical device. It connects the watch to the virtual AndroidWifi access point, installs only the app/test APKs and saves results under `app/build/reports/validation`. The small-screen run temporarily uses 192 dp and 1.3x font scaling, restoring the previous size, density and font setting in a finally block.
For install tests, first open Pakkit on the emulator and use **Allow installs** to approve it through the normal system UI. No shell permission grant is needed. Tests mark missing source approval as an assumption; the runner treats skipped tests as incomplete validation. Native tests clean up staged files, pending system sessions, notifications and activities. The official-installer test stops at required system consent and abandons its test session afterward.
The optional Google Maven mirror property is documented in README.md. If needed, build with that property and pass --skip-build to the runner; its default build uses standard repositories.
## Browser UI tests
```sh
npm ci --prefix web-tests
npm exec --prefix web-tests -- playwright install chromium
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.
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.
## Real browser-to-watch emulator transfer
Complete Chrome’s first-run setup in the Android Emulator, leave Chrome open, and run:
```sh
python 3 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.
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.
## Fixture and release inspection
`qa/fixture` builds a minimal signed test app. StageFixtureApk copies it into debug instrumentation assets only. The consumer APK/AAB must contain no fixture APK or test classes. Inspect release resources, merged permissions and runtime dependencies when changing Gradle configuration:
```sh
./gradlew :app:dependencies --configuration releaseRuntimeClasspath
./gradlew :app:bundleRelease
```
Hardware testing is a final compatibility/power gate, documented in VALIDATION.md, rather than a routine development requirement.
-49
View File
@@ -1,49 +0,0 @@
# Standalone feasibility decision
Research and implementation: October 15, 2026. Pakkit 0.2 replaces the companion architecture.
## Decision and evidence boundary
Use a user-started local HTTP receiving session hosted by the watch, followed by explicit on-watch review and a public PackageInstaller session requiring user action. Receiving a file does not install it. Support is conditional on firmware exposing source approval and a functioning system installer.
Android’s [Wear network guidance](https://developer.android.com/training/wearables/data/network-communication) explicitly supports HTTP/TCP/UDP and independent network access. This supports implementing a server using ordinary Android sockets; the documentation does not certify inbound reachability on every network. A Bluetooth-proxied internet route is not an inbound Wi-Fi listener, so Pakkit requests a Wi-Fi network and binds only its private IPv4 address. Guest-network isolation and firewalls remain outside application control.
The [standalone app definition](https://developer.android.com/training/wearables/apps/standalone-apps) permits QR/browser alternatives without a companion phone app. The manifest now declares standalone=true. “Any device” means a supported modern browser on a reachable local network, not independence from the watch’s original OEM onboarding requirements. A Galaxy Watch 7’s initial setup requirements are separate from Pakkit’s browser support.
## Installation is a separate capability
[PackageInstaller](https://developer.android.com/reference/android/content/pm/PackageInstaller) permits ordinary apps to create sessions with REQUEST_INSTALL_PACKAGES. Pakkit uses MODE_FULL_INSTALL and USER_ACTION_REQUIRED, handles STATUS_PENDING_USER_ACTION and starts only the returned system confirmation intent following a watch action. Android decides the final outcome. Readable signing metadata, hashes, SDK, ABI and space checks are preflight, not malware scanning or proof that an app will work on a round display.
[canRequestPackageInstalls](https://developer.android.com/reference/android/content/pm/PackageManager#canRequestPackageInstalls()) reports source trust. [ACTION_MANAGE_UNKNOWN_APP_SOURCES](https://developer.android.com/reference/android/provider/Settings#ACTION_MANAGE_UNKNOWN_APP_SOURCES) is the public settings route. A resolving activity alone does not prove a usable permission UI. Pakkit checks actual trust and gates session start; if approval is unavailable it explains the limit and offers Google Play. No appops changes, hidden components, privileged APIs or debugging client exist in application code.
### Galaxy Watch 7 evidence
Reference hardware observed: SM-L310, Android 16, fingerprint `samsung/fresh7blue/fresh7bl:16/BP2A.250325.020/L310XXS2BZF4:user/release-keys`.
The user reports that the previous Pakkit build completed installation normally without ADB, including with ADB debugging disabled. The development inspection found REQUEST_INSTALL_PACKAGES already allowed; no shell permission grant or security-setting modification was made. This is useful hardware evidence but does not independently reproduce a fresh Play-installed permission setup. See VALIDATION.md for the separately observed browser/upload/installer results. Do not generalize this result to every Samsung firmware, region or security configuration.
## Lifecycle and power
A [connectedDevice foreground service](https://developer.android.com/develop/background-work/services/fgs/service-types#connected-device) fits an explicit local transfer with an external browser device. CHANGE_NETWORK_STATE is used to request Wi-Fi and meets this service type’s declared prerequisite. The foreground notification has a stop action. A timed partial wake lock keeps the CPU available without holding the display on. Wi-Fi requests and CPU lock are released at session stop, network loss, service destruction or ten-minute expiry. Nothing starts at boot; START_NOT_STICKY prevents automatic session resurrection. Process death invalidates the session and the user starts another.
No continuous decorative watch animation, discovery broadcasts, cloud relay or analytics runs. Browser polling pauses while hidden. Watch byte updates are throttled to four per second. This bounds resource use but is not a battery consumption measurement; screen-off longevity, thermal and energy measurements remain release tests.
[Local network protections](https://developer.android.com/privacy-and-security/local-network-permission) cover incoming TCP too. At the current target SDK 36, INTERNET provides implicit local access. Before targeting 37, implement and test ACCESS_LOCAL_NETWORK runtime permission; official guidance says not to request it on lower targets. Browsers can independently require local-network permission.
## Google Play
The [REQUEST_INSTALL_PACKAGES policy](https://support.google.com/googleplay/android-developer/answer/12085295?hl=en) permits file sharing/transfer/management when package receipt and user-initiated installation are core functionality. Pakkit appears aligned with that category; this is an eligibility assessment, not approval. Accurately declare the final standalone purpose in Play Console and show source approval, transfer, watch review, system consent and denial handling. Do not reuse a companion-sync justification.
Declare the [foreground service use](https://support.google.com/googleplay/android-developer/answer/13392821) and provide the required demonstration. Publish only the watch artifact, with the required watch feature and standalone metadata, following [Wear packaging guidance](https://developer.android.com/training/wearables/packaging).
[Android developer verification](https://developer.android.com/developer-verification/guides) can add system restrictions to external apps. Some unverified-developer flows require developer settings and a delay. Those flows conflict with the product’s setup goal; Pakkit does not bypass them. Describe the supported compatible/verified package path rather than guaranteeing installation of every APK.
## Alternatives and limits
- **Google Play installation:** the compliant fallback when source trust, security policy, verification or firmware blocks external installation. Pakkit cannot silently elevate itself.
- **Trusted HTTPS relay:** could avoid LAN reachability and certificate setup, but requires a backend, retention policy, hosting cost, internet connectivity and additional privacy work. It would not fix a blocked PackageInstaller. Not implemented.
- **Local HTTPS:** a self-signed watch certificate produces browser trust warnings; ordinary public trust cannot be issued to an arbitrary private IP without additional infrastructure. Current local HTTP avoids certificate setup, openly limits use to trusted networks and does not claim encryption.
- **ADB/root/device-owner hacks:** excluded; they defeat the product goal or require privileges consumers do not have.
- **Cloud APK catalog/self-updater:** excluded; no third-party catalog, bundled consumer APK or Pakkit self-update path.
Current scope: private IPv4 Wi-Fi, one complete APK up to 50 MiB, one pending review, no split/APKS/APKM/XAPK/AAB support, no resumable upload. The OS performs final signature/update/verification checks. A failed firmware matrix or rejected permission declaration blocks production publication; a working upload alone does not change that decision.
+31
View File
@@ -0,0 +1,31 @@
# Platform and distribution constraints
## Supported flow
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.
[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.
## Source approval and installation
[PackageManager.canRequestPackageInstalls](<https://developer.android.com/reference/android/content/pm/PackageManager#canRequestPackageInstalls()>) reports trust as an installation source. Pakkit opens the public [unknown-app sources setting](https://developer.android.com/reference/android/provider/Settings#ACTION_MANAGE_UNKNOWN_APP_SOURCES) for the user to approve; it never changes that setting itself.
[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.
## 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.
[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.
## Google Play
The [REQUEST_INSTALL_PACKAGES policy](https://support.google.com/googleplay/android-developer/answer/12085295?hl=en) permits file transfer/management where package receipt and user-initiated installation are core functionality. This makes Pakkit’s use potentially eligible; it does not guarantee approval. Accurately declare this purpose and submit the source-approval/review/consent flow. Also declare the [foreground-service use](https://support.google.com/googleplay/android-developer/answer/13392821) and meet [Wear packaging/quality guidance](https://developer.android.com/training/wearables/packaging).
[Android developer verification](https://developer.android.com/developer-verification/guides) may add restrictions to externally installed packages. Pakkit respects system blocks and does not promise to install every APK without additional platform requirements.
Local HTTP avoids a self-signed certificate setup flow but is unencrypted and limited to trusted networks. A relay or local HTTPS architecture would require separate certificate/backend/privacy work and would not make a blocked installer available. Google Play is the supported fallback when firmware or security policy prevents external installation.
+7 -7
View File
@@ -1,13 +1,13 @@
# Pakkit privacy disclosure draft # Privacy disclosure draft
Pakkit transfers an APK that you select in a browser directly to your Wear OS watch over your local Wi-Fi. It does not require an account, companion app, cloud relay, analytics or advertising. The HTML, styles, JavaScript, icons and QR generation are bundled with the watch app; no external font or asset service is contacted. 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.
A short receiving session exposes a private URL and key. Keep that link private and use trusted Wi-Fi. Local HTTP is not encrypted; people able to observe or alter your network traffic may access it. Your browser/operating system may maintain its own local browsing history. Pakkit does not log uploaded filenames, IP addresses, keys or APK contents to a remote service. 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 APK is stored in the app’s private watch storage. Pakkit reads package metadata and signing information, checks size/compatibility and computes a hash. This does not certify that a package is safe. Nothing installs until you explicitly request it on the watch and complete Android’s system approval. Android may independently verify the app under its own policies. APKs and package-review metadata are stored in private watch storage. Pakkit reads package/signing metadata and computes a hash to detect corruption or changed staged files. This is not malware certification. Installation requires your watch action and Android’s system consent. Android can independently verify or block packages under its own policies.
Rejected/partial uploads are deleted. Successful installations and dismissed reviews delete the staged APK. Pending packages expire for installation after 24 hours and are cleaned up on the next app launch; they may remain in private storage until then. Local status history holds up to 20 entries of package label, state and timestamp. App backups/device transfer are disabled. Uninstalling Pakkit removes its private data; installed third-party apps are separate. 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.
Sessions end automatically within ten minutes, on Wi-Fi loss or when you stop them. Ending a session closes network access; it does not cancel an already committed system installation. 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.
Before publication, add the legal developer identity, support contact and hosted privacy policy URL. Reconcile the final binary, Android system behavior and Google Play Data safety answers; this draft is not a completed Play declaration. 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.
+32 -14
View File
@@ -1,16 +1,34 @@
# Google Play release preparation # Release preparation
Pakkit is implemented as a standalone Wear OS app. This checklist does not assert Google Play approval. ## Artifact
- Publish only `wear`: application ID `meghdad.pakkit`, version 0.2.0/code100003, standalone=true, required watch feature, min31/target36/compile36.1. The phone module is removed. Increment codes for subsequent uploads. Publish the app module’s Wear OS AAB: application ID `meghdad.pakkit`, version 0.3.0/code 100004, min 31/target 36/compile 36.1. It declares required watch hardware and standalone=true. Increment versionCode for each upload. R 8 and resource shrinking are enabled.
- Build `./gradlew :wear:bundleRelease`. R8/resource shrinking enabled. Debug fixtures remain only in the test APK.
- Production signing inputs: PAKKIT_KEYSTORE, PAKKIT_KEYSTORE_PASSWORD, PAKKIT_KEY_ALIAS, PAKKIT_KEY_PASSWORD. No secret/default production key is included. Without the full set the release AAB is unsigned and must be signed by the release pipeline. ```sh
- Declare REQUEST_INSTALL_PACKAGES accurately as core, user-selected local package transfer with user-initiated installation. Submit the final standalone flow, source approval, transfer, watch review, system approval, cancellation and unsupported-state screencast. Do not claim prior companion permission eligibility automatically applies. ./gradlew :app:bundleRelease
- Declare connectedDevice foreground-service use for a user-started bounded local device transfer, with notification/stop controls and required evidence. Review final merged permissions. No storage, broad package visibility, Bluetooth, location or boot permissions are requested. ```
- INTERNET/ACCESS_NETWORK_STATE/CHANGE_NETWORK_STATE support the requested Wi-Fi network and socket. WAKE_LOCK supports the bounded session. POST_NOTIFICATIONS is optional for receiving and approval alerts. Foreground service and connected-device foreground permissions are declared explicitly.
- Confirm the [install-package permission policy](https://support.google.com/googleplay/android-developer/answer/12085295) and [foreground service declaration requirements](https://support.google.com/googleplay/android-developer/answer/13392821) with the actual listing. Approval is not guaranteed. Output: app/build/outputs/bundle/release/app-release.aab. Production signing uses PAKKIT_KEYSTORE, PAKKIT_KEYSTORE_PASSWORD, PAKKIT_KEY_ALIAS and PAKKIT_KEY_PASSWORD. Set all four; incomplete/blank signing configuration fails clearly. With all unset, the bundle is unsigned and must be signed through the release pipeline. Keep keys and passwords outside source control. Application ID and private review schema are stable across updates; source class/package refactoring does not require data migration.
- Add real developer/support identity and hosted privacy policy. Reconcile Data safety with PRIVACY.md and the final binary. No backend/analytics is used, but system installation verification is controlled by Android.
- Use genuine current standalone web and round-watch screenshots. Explain trusted same-Wi-Fi requirement, unencrypted local HTTP, source approval, complete APK limit, device/firmware restrictions and final Android consent. Avoid universal “all APKs” or encrypted/private-network security guarantees. ## Runtime permission surface
- Test fresh Play-delivered source approval on Watch7 firmware/regions, screen-off receiving, blocked sources, browser local-network permission, guest/client-isolated networks, user stop, session expiry, interrupted upload, process death, battery and accessibility. Record browser/device versions. Full Safari/iOS/Firefox/Windows/Linux coverage remains required.
- Recheck target SDK, Wear quality and developer verification requirements at submission. Target37 needs runtime ACCESS_LOCAL_NETWORK implementation/testing before adoption; current target36 follows Android’s implicit local network access rules. | Permission | Use |
- Run internal/closed testing and Play pre-launch/review. Do not promote until VALIDATION.md gates are met and restricted-permission/foreground-service declarations are accepted. | -------------------------------------------------------- | ------------------------------------------------------------------------- |
| INTERNET | Local listener and HTTP responses |
| ACCESS_NETWORK_STATE / CHANGE_NETWORK_STATE | Request/watch the Wi-Fi network and handle connectivity lifecycle |
| WAKE_LOCK | Timed partial CPU lock during a receiving session |
| FOREGROUND_SERVICE / FOREGROUND_SERVICE_CONNECTED_DEVICE | Explicit local receiving service with stop action |
| REQUEST_INSTALL_PACKAGES | Watch-initiated system installation after review |
| POST_NOTIFICATIONS | Optional session/approval alerts; in-app consent remains usable if denied |
No package-visibility queries, broad storage, location, Bluetooth, boot receiver or unrestricted installed-app enumeration is required. Inspect merged release permissions and verify fixture/test assets are absent. Release runtime dependencies are ZXing Core and the Kotlin standard library with its annotations dependency; browser development tools are separate.
## Publication gates
1. Complete unit/native/browser checks in DEVELOPMENT.md and the hardware-specific matrix in VALIDATION.md.
2. Submit REQUEST_INSTALL_PACKAGES as core local package receipt plus user-initiated installation, with source approval, transfer, watch review, system consent, denial and cancellation evidence. [Permission policy](https://support.google.com/googleplay/android-developer/answer/12085295).
3. Submit the connectedDevice foreground-service declaration and required demonstration. [Foreground-service requirements](https://support.google.com/googleplay/android-developer/answer/13392821).
4. Provide real developer/support identity, hosted privacy policy, Data safety answers, content rating, audience/ads declarations and current screenshots. Generate screenshots from the product; do not commit development artifacts as source assets.
5. Describe trusted same-Wi-Fi, unencrypted HTTP, complete APK limit, source approval and firmware/package restrictions accurately. Do not promise universal compatibility, malware certification, silent installation or guaranteed permission approval.
6. Recheck target API, Wear app quality and developer-verification requirements against current Play Console guidance. Target 37 requires explicit local-network permission implementation/testing.
7. Run internal/closed testing and Play review before public promotion. Successful development/emulator tests do not constitute Google Play acceptance.
+37 -26
View File
@@ -1,37 +1,48 @@
# Standalone validation — October 15, 2026 # Validation
Version 0.2.0 / 100003. The consumer app is standalone; old companion test results in `validation/brand` and older screenshots are historical evidence only. Routine validation uses a Wear OS Emulator and an Android Emulator browser. Hardware is reserved for final compatibility and power testing. This document distinguishes completed automated coverage from release requirements.
## Automated coverage ## Reproducible checks
- 13 shared JVM tests: six bounded-stream/expiry/ABI rules, three semantic contrast checks, four HTTP parsing/authentication/size tests. Results: `shared/build/test-results/testDebugUnitTest`. See DEVELOPMENT.md for the commands and environment setup. Results are generated under app/build rather than committed. Current architecture: one production Android module (`app`) and the instrumentation-only signed fixture (`qaFixture`).
- Two watch instrumentation tests on the Wear OS API37 round emulator: actual Wi-Fi socket GET/status/raw APK POST; missing-token and cross-origin rejection; invalid APK deletion; duplicate upload refusal; verified fixture metadata; no automatic PackageInstaller session; listener closes and private URL clears at explicit stop. The separate round-review test verifies 48dp actions are reachable and receipt does not create an installation session.
- The emulator needed its virtual Wi-Fi enabled and associated with AndroidWifi. Initial failures while Wi-Fi was disabled were environmental. A repeated run exposed an HTTP test-client bug: reading until EOF could observe a reset after an intentionally early rejected request; the test now reads the response’s exact Content-Length. Final results are saved in `validation/standalone/watch-tests.txt`.
- Debug APK, instrumentation APK, optimized release AAB, shared unit tests and Android lint build successfully. Lint has zero errors; remaining warnings concern SDK/library update suggestions and optional KTX/style changes. Release bundle is unsigned unless production signing inputs are supplied.
## Physical Galaxy Watch 7 | 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 |
| 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 |
| 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 |
SM-L310, Android16 firmware `L310XXS2BZF4`, full fingerprint in FEASIBILITY.md. Development ADB installed Pakkit and observed/clicked visible UI for QA. No `pm grant`, `appops set`, hidden installer, root or ADB package installation was used to install the QA fixture. Consumer code contains no ADB/debugging path. The install-consent test calls the same ApkInstaller used by the explicit watch action, waits for Android’s STATUS_PENDING_USER_ACTION and abandons the test session afterward. It does not grant permission or install through a shell command. Tests that require source approval use the emulator’s normal system setting; skipped assumptions are reported as incomplete validation by the test runner.
1. Existing Pakkit source approval was already allowed. User reports normal prior source approval/installation without ADB, including with ADB debugging disabled. The agent did not reproduce a fresh Play-installed permission setup. Browser UI fixtures exercise interactions independently; the separate Android Emulator test proves that the actual browser/XHR path reaches the actual watch listener. These are not substituted for one another. The receiving protocol continues to have no browser-triggered installation endpoint.
2. Started Pakkit’s explicit receiving session on real Wi-Fi. Watch issued a private IPv4 URL and locally generated QR.
3. Headless Chromium opened **the real watch-hosted site**, authenticated and rendered desktop1440x1100 and mobile390x844 layouts in light/dark modes. Zero JavaScript errors; no mobile horizontal overflow. Screenshots are actual product renders in `screenshots/standalone`.
4. Browser selected our signed `qaFixture-debug.apk` (2,473,486 bytes), uploaded it through XHR to the watch’s socket and received ready. Watch persisted package `meghdad.pakkit.fixture`, correct SHA-256 and source `local-browser`. Receiving stopped at review without an installation session.
5. Watch Install and Continue actions reached the pending system-consent flow. Subsequent InstallReceiver history recorded **installed** for that exact upload UUID, and Android’s package list confirmed the fixture. The user was interacting with the watch during this test. A separate screenshot of the system installer was not captured; the image initially taken after consent had already returned to Pakkit is not presented as system UI evidence.
6. Repeated live HTTP checks: public page200; status without token403; wrong token403; authenticated status200; foreign-Origin upload403; invalid APK400. Recorded in `validation/standalone/live-http.json`. These checks also passed with the physical display explicitly asleep. This is a short screen-off accessibility check, not a long-duration power/Doze certification.
7. Final QR layout centers its square in the circular safe area and sizes with screen width. ZXing decoded the actual physical screenshot after masking all pixels outside the display circle (`validation/standalone/qr-check.txt`); the watch remains scrollable for the URL, disclosure and End session action.
The temporary QA fixture was removed after verification. ## Latest completed run
No release claim is inferred solely from a successful file upload. The observed fixture installation is separate, stronger evidence for this device’s public installation route with trust already granted. Refactoring validation date: October 15, 2026. No physical device was accessed.
## Remaining release gates - **19 JVM tests passed**, with zero failures/errors.
- **14 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.
- **Two round UI tests passed again** at 192 dp / 1.3x text: reachable review actions and a decodable QR whose full square fits inside the circular bezel. Size, density and font scale were restored.
- **13 browser UI checks passed** on Chromium 140.0.7339.16 across four viewport widths and both themes, 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.
- **Clean 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.
- Fresh Play-delivered installation and source-approval flow without preexisting Pakkit trust, across supported Samsung firmware/regions and security settings. Record denial/revocation/cancellation and developer-verification behavior. Detailed XML, text logs, screenshots 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.
- Google Play restricted-permission and foreground-service declaration acceptance, listing/quality review, developer identity/signing and hosted privacy policy.
- Safari on real iOS/macOS, Firefox, Edge/Windows, Android browser and Linux coverage. The current browser run was Chromium on macOS, with mobile viewport emulation; it is not proof of all browser/platform combinations.
- Full ten-minute expiry on hardware, repeated sessions, long screen-off/Doze, network/IP change, client isolation, local-network permissions, interrupted large upload, low storage and process death. Explicit-stop cleanup is automated; expiry is implemented but not yet a completed elapsed-time hardware test.
- Full TalkBack/rotary/large-text/contrast review of the new receiving screen and web flow; small round physical displays. The prior review screen was tested at192dp/1.3x text, but this does not certify every new state.
- Measured battery/thermal/memory behavior under maximum50MiB transfers and adversarial bounded connections. Locks, buffers, threads and deadlines are bounded by implementation, not a measured battery guarantee.
Do not advertise universal firmware/APK compatibility, encrypted transport, unconditional no-setup installation, or Google Play approval. ## 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.
- 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.
- Safari on iOS/macOS, Firefox, Edge/Windows, Linux browsers and Android browser variants. Emulator Chrome and desktop Chromium do not certify the whole browser matrix.
- Minimum supported API 31 devices and supported newer OS versions. Native lint checks API usage but cannot replace that runtime matrix.
- Google Play restricted-permission/foreground-service declarations, Wear quality review, signing/identity and hosted privacy policy.
Do not claim universal APK/firmware compatibility, encrypted transport, guaranteed Google Play approval or measured power quality from emulator results.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 279 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 235 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 414 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 241 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 295 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 365 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 283 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 414 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 231 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 232 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 211 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

-8
View File
@@ -1,8 +0,0 @@
meghdad.pakkit.ProductInstrumentedTest:.....
Time: 3.951
OK (5 tests)
@@ -1,8 +0,0 @@
meghdad.pakkit.wear.WatchReviewTest:.
Time: 0.854
OK (1 test)
-8
View File
@@ -1,8 +0,0 @@
meghdad.pakkit.wear.WatchReviewTest:.
Time: 0.772
OK (1 test)
-8
View File
@@ -1,8 +0,0 @@
meghdad.pakkit.ProductInstrumentedTest:....
Time: 1.434
OK (4 tests)
@@ -1,27 +0,0 @@
{
"unitSuites": [
{
"name": "meghdad.pakkit.core.TransferRulesTest",
"tests": "6",
"failures": "0",
"errors": "0"
},
{
"name": "meghdad.pakkit.core.HttpProtocolTest",
"tests": "4",
"failures": "0",
"errors": "0"
},
{
"name": "meghdad.pakkit.core.BrandPaletteTest",
"tests": "3",
"failures": "0",
"errors": "0"
}
],
"lintErrors": 0,
"lintWarnings": 17,
"version": "0.2.0",
"versionCode": 100003,
"releaseBundleSigned": false
}
@@ -1,8 +0,0 @@
{
"publicPage": 200,
"noToken": 403,
"wrongToken": 403,
"status": 200,
"wrongOrigin": 403,
"invalidApk": 400
}
-1
View File
@@ -1 +0,0 @@
Physical Watch 7 screenshot: QR decodes successfully with circular display mask.
@@ -1,9 +0,0 @@
meghdad.pakkit.wear.LocalReceiveTest:.
meghdad.pakkit.wear.WatchReviewTest:.
Time: 1.492
OK (2 tests)
-8
View File
@@ -1,8 +0,0 @@
meghdad.pakkit.wear.WatchReviewTest:.
Time: 1.014
OK (1 test)
-16
View File
@@ -1,19 +1,3 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. For more details, visit
# https://developer.android.com/r/tools/gradle-multi-project-decoupled-projects
# org.gradle.parallel=true
# When enabled, the Configuration Cache allows Gradle to skip the configuration
# phase entirely if nothing that affects the build configuration (such as build scripts)
# has changed. Additionally, Gradle applies performance optimizations to task execution.
org.gradle.configuration-cache=true org.gradle.configuration-cache=true
# Kotlin code style for this project: "official" or "obsolete":
kotlin.code.style=official kotlin.code.style=official
-12
View File
@@ -1,12 +0,0 @@
#This file is generated by updateDaemonJvm
toolchainUrl.FREE_BSD.AARCH64=https\://api.foojay.io/disco/v3.0/ids/ec7520a1e057cd116f9544c42142a16b/redirect
toolchainUrl.FREE_BSD.X86_64=https\://api.foojay.io/disco/v3.0/ids/4c4f879899012ff0a8b2e2117df03b0e/redirect
toolchainUrl.LINUX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/ec7520a1e057cd116f9544c42142a16b/redirect
toolchainUrl.LINUX.X86_64=https\://api.foojay.io/disco/v3.0/ids/4c4f879899012ff0a8b2e2117df03b0e/redirect
toolchainUrl.MAC_OS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/73bcfb608d1fde9fb62e462f834a3299/redirect
toolchainUrl.MAC_OS.X86_64=https\://api.foojay.io/disco/v3.0/ids/846ee0d876d26a26f37aa1ce8de73224/redirect
toolchainUrl.UNIX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/ec7520a1e057cd116f9544c42142a16b/redirect
toolchainUrl.UNIX.X86_64=https\://api.foojay.io/disco/v3.0/ids/4c4f879899012ff0a8b2e2117df03b0e/redirect
toolchainUrl.WINDOWS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/9482ddec596298c84656d31d16652665/redirect
toolchainUrl.WINDOWS.X86_64=https\://api.foojay.io/disco/v3.0/ids/39701d92e1756bb2f141eb67cd4c660e/redirect
toolchainVersion=21
+7 -12
View File
@@ -1,20 +1,15 @@
[versions] [versions]
agp = "9.2.1" agp = "9.2.1"
coreKtx = "1.15.0" zxing = "3.5.3"
junit = "4.13.2" junit = "4.13.2"
junitVersion = "1.3.0" androidxJunit = "1.3.0"
espressoCore = "3.7.0" androidxRunner = "1.7.0"
appcompat = "1.8.0"
material = "1.14.0"
[libraries] [libraries]
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" } zxing = { module = "com.google.zxing:core", version.ref = "zxing" }
junit = { group = "junit", name = "junit", version.ref = "junit" } junit = { module = "junit:junit", version.ref = "junit" }
androidx-junit = { group = "androidx.test.ext", name = "junit", version.ref = "junitVersion" } androidx-junit = { module = "androidx.test.ext:junit", version.ref = "androidxJunit" }
androidx-espresso-core = { group = "androidx.test.espresso", name = "espresso-core", version.ref = "espressoCore" } androidx-runner = { module = "androidx.test:runner", version.ref = "androidxRunner" }
androidx-appcompat = { group = "androidx.appcompat", name = "appcompat", version.ref = "appcompat" }
material = { group = "com.google.android.material", name = "material", version.ref = "material" }
[plugins] [plugins]
android-application = { id = "com.android.application", version.ref = "agp" } android-application = { id = "com.android.application", version.ref = "agp" }
+1 -1
View File
@@ -1,4 +1,3 @@
#Thu Oct 15 13:09:23 IRST 2026
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.1-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.1-bin.zip
@@ -6,3 +5,4 @@ networkTimeout=10000
validateDistributionUrl=true validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists
distributionSha256Sum=2ab2958f2a1e51120c326cad6f385153bb11ee93b3c216c5fccebfdfbb7ec6cb
-1
View File
@@ -1 +0,0 @@
# No reflection-based application components require custom keep rules.
Loaded 100 of 136 files, more files were not shown because too many files have changed in this diff. Show more