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
+4822 -1773

No files matched your search

+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"),
)
}
}
@@ -0,0 +1,39 @@
package meghdad.pakkit.apk
import java.io.InputStream
import java.io.OutputStream
import java.security.MessageDigest
object ApkRules {
const val MAX_BYTES = 50L * 1024 * 1024
const val TTL_MS = 24L * 60 * 60 * 1000
fun validId(id: String) =
Regex("[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}").matches(id)
fun fresh(created: Long, now: Long) = created <= now + 60_000 && now - created < TTL_MS
fun compatibleAbis(packageAbis: Set<String>, deviceAbis: Set<String>) =
packageAbis.isEmpty() || packageAbis.any { it in deviceAbis }
fun copyBounded(
input: InputStream,
output: OutputStream? = null,
max: Long = MAX_BYTES,
): Pair<Long, String> {
val hash = MessageDigest.getInstance("SHA-256")
val buffer = ByteArray(64 * 1024)
var total = 0L
while (true) {
val count = input.read(buffer)
if (count < 0) break
if (count == 0) continue
total += count
require(total <= max) { "Choose an APK up to 50 MiB." }
hash.update(buffer, 0, count)
output?.write(buffer, 0, count)
}
require(total > 0) { "This file is empty." }
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
}
}
@@ -0,0 +1,58 @@
package meghdad.pakkit.transfer
import java.io.InputStream
import java.security.MessageDigest
import meghdad.pakkit.apk.ApkRules
/** Deliberately small HTTP/1.1 subset: one request per socket, no pipelining or chunked uploads. */
object HttpProtocol {
data class Request(val method: String, val path: String, val headers: Map<String, String>)
fun read(input: InputStream): Request {
var total = 0
fun line(): String {
val out = StringBuilder()
while (true) {
val b = input.read()
require(b >= 0 && ++total <= 8192) { "Invalid request headers" }
if (b == 13) {
require(input.read() == 10)
total++
return out.toString()
}
require(b in 32..126 && out.length < 4096) { "Invalid request headers" }
out.append(b.toChar())
}
}
val first = line().split(' ')
require(first.size == 3 && first[2] == "HTTP/1.1" && first[0] in setOf("GET", "POST"))
require(first[1].startsWith('/') && !first[1].startsWith("//"))
val headers = mutableMapOf<String, String>()
while (true) {
val next = line()
if (next.isEmpty()) break
val separator = next.indexOf(':')
require(separator > 0)
val name = next.substring(0, separator).lowercase()
require(name.matches(Regex("[a-z0-9-]+")) && name !in headers)
headers[name] = next.substring(separator + 1).trim()
}
require("transfer-encoding" !in headers && "expect" !in 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 uploadLength(headers: Map<String, String>): Long {
require(headers["content-type"] == "application/octet-stream") { "Send a complete APK" }
val raw = headers["content-length"] ?: error("Content length required")
require(raw.matches(Regex("[0-9]+"))) { "Invalid content length" }
val size = raw.toLongOrNull() ?: error("Invalid content length")
require(size in 1..ApkRules.MAX_BYTES) { "Choose an APK up to 50 MiB" }
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)
}
}