feat: make Pakkit a standalone Wear OS APK installer

- Replace companion app transport with local Wi-Fi receiving sessions
- Add branded web upload UI, private links, QR codes, and live progress
- Preserve explicit watch review and system installation consent
- Add bounded uploads, session expiry, authentication, and cleanup
- Validate Watch 7 installation and document release requirements
This commit is contained in:
Meghdad committed 2026-10-15 17:47:15 +03:30
1 parent 6ce4f924b7
commit 4d5d0b4165
48 files changed
+748 -1125

No files matched your search

+23 -33
View File
@@ -1,50 +1,40 @@
# Pakkit
# Pakkit — Pocket to Wrist.
**Pocket to Wrist.** A phone-to-Wear OS APK companion with an original luminous parcel identity, electric violet, mint and midnight themes, and explicit watch-side consent.
One standalone Wear OS app. A browser on your Wi-Fi. No companion app.
Pack it. Send it. Wear it. See [the implemented brand system](design/README.md) and the supplied [creative reference](design/brand-concept.png).
Pakkit starts a ten-minute receiving session on the watch, shows a private URL and QR code, and serves its own responsive web interface. Select a complete APK in the browser, send it directly to the watch, review it there, and approve the official Android installer. No ADB, root or developer options are used by the application. Play publication remains subject to permission declaration and review.
**Status: implemented device-validation build, not a production-certified or Play-approved release.** No debugging, root, hidden APIs, automatic installation, APK marketplace or security bypass appears in the consumer flow. Universal no-setup sideloading on Wear OS is not technically guaranteed. See [the feasibility decision](docs/FEASIBILITY.md) before making product claims.
## Use
## What is implemented
1. Install Pakkit on a supported Wear OS watch. The current build is a development APK; a Play listing has not been published.
2. Allow Pakkit to request installations using the watch’s system permission screen. If firmware does not expose this permission, use Google Play instead.
3. Connect the watch and browser device to the same trusted Wi-Fi, then tap **Start receiving**.
4. Scan the QR code or enter the full private link. If you enter just the address, enter the session key shown after `#` on the watch.
5. Select one complete `.apk` up to 50 MiB. Transfer progress is shown on both devices. Review the package and approve installation on the watch.
6. End the session or let it expire. A fresh session has a new address/key. Turn off development wireless debugging after testing; it is unrelated to Pakkit’s receiving session.
- Cohesive vector launcher/splash/parcel artwork, themed native components, a persisted phone appearance chooser, finite motion, and a midnight round-watch interface.
- Separate phone (`app`) and round-screen watch (`wear`) applications with the same application ID and distinct version codes.
- Pakkit capability discovery over Google's Wearable Data Layer; nonce-based live capability checks and explicit selection when multiple watches are available.
- Android's file picker, private APK storage, bounded streaming (50 MiB), archive/package inspection, signing-metadata checks, SHA-256 transfer integrity, API/ABI/storage preflight.
- Persistent, retried work and Data Layer asset syncing. No fabricated percentages or success states. One active transfer per phone and one active received APK per watch.
- Watch review and explicit install action, public PackageInstaller sessions with required user action, system confirmation handoff, optional approval notification, and structured installation results.
- Hardware/firmware limitations, unsupported package formats, errors, transfer history, privacy explanation and a Google Play fallback.
Local HTTP is **not encrypted**. The private link restricts access but does not protect against an attacker on the network. Use trusted Wi-Fi, keep the link private and install only apps you trust. Guest/client-isolated networks, VPNs and browser local-network restrictions can prevent access. Internet access and a paired phone are not needed for the transfer itself.
## Build
Use Android Studio's Java 21 runtime, Android SDK 36.1, and the included Gradle wrapper. Both apps support Android API 31+ and target API 36.
Java 21, Android SDK 36.1, min SDK 31, target SDK 36. Application ID `meghdad.pakkit`, version `0.2.0` / `100003`.
```sh
./gradlew :app:assembleDebug :wear:assembleDebug :shared:testDebugUnitTest :app:lintDebug :wear:lintDebug
./gradlew :wear:assembleDebug :shared:testDebugUnitTest :wear:lint :wear:bundleRelease
```
Google Maven returned HTTP 404 in the original development environment. An **optional**, explicitly selected mirror is supported; Google's repository remains the default:
Optional mirror when Google Maven is unavailable: `-PpakkitGoogleMavenMirror=https://maven.aliyun.com/repository/google`. Review dependency provenance in your release environment.
```sh
./gradlew :app:assembleDebug :wear:assembleDebug -PpakkitGoogleMavenMirror=https://maven.aliyun.com/repository/google
```
- Debug APK: `wear/build/outputs/apk/debug/wear-debug.apk`
- Release AAB: `wear/build/outputs/bundle/release/wear-release.aab`
- Release signing: see [release preparation](docs/RELEASE.md). No signing secrets are included.
Review mirror provenance and validate dependency checksums through your trusted build environment before production distribution. Dependency versions are pinned; no dynamically versioned libraries are used.
## Structure
Open both app modules in Android Studio. Install the phone build on the phone and the watch build on a **paired** Wear OS device, using the same signing certificate. Open the watch app first and allow external installs if its firmware exposes that setting. Refresh the phone connection. A reachable watch with the install capability and source approval is required before sending.
- `wear`: foreground Wi-Fi session, local HTTP server, bundled web assets, round watch UI, source approval and PackageInstaller consent.
- `shared`: bounded HTTP parsing, package inspection, integrity, storage, native design primitives and unit tests.
- `qa/fixture`: harmless signed test app, staged only into instrumentation assets; never included in the consumer app.
APK outputs: `app/build/outputs/apk/debug/app-debug.apk` and `wear/build/outputs/apk/debug/wear-debug.apk`. Release bundles are produced with `:app:bundleRelease :wear:bundleRelease`. Release signing uses optional environment variables described in [RELEASE.md](docs/RELEASE.md); without them bundles remain unsigned.
The former phone module and Data Layer/WorkManager transport have been removed. Historical companion screenshots are retained as design history; current screenshots are in `docs/screenshots/standalone`.
## Development guide
- `shared`: package inspection, bounded IO, protocol, persistence, workers, and visual primitives.
- `app`: file selection, connection, file review, activity and guidance.
- `wear`: review, unknown-source settings, installation and result receiver.
- [Architecture and security](docs/ARCHITECTURE.md)
- [Feasibility and official sources](docs/FEASIBILITY.md)
- [Release preparation](docs/RELEASE.md)
- [Validation record and physical-device checklist](docs/VALIDATION.md)
Never replace a real capability, transfer result or installer result with a timed simulation. Do not introduce ADB pairing, privileged installation or security-setting automation to make an unsupported watch appear supported. Test-only emulator tooling is distinct from consumer functionality.
[Feasibility and platform evidence](docs/FEASIBILITY.md) · [Architecture/security](docs/ARCHITECTURE.md) · [Validation](docs/VALIDATION.md) · [Brand](design/README.md) · [Privacy](docs/PRIVACY.md)
-1
View File
@@ -1 +0,0 @@
/build
-49
View File
@@ -1,49 +0,0 @@
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 = 100001
versionName = "0.1.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
if (listOf(releaseKey, releaseStorePassword, releaseAlias, releaseKeyPassword).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"), "../proguard-rules.pro") } }
compileOptions { sourceCompatibility = JavaVersion.VERSION_11; targetCompatibility = JavaVersion.VERSION_11 }
}
dependencies {
implementation(project(":shared"))
testImplementation(libs.junit)
androidTestImplementation(libs.androidx.espresso.core)
androidTestImplementation(libs.androidx.junit)
}
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)
}
@@ -1,107 +0,0 @@
package meghdad.pakkit
import android.app.Activity
import android.content.Intent
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import meghdad.pakkit.core.Design
import meghdad.pakkit.core.BrandPalette
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.matcher.ViewMatchers.withText
import meghdad.pakkit.core.Packages
import meghdad.pakkit.core.Store
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import java.io.File
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
@RunWith(AndroidJUnit4::class)
class ProductInstrumentedTest {
private val instrumentation get() = InstrumentationRegistry.getInstrumentation()
private val context get() = instrumentation.targetContext
private fun texts(view: View): List<TextView> = when(view) {
is ViewGroup -> (0 until view.childCount).flatMap { texts(view.getChildAt(it)) }
is TextView -> listOf(view)
else -> emptyList()
}
@Test fun navigationAndRecreationRetainSelectedPage() {
val monitor=instrumentation.addMonitor(MainActivity::class.java.name,null,false)
context.startActivity(Intent(context,MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
val activity=monitor.waitForActivityWithTimeout(5000) as Activity
instrumentation.runOnMainSync {
assertEquals("Pocket to Wrist.", activity.findViewById<TextView>(R.id.page_heading).text.toString())
activity.findViewById<View>(R.id.nav_guide).performClick()
assertEquals("Good to know.", activity.findViewById<TextView>(R.id.page_heading).text.toString())
activity.recreate()
}
val recreated=monitor.waitForActivityWithTimeout(5000)
assertNotNull(recreated)
instrumentation.runOnMainSync {
assertEquals("Good to know.", recreated.findViewById<TextView>(R.id.page_heading).text.toString())
recreated.finish()
}
instrumentation.removeMonitor(monitor)
}
@Test fun themeChooserAppliesAndPersistsMidnightTheme() {
val original = Design.themeMode(context)
Design.setThemeMode(context, "light")
val monitor = instrumentation.addMonitor(MainActivity::class.java.name, null, false)
try {
context.startActivity(Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
val light = monitor.waitForActivityWithTimeout(5000)
assertNotNull(light)
instrumentation.runOnMainSync {
assertEquals(BrandPalette.Light.text, light.findViewById<TextView>(R.id.page_heading).currentTextColor)
light.findViewById<View>(R.id.appearance).performClick()
}
onView(withText("Midnight dark")).perform(click())
val dark = monitor.waitForActivityWithTimeout(5000)
assertNotNull(dark)
instrumentation.runOnMainSync {
assertEquals("dark", Design.themeMode(context))
assertEquals(BrandPalette.Dark.text, dark.findViewById<TextView>(R.id.page_heading).currentTextColor)
dark.recreate()
}
val restored = monitor.waitForActivityWithTimeout(5000)
assertNotNull(restored)
instrumentation.runOnMainSync {
assertEquals(BrandPalette.Dark.text, restored.findViewById<TextView>(R.id.page_heading).currentTextColor)
restored.finish()
}
} finally {
instrumentation.removeMonitor(monitor)
Design.setThemeMode(context, original)
}
}
@Test fun readsSignedCompleteWearApk() {
val file=File(context.cacheDir,"fixture.apk")
try {
val digest=instrumentation.context.assets.open("fixture.apk").use { input -> file.outputStream().use { meghdad.pakkit.core.TransferRules.copyBounded(input,it).second } }
val apk=Packages.inspect(context,file,digest)
assertEquals("meghdad.pakkit.fixture",apk.packageName)
assertTrue(apk.wear)
assertEquals(31,apk.minSdk)
assertTrue(apk.bytes>0)
} finally { file.delete() }
}
@Test fun rejectsOwnPackageForSelfUpdates() {
val file=File(context.applicationInfo.sourceDir)
val failure=runCatching { Packages.inspect(context,file,"test") }.exceptionOrNull()
assertNotNull(failure)
assertTrue(failure!!.message.orEmpty().contains("Google Play"))
}
@Test fun rejectsNonApkArchivesAndPathTraversal() {
val file=File(context.cacheDir,"invalid.apk")
ZipOutputStream(file.outputStream()).use { it.putNextEntry(ZipEntry("readme.txt")); it.write("hello".toByteArray()); it.closeEntry() }
try {
assertNotNull(runCatching { Packages.inspect(context,file,"test") }.exceptionOrNull())
assertNotNull(runCatching { Store(context).file("../outside") }.exceptionOrNull())
} finally { file.delete() }
}
}
-7
View File
@@ -1,7 +0,0 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<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">
<activity android:name=".MainActivity" android:exported="true">
<intent-filter><action android:name="android.intent.action.MAIN"/><category android:name="android.intent.category.LAUNCHER"/></intent-filter>
</activity>
</application>
</manifest>
@@ -1,428 +0,0 @@
package meghdad.pakkit
import android.app.Activity
import android.app.AlertDialog
import android.app.Dialog
import android.content.Intent
import android.content.SharedPreferences
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.Gravity
import android.view.View
import android.widget.*
import androidx.work.*
import com.google.android.gms.wearable.*
import meghdad.pakkit.core.*
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.util.UUID
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
class MainActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeListener {
private val io = Executors.newSingleThreadExecutor()
private val main = Handler(Looper.getMainLooper())
private val colors by lazy { Design.palette(this) }
private lateinit var store: Store
private lateinit var content: LinearLayout
private lateinit var scroll: ScrollView
private var renderedPage = -1
private var page = 0
private var finding = false
private var importing = false
private var watch: Node? = null
private var capabilities: DataMap? = null
private var capabilitiesReceivedAt = 0L
private var connectionText = "Open Pakkit on your paired watch to begin."
private var message: String? = null
private var nonce = ""
private var appearanceDialog: Dialog? = null
private val redraw = Runnable { if (!isDestroyed) render() }
private val listener = DataClient.OnDataChangedListener { events ->
for (e in events) {
if (e.type == DataEvent.TYPE_CHANGED && e.dataItem.uri.path?.startsWith("/pakkit/cap/") == true) {
val map = DataMapItem.fromDataItem(e.dataItem).dataMap
if (e.dataItem.uri.host == watch?.id && map.getString("nonce") == nonce) {
capabilities = map
capabilitiesReceivedAt = android.os.SystemClock.elapsedRealtime()
connectionText = "Your watch is connected. You’re ready to send."
finding = false
render()
}
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
setTheme(if (Design.isDark(this)) R.style.Theme_Pakkit_Dark else R.style.Theme_Pakkit_Light)
super.onCreate(savedInstanceState)
store = Store(this)
store.clean()
page = savedInstanceState?.getInt("page") ?: 0
render()
savedInstanceState?.getInt("scroll")?.let { y -> scroll.post { scroll.scrollTo(0, y) } }
}
override fun onSaveInstanceState(outState: Bundle) {
outState.putInt("page", page)
outState.putInt("scroll", scroll.scrollY)
super.onSaveInstanceState(outState)
}
override fun onResume() {
super.onResume()
store.prefs.registerOnSharedPreferenceChangeListener(this)
Wearable.getDataClient(this).addListener(listener).addOnFailureListener {
connectionText = "Google Play services is unavailable. Reopen Pakkit after it’s available."
render()
}
discover()
}
override fun onPause() {
store.prefs.unregisterOnSharedPreferenceChangeListener(this)
Wearable.getDataClient(this).removeListener(listener)
super.onPause()
}
override fun onDestroy() { appearanceDialog?.dismiss(); main.removeCallbacksAndMessages(null); io.shutdown(); super.onDestroy() }
override fun onSharedPreferenceChanged(prefs: SharedPreferences?, key: String?) {
if (key == "outgoing" || key == "history" || key == null) {
main.removeCallbacks(redraw)
main.postDelayed(redraw, 32)
}
}
private fun dp(n: Int) = Design.dp(this, n)
private fun text(value: String, size: Float = 16f, color: Int = colors.text, bold: Boolean = false) = Design.text(this, value, size, color, bold)
private fun add(v: View, parent: LinearLayout = content, top: Int = 0) {
parent.addView(v, LinearLayout.LayoutParams(-1, v.layoutParams?.height ?: -2).apply { topMargin = dp(top) })
}
private fun card(color: Int = colors.surface) = Design.column(this).apply {
setPadding(dp(20), dp(20), dp(20), dp(20))
background = Design.shape(color, dp(26).toFloat(), colors.border)
}
private fun action(label: String, primary: Boolean = true, callback: () -> Unit) = Design.button(this, label, primary, callback)
private fun icon(glyph: Glyph, tint: Int = colors.accent, size: Int = 24) = ImageView(this).apply {
setImageDrawable(GlyphDrawable(glyph, tint))
layoutParams = LinearLayout.LayoutParams(dp(size), dp(size))
importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
}
private fun heading(value: String, caption: String) {
add(text(value, 38f, bold = true).apply { id = R.id.page_heading; letterSpacing = -.045f }, top = 26)
add(text(caption, 15f, colors.secondary), top = 10)
}
private fun render(animate: Boolean = false) {
if (isDestroyed || isFinishing) return
val y = if (::scroll.isInitialized && renderedPage == page) scroll.scrollY else 0
renderedPage = page
val root = Design.column(this).apply { background = AuroraDrawable(colors) }
root.setOnApplyWindowInsetsListener { v, insets ->
val bars = insets.getInsets(android.view.WindowInsets.Type.systemBars())
v.setPadding(bars.left, bars.top, bars.right, bars.bottom)
insets
}
scroll = ScrollView(this).apply { isFillViewport = true; clipToPadding = false; isVerticalScrollBarEnabled = false }
val frame = FrameLayout(this)
content = Design.column(this).apply { setPadding(dp(20), dp(18), dp(20), dp(24)) }
frame.addView(content, FrameLayout.LayoutParams(minOf(resources.displayMetrics.widthPixels, dp(640)), -2, Gravity.TOP or Gravity.CENTER_HORIZONTAL))
scroll.addView(frame)
root.addView(scroll, LinearLayout.LayoutParams(-1, 0, 1f))
header()
when (page) { 0 -> transferPage(); 1 -> activityPage(); else -> guidePage() }
root.addView(navigation())
setContentView(root)
root.requestApplyInsets()
scroll.post { scroll.scrollTo(0, y) }
if (animate) Design.entrance(content)
}
private fun header() {
val row = LinearLayout(this).apply { gravity = Gravity.CENTER_VERTICAL }
row.addView(ImageView(this).apply {
setImageResource(meghdad.pakkit.core.R.drawable.pakkit_icon)
importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
}, LinearLayout.LayoutParams(dp(48), dp(48)).apply { marginStart = -dp(8) })
row.addView(text("Pakkit", 27f, bold = true).apply { letterSpacing = -.05f }, LinearLayout.LayoutParams(0, -2, 1f))
row.addView(ImageButton(this).apply {
id = R.id.appearance
setImageDrawable(GlyphDrawable(Glyph.APPEARANCE, colors.text))
scaleType = ImageView.ScaleType.FIT_CENTER
setPadding(dp(14), dp(14), dp(14), dp(14))
background = android.graphics.drawable.RippleDrawable(android.content.res.ColorStateList.valueOf(0x227150EF), Design.shape(colors.surface, dp(18).toFloat(), colors.border), null)
contentDescription = "Appearance: ${Design.themeMode(this@MainActivity)}. Change theme"
setOnClickListener { appearance() }
}, LinearLayout.LayoutParams(dp(48), dp(48)))
add(row)
}
private fun navigation(): View {
val frame = FrameLayout(this).apply { background = Design.shape(colors.surface, 0f, colors.border) }
val row = LinearLayout(this).apply { setPadding(dp(16), dp(8), dp(16), dp(8)) }
val labels = listOf("Transfer", "Activity", "Guide")
val glyphs = listOf(Glyph.TRANSFER, Glyph.HISTORY, Glyph.GUIDE)
val ids = listOf(R.id.nav_transfer, R.id.nav_activity, R.id.nav_guide)
labels.forEachIndexed { index, label ->
row.addView(action(label, false) { if (page != index) { page = index; render(animate = true) } }.apply {
id = ids[index]
isSelected = page == index
textSize = 12f
minHeight = dp(60)
setPadding(dp(8), dp(8), dp(8), dp(8))
background = android.graphics.drawable.RippleDrawable(android.content.res.ColorStateList.valueOf(0x227150EF), Design.shape(if (isSelected) colors.accentSoft else Color.TRANSPARENT, dp(18).toFloat()), null)
setTextColor(if (isSelected) colors.accent else colors.secondary)
val glyph = GlyphDrawable(glyphs[index], if (isSelected) colors.accent else colors.secondary).apply { setBounds(0, 0, dp(21), dp(21)) }
setCompoundDrawables(null, glyph, null, null)
compoundDrawablePadding = dp(5)
}, LinearLayout.LayoutParams(0, -2, 1f).apply { marginEnd = dp(5) })
}
frame.addView(row, FrameLayout.LayoutParams(minOf(resources.displayMetrics.widthPixels, dp(640)), -2, Gravity.CENTER))
return frame
}
private fun appearance() {
val dialog = Dialog(this)
appearanceDialog = dialog
val sheet = Design.column(this).apply { setPadding(dp(24), dp(26), dp(24), dp(20)) }
add(text("Make it yours.", 25f, bold = true), sheet)
add(text("Choose your atmosphere.", 14f, colors.secondary), sheet, 8)
listOf("system" to "Follow device theme", "light" to "Lavender light", "dark" to "Midnight dark").forEach { (mode, label) ->
val selected = Design.themeMode(this) == mode
add(action(label, false) {
Design.setThemeMode(this, mode)
dialog.dismiss()
recreate()
}.apply {
gravity = Gravity.CENTER_VERTICAL or Gravity.START
isSelected = selected
if (selected) {
background = Design.shape(colors.accentSoft, dp(18).toFloat(), colors.accent)
setTextColor(colors.accent)
setCompoundDrawablesRelative(null, null, GlyphDrawable(Glyph.CHECK, colors.accent).apply { setBounds(0, 0, dp(20), dp(20)) }, null)
}
}, sheet, 14)
}
add(action("Close", false) { dialog.dismiss() }, sheet, 20)
dialog.setContentView(ScrollView(this).apply { addView(sheet) })
dialog.window?.setBackgroundDrawable(Design.shape(colors.surface, dp(28).toFloat()))
dialog.show()
dialog.window?.setLayout(minOf(resources.displayMetrics.widthPixels - dp(40), dp(420)), -2)
}
private fun transferPage() {
val job = store.read("outgoing")
if (job != null) {
heading("A little closer.", getString(meghdad.pakkit.core.R.string.brand_secondary_tagline))
fileCard(job)
connectionCard(compact = true)
} else {
heading(getString(meghdad.pakkit.core.R.string.brand_tagline), "Your next favorite app. A little closer.")
connectionCard()
val box = card()
val row = LinearLayout(this).apply { gravity = Gravity.CENTER_VERTICAL }
row.addView(icon(Glyph.FILE, size = 30))
row.addView(Design.column(this).apply {
add(text("A new wrist essential.", 19f, bold = true), this)
add(text("Single APK · up to 50 MB", 13f, colors.secondary), this, 6)
}, LinearLayout.LayoutParams(0, -2, 1f).apply { marginStart = dp(14) })
add(row, box)
add(action(if (importing) "Reading your APK…" else "Choose an APK") { pick() }.apply { isEnabled = !importing }, box, 18)
add(box, top = 16)
}
message?.let { notice("A small detour", it, warning = true) }
add(text(getString(meghdad.pakkit.core.R.string.brand_secondary_tagline), 13f, colors.secondary, true).apply { gravity = Gravity.CENTER }, top = 24)
add(text("Only send apps you trust. You approve installation on your watch.", 12f, colors.secondary).apply { gravity = Gravity.CENTER }, top = 8)
}
private fun connectionCard(compact: Boolean = false) {
val box = card()
if (!compact) box.background = Design.gradient(if (colors.dark) intArrayOf(0xFF24203E.toInt(), 0xFF112A31.toInt()) else intArrayOf(0xFFF0E9FF.toInt(), 0xFFE2F7F6.toInt()), dp(26).toFloat())
val row = LinearLayout(this).apply { gravity = Gravity.CENTER_VERTICAL }
row.addView(icon(Glyph.WATCH, if (capabilities != null) colors.mint else colors.accent, 20))
row.addView(text(if (capabilities != null) "Connected" else if (finding) "Finding your watch" else "Your watch", 12f, colors.secondary, true), LinearLayout.LayoutParams(0, -2, 1f).apply { marginStart = dp(8) })
row.addView(text("WEAR OS", 10f, colors.secondary, true).apply { letterSpacing = .12f })
add(row, box)
if (!compact) add(ParcelSceneView(this).apply { active = finding; layoutParams = LinearLayout.LayoutParams(-1, dp(174)) }, box, 4)
add(text(if (finding) "Making the introduction…" else watch?.displayName ?: "Let’s find your watch.", if (compact) 17f else 20f, bold = true), box, if (compact) 14 else 0)
add(text(connectionText, 13f, colors.secondary), box, 8)
add(action(if (finding) "Looking for Pakkit…" else if (capabilities != null) "Refresh connection" else "Connect a watch", false) { discover() }.apply { isEnabled = !finding }, box, 16)
add(box, top = 20)
capabilities?.let { cap ->
if (!supported(cap)) notice("A different route", "This watch’s software does not expose the approval controls Pakkit needs. Install compatible apps through Google Play on the watch.", true)
else if (!cap.getBoolean("allowed")) notice("One permission, on your watch", "Open Pakkit on your watch and tap “Allow installs”. Then refresh the connection here.")
}
}
private fun notice(title: String, description: String, warning: Boolean = false) {
val box = card(if (warning) colors.errorSoft else colors.accentSoft)
val tint = if (warning) colors.error else colors.accent
add(text(title, 16f, tint, true), box)
add(text(description, 14f, if (warning) colors.error else colors.text), box, 8)
add(box, top = 16)
}
private fun fileCard(job: JSONObject) {
val apk = Apk.from(job.getJSONObject("apk"))
val state = job.optString("state", "draft")
val box = card()
val success = state == "installed"
val failed = state == "failed"
val title = when (state) {
"draft" -> "Packed and ready"
"sending" -> "Preparing your parcel"
"syncing" -> "On its way"
"receiving" -> "A final check, on your watch"
"ready" -> "Ready on your wrist"
"confirm" -> "Over to you"
"installing" -> "With the system installer"
"installed" -> "Right where it belongs."
"declined" -> "Dismissed on your watch"
else -> "A small detour"
}
val row = LinearLayout(this).apply { gravity = Gravity.CENTER_VERTICAL }
row.addView(icon(if (success) Glyph.CHECK else if (failed) Glyph.ALERT else Glyph.FILE, if (success) colors.mint else if (failed) colors.error else colors.accent, 28))
row.addView(Design.badge(this, if (success) "Installed" else if (failed) "Needs attention" else "Your APK", positive = success, warning = failed), LinearLayout.LayoutParams(-2, -2).apply { marginStart = dp(12) })
add(row, box)
add(text(title, 23f, bold = true), box, 18)
add(text(apk.label, 19f, bold = true), box, 18)
add(text("${apk.version} · ${"%.1f".format(apk.bytes / 1048576.0)} MB", 13f, colors.secondary), box, 6)
add(text(apk.packageName, 12f, colors.secondary), box, 6)
if (state == "draft") {
add(text(if (apk.wear) "Watch support declared. Hardware is checked before sending." else "Watch support is unverified. This app may not fit or work on a round screen.", 13f, if (apk.wear) colors.secondary else colors.error), box, 16)
add(text("Package details are readable. This is not a malware scan or a guarantee of compatibility.", 12f, colors.secondary), box, 10)
add(action("Send to my watch") { send(job) }.apply { isEnabled = capabilities?.let { supported(it) && it.getBoolean("allowed") } == true }, box, 20)
add(action("Choose another file", false) { discard(job); pick() }, box, 8)
} else {
add(text(job.optString("detail"), 14f, colors.secondary), box, 16)
transferSteps(state, box)
if (state in setOf("installed", "failed", "declined")) add(action("Choose another APK") { discard(job); pick() }, box, 20)
else {
if (state in setOf("sending", "syncing", "receiving")) add(Design.progress(this), box, 14)
add(text("Open Pakkit on your watch to continue. Brief disconnections are handled by syncing. Files expire 24 hours after selection.", 12f, colors.secondary), box, 14)
add(action("Transfer help", false) { page = 2; render(animate = true) }, box, 12)
}
}
add(box, top = 22)
}
private fun transferSteps(state: String, parent: LinearLayout) {
val current = when (state) { "sending", "syncing", "receiving" -> 1; "ready", "confirm", "installing" -> 2; "installed" -> 3; else -> 0 }
val row = LinearLayout(this)
listOf("Choose", "Send", "Approve", "Wear").forEachIndexed { index, label ->
row.addView(Design.column(this).apply {
gravity = Gravity.CENTER
if (index < current) addView(icon(Glyph.CHECK, colors.accent, 18))
else addView(text("0${index + 1}", 13f, if (index == current) colors.accent else colors.secondary, true).apply { gravity = Gravity.CENTER })
addView(text(label, 11f, if (index <= current) colors.text else colors.secondary).apply { gravity = Gravity.CENTER; setPadding(0, dp(6), 0, 0) })
}, LinearLayout.LayoutParams(0, -2, 1f))
}
add(row, parent, 22)
}
private fun activityPage() {
heading("Little journeys.", "Your last 20 transfers, kept on this phone.")
val entries = JSONArray(store.prefs.getString("history", "[]"))
if (entries.length() == 0) {
add(ParcelSceneView(this).apply { layoutParams = LinearLayout.LayoutParams(-1, dp(170)) }, top = 24)
add(text("The first one is yours.", 24f, bold = true).apply { gravity = Gravity.CENTER }, top = 18)
add(text("Send an APK and follow its journey here, from your pocket to your wrist.", 15f, colors.secondary).apply { gravity = Gravity.CENTER }, top = 12)
add(action("Choose your first APK") { page = 0; render(animate = true); pick() }, top = 24)
} else {
for (i in 0 until entries.length()) {
val entry = entries.getJSONObject(i)
val box = card()
val state = entry.optString("state")
add(Design.badge(this, when (state) { "installed" -> "Installed"; "failed" -> "Needs attention"; "declined" -> "Dismissed"; else -> "In progress" }, state == "installed", state == "failed"), box)
add(text(entry.getString("label"), 20f, bold = true), box, 14)
add(text(entry.getString("detail"), 14f, colors.secondary), box, 8)
add(text(android.text.format.DateFormat.format("MMM d · HH:mm", entry.getLong("time")).toString(), 12f, colors.secondary), box, 12)
add(box, top = 16)
}
add(action("Clear activity", false) { store.prefs.edit().remove("history").apply() }, top = 20)
}
}
private fun guidePage() {
heading("Good to know.", "A little bridge. You’re always in control.")
val sections = listOf(
"Make the introduction" to "Pair your watch with its normal companion app, then install Pakkit from Google Play on both devices. Open Pakkit on your watch and allow installs if its software offers that setting.",
"Pack it. Send it." to "Choose a complete APK from a source you trust. Pakkit checks readable signing metadata, file size, Android version and processor support. Split APKs, APKM, XAPK and app bundles aren’t supported.",
"Wear it. With your approval." to "When the APK is ready, review it in Pakkit on your watch and tap Install. Follow the system’s approval screen. Receiving a file never installs it automatically.",
"Every watch is different" to "Some watch firmware does not offer external installation controls. Pakkit cannot enable them. Google Play on the watch is the supported alternative. Phone apps may also be difficult to use on a round screen.",
"Give your parcel a moment" to "Keep the devices charged and connected. Google Play services manages syncing; a byte percentage isn’t available. Files expire 24 hours after selection. If a connection is lost, reopen both apps and refresh.",
"Your files, thoughtfully handled" to "No Pakkit account, ads or analytics. APKs are stored privately and shared using Google Play services. The Data Layer may route encrypted data through Google servers. Temporary APKs are removed after completion or expiry. You can clear activity here.",
"Trust comes first" to "Pakkit does not certify an APK’s safety. System protections, developer verification, device policy or Play Protect may block installation. Pakkit respects those decisions and does not offer debugging or security bypasses."
)
sections.forEachIndexed { index, (title, body) ->
val box = card()
add(text("0${index + 1}", 12f, colors.accent, true), box)
add(text(title, 19f, bold = true), box, 12)
add(text(body, 14f, colors.secondary), box, 10)
add(box, top = 16)
}
add(action("Open Google Play", false) { openPlay() }, top = 20)
add(text(getString(meghdad.pakkit.core.R.string.brand_secondary_tagline), 14f, colors.accent, true).apply { gravity = Gravity.CENTER }, top = 28)
add(text("Pakkit 0.1 · Device validation build", 12f, colors.secondary).apply { gravity = Gravity.CENTER }, top = 10)
}
private fun supported(cap: DataMap) = cap.getBoolean("installer") && (cap.getBoolean("settings") || cap.getBoolean("allowed"))
private fun discover() {
if(finding) return
finding=true; capabilities=null; connectionText="Looking for Pakkit on nearby paired watches."; render()
Wearable.getCapabilityClient(this).getCapability(Link.CAPABILITY,CapabilityClient.FILTER_REACHABLE)
.addOnSuccessListener { info ->
if (isDestroyed || isFinishing) return@addOnSuccessListener
val nodes=info.nodes.sortedBy { it.displayName }
if(nodes.isEmpty()) { finding=false; watch=null; connectionText="No watch found. Install and open Pakkit on your paired watch, then try again."; render() }
else if(nodes.size==1) probe(nodes.first())
else AlertDialog.Builder(this).setTitle("Choose your watch").setItems(nodes.map { it.displayName }.toTypedArray()) { _,i -> probe(nodes[i]) }
.setOnCancelListener { finding=false; render() }.show()
}.addOnFailureListener { finding=false; connectionText="Couldn’t reach your watch. Check Google Play services and the companion connection."; render() }
}
private fun probe(node: Node) {
watch=node; nonce=UUID.randomUUID().toString(); val request=nonce
Wearable.getMessageClient(this).sendMessage(node.id,"/pakkit/probe",nonce.toByteArray()).addOnFailureListener {
if(nonce==request) { finding=false; connectionText="Watch connection interrupted. Reopen Pakkit on your watch and retry."; render() }
}
main.postDelayed({ if(nonce==request && finding) { finding=false; connectionText="Your watch hasn’t replied. Open Pakkit there, then try again."; render() } },15000)
}
@Suppress("DEPRECATION")
private fun pick() {
message=null
startActivityForResult(Intent(Intent.ACTION_OPEN_DOCUMENT).apply { type="application/vnd.android.package-archive"; addCategory(Intent.CATEGORY_OPENABLE) },41)
}
@Deprecated("Platform result bridge")
override fun onActivityResult(requestCode: Int,resultCode: Int,data: Intent?) {
super.onActivityResult(requestCode,resultCode,data)
if(requestCode!=41 || resultCode!=RESULT_OK) return
val uri=data?.data ?: return
importing=true; render()
io.execute {
val id=UUID.randomUUID().toString(); val part=File(store.directory,"$id.part")
try {
require(Packages.free(this)>TransferRules.MAX_BYTES+20*1024*1024) { "Free some storage on your phone first." }
val hash=contentResolver.openInputStream(uri)?.use { input -> part.outputStream().use { TransferRules.copyBounded(input,it).second } } ?: error("Could not read this file.")
val apk=Packages.inspect(this,part,hash)
require(part.renameTo(store.file(id))) { "Could not save this file." }
store.write("outgoing",JSONObject().put("id",id).put("apk",apk.json()).put("created",System.currentTimeMillis()).put("state","draft"))
WorkManager.getInstance(this).enqueueUniqueWork("expire-$id",ExistingWorkPolicy.KEEP,
OneTimeWorkRequestBuilder<ExpireWorker>().setInitialDelay(24,TimeUnit.HOURS).setInputData(workDataOf("id" to id)).build())
} catch(e: Exception) { part.delete(); main.post { message=e.message ?: "Couldn’t read this APK." } }
main.post { importing=false; if(!isDestroyed) render() }
}
}
private fun send(job: JSONObject) {
val cap=capabilities ?: return
val node=watch ?: return
try {
require(android.os.SystemClock.elapsedRealtime()-capabilitiesReceivedAt < 120000) { "Refresh your watch connection before sending." }
require(supported(cap) && cap.getBoolean("allowed")) { "Allow installations in Pakkit on your watch first." }
val apk=Apk.from(job.getJSONObject("apk"))
Packages.checkForWatch(apk,cap.getInt("sdk"),cap.getStringArrayList("abis").orEmpty().toSet(),cap.getLong("free"))
require(TransferRules.fresh(job.optLong("created"),System.currentTimeMillis())) { "This file expired. Choose it again." }
val sendNow = {
val now=job.getLong("created")
job.put("target",node.id).put("created",now).put("state","sending").put("offer",Uri.Builder().scheme("wear").authority("*").path("/pakkit/offer/${job.getString("id")}").build().toString())
.put("detail","Preparing your file for Google Play services.")
store.write("outgoing",job)
store.history(job.getString("id"),apk.label,"sending","Preparing your file for transfer.")
WorkManager.getInstance(this).enqueueUniqueWork("send-${job.getString("id")}",ExistingWorkPolicy.KEEP,
OneTimeWorkRequestBuilder<SendWorker>().setInputData(workDataOf("id" to job.getString("id"))).build())
render()
}
AlertDialog.Builder(this).setTitle("Send ${apk.label}?")
.setMessage("Send this APK to ${node.displayName} using Google Play services. Only continue if you trust its source.${if(!apk.wear) "\n\nThis app does not declare watch support. It may not fit or work on your watch." else ""}\n\nYou’ll review and approve installation on the watch.")
.setNegativeButton("Keep here",null).setPositiveButton("Send") { _,_ -> sendNow() }.show()
} catch(e: Exception) { message=e.message; render() }
}
private fun discard(job: JSONObject) { store.file(job.getString("id")).delete(); store.clear("outgoing"); render() }
private fun openPlay() { runCatching { startActivity(Intent(Intent.ACTION_VIEW,Uri.parse("https://play.google.com/store/search?q=Wear%20OS&c=apps"))) }.onFailure { message="Open Google Play on your watch and search for compatible apps."; render() } }
}
-12
View File
@@ -1,12 +0,0 @@
# Add project specific R8 rules here.
# AGP will combine all keep rule files in src/main/keepRules to pass to R8
#
# For more details, see
# https://d.android.com/r/tools/r8/keep-rules
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
-1
View File
@@ -1 +0,0 @@
<resources><style name="Theme.Pakkit" parent="Theme.Pakkit.Dark"/></resources>
-1
View File
@@ -1 +0,0 @@
<resources><item name="page_heading" type="id"/><item name="nav_transfer" type="id"/><item name="nav_activity" type="id"/><item name="nav_guide" type="id"/><item name="appearance" type="id"/></resources>
-9
View File
@@ -1,9 +0,0 @@
<resources>
<style name="Theme.Pakkit" parent="Theme.Pakkit.Light"/>
<style name="Theme.Pakkit.Light" parent="android:style/Theme.Material.Light.NoActionBar">
<item name="android:fontFamily">sans</item><item name="android:windowLightStatusBar">true</item><item name="android:windowLightNavigationBar">true</item><item name="android:colorAccent">#6140D8</item><item name="android:windowBackground">#F6F5FC</item><item name="android:windowActionModeOverlay">true</item><item name="android:windowSplashScreenBackground">#090B17</item><item name="android:windowSplashScreenAnimatedIcon">@drawable/pakkit_icon</item>
</style>
<style name="Theme.Pakkit.Dark" parent="android:style/Theme.Material.NoActionBar">
<item name="android:fontFamily">sans</item><item name="android:windowLightStatusBar">false</item><item name="android:windowLightNavigationBar">false</item><item name="android:colorAccent">#BAA6FF</item><item name="android:windowBackground">#090B17</item><item name="android:windowActionModeOverlay">true</item><item name="android:windowSplashScreenBackground">#090B17</item><item name="android:windowSplashScreenAnimatedIcon">@drawable/pakkit_icon</item>
</style>
</resources>
@@ -1,17 +0,0 @@
package meghdad.pakkit
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}
+11 -7
View File
@@ -4,25 +4,25 @@ The supplied `brand-concept.png` is a creative reference, not a screen specifica
## Identity
An open parcel and a floating app tile form Pakkit's mark. Cyan and mint illuminate one face; electric violet lights the other. The detached tile suggests a small app making a deliberate journey. The same silhouette appears in the adaptive launcher, monochrome icon, splash, phone illustration and watch header. The work is implemented as vector paths, native shaders and reusable Android components; the reference board is never rendered as application UI.
An open parcel and a floating app tile form Pakkit's mark. Cyan and mint illuminate one face; electric violet lights the other. The detached tile suggests a small app making a deliberate journey. The same silhouette appears in the adaptive launcher, monochrome icon, splash, browser illustration and watch header. The work is implemented as vector paths, native shaders and reusable Android components; the reference board is never rendered as application UI.
## Color and typography
`BrandPalette` in `shared/.../Design.kt` provides semantic tokens for light and dark canvas, cards, body text, secondary text, borders, actions, mint statuses and errors. Principal colors: midnight `#090B17`, action purple `#7150EF`, mint `#68E9CF`, cyan `#37D7F2`. Action buttons use a readable violet gradient. Text colors are adapted rather than copying a bright accent onto every surface.
Lavender light uses subtly tinted backgrounds and white cards. Midnight dark uses restrained illumination, deep surfaces and soft lavender text. The phone follows the device theme by default; its appearance control offers explicit light and dark preferences and preserves the choice. The watch stays midnight in either system theme to limit lit pixels on OLED displays.
Lavender light uses subtly tinted backgrounds and white cards. Midnight dark uses restrained illumination, deep surfaces and soft lavender text. The web interface follows the browser’s color scheme and offers an in-session light/dark toggle. The watch stays midnight in either system theme to limit lit pixels on OLED displays.
Typography uses Android's native sans family with explicit 400/600/650 weights, slightly tightened large headings and scalable SP sizes. Copy remains real text, not outlined lettering. The scale is deliberate: phone headlines 38 SP, section titles 19–23 SP, body 14–16 SP; watch titles 21–25 SP and supporting text 12–14 SP. Small metadata remains scrollable. There are no fixed-height text containers.
Typography uses Android's native sans family with explicit 400/600/650 weights, slightly tightened large headings and scalable SP sizes. Copy remains real text, not outlined lettering. The scale is deliberate: watch titles 21–25 SP and supporting text 12–14 SP. Small metadata remains scrollable. There are no fixed-height text containers.
## Components and interaction
- `ParcelSceneView`: prebuilt parcel geometry, static radial lighting, a floating app tile and a finite 1.1-second entrance. No bitmap assets, blur layers or continuous particle simulation.
- `GlyphDrawable`: a consistent stroke family for navigation, watch, file, trust and status icons. Icons supplement text; decorative art is excluded from accessibility focus.
- Native buttons: gradient primary, tonal secondary, ripple feedback, meaningful disabled colors and platform confirmation haptics. Minimum height 52 DP on phone and 48 DP on watch.
- Phone cards: 26-DP corners, 20-DP padding, quiet borders and consistent spacing. Content is centered and bounded on wide windows. Navigation remains semantic and selected states are exposed to accessibility.
- Native buttons: gradient primary, tonal secondary, ripple feedback and platform confirmation haptics. Watch actions have a minimum height of 48 DP.
- Browser cards: quiet borders, violet actions, original parcel SVG, responsive spacing, semantic native controls, drag/drop and keyboard file selection. All assets are served by the watch.
- `RoundScrollView`: symmetric proportional watch margins, generous end padding, rotary scrolling and an on-demand scroll indicator following the bezel. TextClock updates with the platform; no custom clock loop.
- Scroll position is retained during ordinary status refreshes. New transfer stages on the watch return to the heading so the current decision remains discoverable.
- Motion respects system animation settings and battery saver. Decorative watch art is static. Phone transitions are short, finite and cancelled when detached or the window loses focus. Receiving progress remains indeterminate because the Data Layer does not supply a trustworthy byte percentage.
- Motion respects system animation settings and battery saver. Decorative watch art is static. Web motion is a finite entrance and short hover/press feedback, respecting prefers-reduced-motion. Byte progress reflects actual socket reads on the watch and XHR progress in the browser; verification and installation are distinct states.
## Product truth
@@ -30,6 +30,10 @@ Brand language must never imply a compatibility guarantee or a security bypass.
## Validation
Automated contrast checks cover normal body and secondary copy on all base surfaces, status badges and both action-gradient endpoints at 4.5:1 or better. Device tests exercise the actual appearance chooser and theme persistence, navigation restoration and the unchanged installation consent boundary. Full TalkBack and physical-watch accessibility validation remain release gates.
Automated contrast checks cover normal body and secondary copy on all base surfaces, status badges and both action-gradient endpoints at 4.5:1 or better. Tests exercise HTTP framing, upload authorization, actual streamed APK inspection and the installation consent boundary. Full TalkBack and physical-watch accessibility validation remain release gates.
Design references: [Wear accessibility](https://developer.android.com/training/wearables/accessibility), [round screen guidance](https://developer.android.com/design/ui/wear/guides/get-started/design-for-wearables), [Wear app quality](https://developer.android.com/docs/quality-guidelines/wear-app-quality), and [power guidance](https://developer.android.com/training/wearables/apps/power). These inform the implementation; their requirements are not a substitute for Play review or physical-device testing.
## Standalone web identity
`wear/src/main/assets/web` contains the real HTML/CSS/JS product. A luminous open-parcel SVG complements the native launcher mark. The two-column desktop composition becomes a single-column mobile journey; actual upload, verification, review, system-consent, error and success states use live watch responses. No mock status, screenshot-based control, remote dependency or perpetual animation appears in the browser UI. Historical phone components/screenshots are not current product flows.
+21 -22
View File
@@ -1,36 +1,35 @@
# Architecture and operating boundaries
# Standalone architecture and security
## Protocol v1
## Components and flow
Google Play services enforces matching app ID and certificate. The watch advertises `pakkit_watch_v1`. A reachable node is queried using `/pakkit/probe` with a random nonce. The watch publishes `/pakkit/cap/{node}` with that nonce, API, ABIs, available bytes and installation controls. The phone accepts only the selected node's fresh response. Capabilities expire for send purposes after two minutes.
WatchActivity → explicit Start receiving → ReceiveService → Wi-Fi network request → private IPv4 listener → private URL/QR → browser HTML/CSS/JS from watch → authenticated raw APK POST → bounded private file → Android archive inspection → ready state → watch Install → PackageInstaller → system consent → result receiver → browser status.
A selected document is copied from its content URI into app-private storage. The temporary filename is a generated UUID; URI-supplied paths and display names never determine a filesystem path. SHA-256 is computed while enforcing the size cap. The original document is not modified. Persisted URI permission and broad storage access are unnecessary.
`shared` contains protocol/inspection/storage/design code. `wear` owns the server and installer. The phone module, Play Services Data Layer and WorkManager have been removed. No Google services runtime, backend, account, mDNS or WebView is required. ZXing Core encodes the QR locally.
`SendWorker` publishes `/pakkit/offer/{UUID}`, containing target node, creation time, APK metadata, digest and an Asset. This publication means queued for sync, not delivered. Google Play services owns transport and retransmission; it can route through Google infrastructure. There is no percentage or speed estimate. There is no automatic installation.
## Session ownership
`LinkService` schedules unique `ReceiveWorker` work. The worker checks target, identifier and age; rejects a busy watch; bounds the received bytes; verifies digest and parsed package information; and renames the complete private file. Readiness is sent only after verification. The watch keeps a small recent-ID replay guard. Terminal and ready states are idempotent for a given active transfer. Assets are deleted after verification or a permanent failure, rather than retained as storage.
The user starts a connectedDevice foreground service while WatchActivity is visible. Wi-Fi is requested for up to 25 seconds; absent connectivity yields a recoverable message. A socket binds exclusively to the chosen Wi-Fi private IPv4 address and ephemeral port. The service is never exported, restarted automatically or started at boot. The ten-minute deadline starts at user initiation; a timed CPU wake lock covers the session without keeping the screen on. Losing that network ends the session. Stop closes accepted sockets, shuts down the bounded worker pool, unregisters the network callback, removes the URL and releases power resources.
The watch publishes `/pakkit/status/{UUID}` with target phone and an explicit state. The phone only accepts the current transfer ID from its selected destination node and monotonically increasing status revisions. A status publication worker retries temporary API errors. Phone and watch hold one current job each, plus phone-local history capped at 20 entries. SharedPreferences commits are used for the small durable records; files are not placed in preferences or WorkManager input. WorkManager persists bounded jobs and handles process restart.
The browser may continue watching installation results while the session remains active. Ending the network session does not cancel an already committed Android installation or delete a pending user review. A completed upload remains eligible for review for 24 hours; expired packages are removed when the app next opens. This is lazy cleanup, not a guaranteed background deletion deadline. Partial and rejected uploads are deleted immediately. Reboot/process death requires a new receiving session. No resume tokens are persisted for transfer recovery.
## Installation boundary
## HTTP boundary
Only a foreground button in the watch app creates a PackageInstaller session. The file's age, digest, metadata and hardware compatibility are checked again. The session requests `USER_ACTION_REQUIRED`. The status receiver is not exported. Its explicit mutable PendingIntent is scoped to the session and transfer ID; mutable extras are required for Android's installer result.
- Independent 192-bit SecureRandom URL-safe key per session, in the URL fragment so the initial HTTP request does not include it. JS removes the fragment from visible history after loading, keeps it only in memory and sends an Authorization bearer header for APIs. Reload without the key requires re-entering it or rescanning.
- All content is local. Strict self-only script/style/connect CSP, no framing, no referrer, no cache, no MIME sniffing, no CORS or external fonts/trackers.
- Exact Host check protects against DNS rebinding. Upload requires the watch page’s exact Origin and bearer token. No browser install/cancel-install endpoint exists.
- Parser limits headers to 8 KiB and lines to 4 KiB, rejects duplicate headers, invalid framing, transfer encoding, expectations and unsupported methods. Each socket serves one request then closes. Only fixed public asset routes are served; there is no user-controlled filesystem lookup.
- Raw octet-stream POST with positive Content-Length <=50 MiB. No multipart buffering, user filenames or extraction into filesystem paths. UUID private filename. One upload at a time; another review must be dismissed/completed first. Free-space preflight, streamed SHA-256, 64 KiB buffer, ZIP expansion/entry limits, full-package/split and self-update rejection, SDK/ABI/storage checks.
- Two workers, four queued connections, 15-second read inactivity deadline and hard session lifetime. CPU/memory/storage are bounded. Early rejected large requests may be observed by a browser as a connection error because the server intentionally does not consume an unauthorized body.
- Progress is bytes actually read on the watch and bytes sent by browser XHR. 100% sent changes to verification wording and never implies installation. Installation success appears only after STATUS_SUCCESS.
Pending approval is presented inside Pakkit, with an optional notification containing the system confirmation Intent. No background activity launch is attempted by the receiver. Notification permission is optional and requested only from an explanatory watch button. If approval state is interrupted and cannot be recovered in memory or from its notification, the user can explicitly retry, abandoning the previous session first. A transfer can only be reported as installed after `STATUS_SUCCESS`.
## Trust model
The system owns final package validation, update signatures, policy checks, verification and approval UI. No install result is inferred from a file transfer, countdown or launch attempt. Installation failures are mapped to understandable messages without logging APK contents or private paths.
Local HTTP is unencrypted. Link secrecy, Host/Origin checks and SHA-256 do not stop an active LAN attacker, protect against passive capture, or authenticate the server with a certificate. Use a trusted private Wi-Fi and keep the private URL secret. Anyone holding the link can submit a package, but only an explicit watch action can request its installation and Android requires consent. The app does not claim malware scanning or universal app compatibility. Source approval and system restrictions remain authoritative.
## Storage and battery
ReceiveService has INTERNET, ACCESS_NETWORK_STATE, CHANGE_NETWORK_STATE, WAKE_LOCK and foreground-service permissions; these support the explicit Wi-Fi session. REQUEST_INSTALL_PACKAGES is limited to the watch. Optional notification permission enables visible receiving/approval alerts; denying it does not authorize hidden background starts or bypass the in-app consent flow. The system may still expose the running foreground service in its task UI.
- 50 MiB maximum package, 64 KiB buffers, no entire APK byte arrays, no ZIP extraction.
- Approximate watch space budget: three APK sizes plus 20 MiB. This is a preflight, not a reservation; the system may still report insufficient storage.
- TTL: 24 hours from file selection. Workers remove retained offers/files when scheduled; background scheduling can be deferred by the OS. Stale files are additionally cleaned on app startup and after receive.
- One outstanding offer per phone, one reviewable file per watch; no parallel sync queue. Keep the watch app open for the most predictable receiving experience.
- No always-on service, app-managed wake lock, polling scan loop, custom networking, analytics or account system.
- The parcel artwork uses a short finite entrance, respects system animation and battery saver settings, and stops when its window is hidden or detached. Decorative watch artwork remains static. See the semantic palettes and components in Design.kt and the brand guide in design/README.md.
## Installation state
## Known engineering limits before production
`LocalInstall.status` writes watch-local ready/installing/confirm/installed/failed state. Store persists the current package/review across activity recreation. Session callbacks validate job and session IDs in a non-exported receiver. The pending system intent is kept in process or carried by the app’s immutable notification PendingIntent; interrupted approval can be retried. Installation re-hashes the private file and rechecks compatibility before writing a PackageInstaller session. Dismiss deletes the staged package. Success deletes it and cancels the consent notification.
Native Android views keep the runtime and dependencies small. Touch controls and text remain semantic views; the parcel art is decorative. The first locale is English; RTL mirroring uses platform layouts but localized copy and real RTL QA remain release work. Ordinary refreshes preserve scroll position. The watch returns to the heading when its transfer stage changes so the next decision is visible.
Single-file inspection does not fully classify all unusual/vendor split manifests, malicious parser edge cases or expanded installed size. Android remains the security authority. Asset transfer latency, cloud behavior, retry timing, UI interruption and consent recovery require paired-device testing. The initial implementation intentionally excludes automatic recovery that might open an installer without another user action. Cross-device cancellation of an already queued offer is deferred; current jobs can be dismissed on the watch after receipt or expire.
No appops mutation, permission grant shell command, ADB client, root, hidden installer component, device-owner privilege, automatic installation, browser-driven installation or Pakkit self-update exists in the product.
+33 -21
View File
@@ -1,37 +1,49 @@
# Feasibility decision
# Standalone feasibility decision
Research date: October 15, 2026. Reference hardware: Samsung Galaxy Watch 7; no physical hardware has been verified in this workspace.
Research and implementation: October 15, 2026. Pakkit 0.2 replaces the companion architecture.
## Decision
## Decision and evidence boundary
Build a **capability-gated companion**, rather than promise a universal installer. Official APIs support file transfer and user-initiated package installation. Their presence in Android does not prove that a particular Wear OS firmware provides usable unknown-source settings and installation confirmation. Pakkit never changes security settings itself.
Use a user-started local HTTP receiving session hosted by the watch, followed by explicit on-watch review and a public PackageInstaller session requiring user action. Receiving a file does not install it. Support is conditional on firmware exposing source approval and a functioning system installer.
The desired no-debugging path is conditional: paired Android phone and watch → install Pakkit through Play on both → approve Pakkit as an install source on supported watch firmware → choose a complete compatible APK → send → review on watch → explicitly request installation → approve the system screen. Source approval is an unavoidable extra setup step where Android requires it.
Android’s [Wear network guidance](https://developer.android.com/training/wearables/data/network-communication) explicitly supports HTTP/TCP/UDP and independent network access. This supports implementing a server using ordinary Android sockets; the documentation does not certify inbound reachability on every network. A Bluetooth-proxied internet route is not an inbound Wi-Fi listener, so Pakkit requests a Wi-Fi network and binds only its private IPv4 address. Guest-network isolation and firewalls remain outside application control.
## Confirmed platform capabilities
The [standalone app definition](https://developer.android.com/training/wearables/apps/standalone-apps) permits QR/browser alternatives without a companion phone app. The manifest now declares standalone=true. “Any device” means a supported modern browser on a reachable local network, not independence from the watch’s original OEM onboarding requirements. A Galaxy Watch 7’s initial setup requirements are separate from Pakkit’s browser support.
1. The [Wearable Data Layer overview](https://developer.android.com/training/wearables/data/overview) documents app-private phone/watch communication and requires matching package names and signing certificates. The transport can use Bluetooth or encrypted cloud routing. Pakkit uses it without its own network backend, direct sockets, Bluetooth discovery permissions or accounts. [Asset synchronization](https://developer.android.com/training/wearables/data/sync) allows queued transfer when disconnected; it is not an application database. Pakkit keeps its own state and private files. Asset APIs do not provide Pakkit with an accurate network byte-progress signal.
## Installation is a separate capability
2. [PackageInstaller](https://developer.android.com/reference/android/content/pm/PackageInstaller) supports sessions and reports success, failure or pending user action. Pakkit explicitly requires user action and handles the returned confirmation intent. This general Android capability is not proof of a usable Wear installation UI on every OEM firmware.
[PackageInstaller](https://developer.android.com/reference/android/content/pm/PackageInstaller) permits ordinary apps to create sessions with REQUEST_INSTALL_PACKAGES. Pakkit uses MODE_FULL_INSTALL and USER_ACTION_REQUIRED, handles STATUS_PENDING_USER_ACTION and starts only the returned system confirmation intent following a watch action. Android decides the final outcome. Readable signing metadata, hashes, SDK, ABI and space checks are preflight, not malware scanning or proof that an app will work on a round display.
3. [PackageManager.canRequestPackageInstalls](https://developer.android.com/reference/android/content/pm/PackageManager#canRequestPackageInstalls()) reports whether the caller is trusted as an installation source. Pakkit checks this on the watch. If allowed-source settings are unavailable and source approval is absent, Pakkit blocks sending. Resolver availability is a conservative preflight, not a compatibility certification.
[canRequestPackageInstalls](https://developer.android.com/reference/android/content/pm/PackageManager#canRequestPackageInstalls()) reports source trust. [ACTION_MANAGE_UNKNOWN_APP_SOURCES](https://developer.android.com/reference/android/provider/Settings#ACTION_MANAGE_UNKNOWN_APP_SOURCES) is the public settings route. A resolving activity alone does not prove a usable permission UI. Pakkit checks actual trust and gates session start; if approval is unavailable it explains the limit and offers Google Play. No appops changes, hidden components, privileged APIs or debugging client exist in application code.
## Google Play eligibility is conditional
### Galaxy Watch 7 evidence
[Play's sensitive permissions policy](https://support.google.com/googleplay/android-developer/answer/16558241?hl=en) includes phone-to-wearable companion synchronization among permitted REQUEST_INSTALL_PACKAGES purposes. This makes the proposed purpose potentially eligible; it does **not** guarantee permission approval or listing acceptance. Core functionality must be accurately described, declared and reviewed. Pakkit requests this permission only on the watch, offers no self-update mechanism, bundles no third-party APK and never starts an installation just because a transfer arrived. A reviewer must assess the final implementation and listing.
Reference hardware observed: SM-L310, Android 16, fingerprint `samsung/fresh7blue/fresh7bl:16/BP2A.250325.020/L310XXS2BZF4:user/release-keys`.
[Wear app packaging guidance](https://developer.android.com/training/wearables/packaging) requires a separate watch artifact, watch feature declaration and form-factor versioning. Pakkit's watch app declares itself non-standalone because selecting and sending requires the phone. Both artifacts must use the same production signing identity for the Data Layer.
The user reports that the previous Pakkit build completed installation normally without ADB, including with ADB debugging disabled. The development inspection found REQUEST_INSTALL_PACKAGES already allowed; no shell permission grant or security-setting modification was made. This is useful hardware evidence but does not independently reproduce a fresh Play-installed permission setup. See VALIDATION.md for the separately observed browser/upload/installer results. Do not generalize this result to every Samsung firmware, region or security configuration.
[Current target API policy](https://support.google.com/googleplay/android-developer/answer/11926878) requires API 36 for new phone apps and API 35 for Wear OS as of August 31, 2026. Both modules target 36. Recheck Play Console requirements at submission time.
## Lifecycle and power
## Developer verification changes the promise
A [connectedDevice foreground service](https://developer.android.com/develop/background-work/services/fgs/service-types#connected-device) fits an explicit local transfer with an external browser device. CHANGE_NETWORK_STATE is used to request Wi-Fi and meets this service type’s declared prerequisite. The foreground notification has a stop action. A timed partial wake lock keeps the CPU available without holding the display on. Wi-Fi requests and CPU lock are released at session stop, network loss, service destruction or ten-minute expiry. Nothing starts at boot; START_NOT_STICKY prevents automatic session resurrection. Process death invalidates the session and the user starts another.
[Android's developer-verification guidance](https://developer.android.com/developer-verification/guides) describes regional enforcement beginning September 30, 2026. Its [FAQ](https://developer.android.com/developer-verification/guides/faq) explains an advanced flow for unverified developers that includes developer mode and a protective delay. Pakkit does not implement or recommend this flow: it conflicts with the requested no-developer-options experience. Applicability to a particular Wear firmware must be tested; do not infer a verified exemption or rollout from the generic Android guidance. Respect any system block and direct users to a supported distribution of the app.
No continuous decorative watch animation, discovery broadcasts, cloud relay or analytics runs. Browser polling pauses while hidden. Watch byte updates are throttled to four per second. This bounds resource use but is not a battery consumption measurement; screen-off longevity, thermal and energy measurements remain release tests.
## Limits and assumptions
[Local network protections](https://developer.android.com/privacy-and-security/local-network-permission) cover incoming TCP too. At the current target SDK 36, INTERNET provides implicit local access. Before targeting 37, implement and test ACCESS_LOCAL_NETWORK runtime permission; official guidance says not to request it on lower targets. Browsers can independently require local-network permission.
- **Unverified:** Galaxy Watch 7 firmware versions, region-specific security settings, actual approval activity behavior and developer-verifier enforcement. Run the physical-device matrix before advertising support.
- **Supported intentionally:** complete single APKs up to 50 MiB. No APKM/XAPK/APKS/AAB or split installation support.
- **Preflight only:** SDK minimum, native-library ABI, approximate space, readable signing information and integrity. These do not prove safety, runtime usability, feature availability, signature validity under all platform rules, successful update or a wearable layout. The OS makes the final install decision.
- **No bypass:** if watch installation is unavailable, Google Play on that watch is the fallback. Pakkit does not silently enable debugging, root, hidden services or elevated privileges.
- **Release gate:** if physical tests show the reference device cannot complete the public consent path, do not publish the installer listing as broadly compatible. Narrow support to tested firmware or reconsider the product's scope.
## Google Play
The [REQUEST_INSTALL_PACKAGES policy](https://support.google.com/googleplay/android-developer/answer/12085295?hl=en) permits file sharing/transfer/management when package receipt and user-initiated installation are core functionality. Pakkit appears aligned with that category; this is an eligibility assessment, not approval. Accurately declare the final standalone purpose in Play Console and show source approval, transfer, watch review, system consent and denial handling. Do not reuse a companion-sync justification.
Declare the [foreground service use](https://support.google.com/googleplay/android-developer/answer/13392821) and provide the required demonstration. Publish only the watch artifact, with the required watch feature and standalone metadata, following [Wear packaging guidance](https://developer.android.com/training/wearables/packaging).
[Android developer verification](https://developer.android.com/developer-verification/guides) can add system restrictions to external apps. Some unverified-developer flows require developer settings and a delay. Those flows conflict with the product’s setup goal; Pakkit does not bypass them. Describe the supported compatible/verified package path rather than guaranteeing installation of every APK.
## Alternatives and limits
- **Google Play installation:** the compliant fallback when source trust, security policy, verification or firmware blocks external installation. Pakkit cannot silently elevate itself.
- **Trusted HTTPS relay:** could avoid LAN reachability and certificate setup, but requires a backend, retention policy, hosting cost, internet connectivity and additional privacy work. It would not fix a blocked PackageInstaller. Not implemented.
- **Local HTTPS:** a self-signed watch certificate produces browser trust warnings; ordinary public trust cannot be issued to an arbitrary private IP without additional infrastructure. Current local HTTP avoids certificate setup, openly limits use to trusted networks and does not claim encryption.
- **ADB/root/device-owner hacks:** excluded; they defeat the product goal or require privileges consumers do not have.
- **Cloud APK catalog/self-updater:** excluded; no third-party catalog, bundled consumer APK or Pakkit self-update path.
Current scope: private IPv4 Wi-Fi, one complete APK up to 50 MiB, one pending review, no split/APKS/APKM/XAPK/AAB support, no resumable upload. The OS performs final signature/update/verification checks. A failed firmware matrix or rejected permission declaration blocks production publication; a working upload alone does not change that decision.
+7 -7
View File
@@ -1,13 +1,13 @@
# Pakkit privacy text — draft for developer review
# Pakkit privacy disclosure draft
Pakkit helps you transfer an APK you select on your Android phone to your paired Wear OS watch and request its installation. You decide which file to send and approve installation on the watch.
Pakkit transfers an APK that you select in a browser directly to your Wear OS watch over your local Wi-Fi. It does not require an account, companion app, cloud relay, analytics or advertising. The HTML, styles, JavaScript, icons and QR generation are bundled with the watch app; no external font or asset service is contacted.
Pakkit stores the selected APK, package details, file-integrity digest and transfer state in its private app storage. The phone keeps the latest state of up to 20 transfers. You can clear this activity within Pakkit. Temporary package files are removed after completion or expiry (24 hours from selection); cleanup may be delayed by Android background scheduling. Removing Pakkit removes its local app data.
A short receiving session exposes a private URL and key. Keep that link private and use trusted Wi-Fi. Local HTTP is not encrypted; people able to observe or alter your network traffic may access it. Your browser/operating system may maintain its own local browsing history. Pakkit does not log uploaded filenames, IP addresses, keys or APK contents to a remote service.
Transfers use the Wearable Data Layer provided by Google Play services. Depending on device connectivity, data may travel over Bluetooth or encrypted cloud transport through Google infrastructure. Pakkit does not operate its own APK server, require an account, contain advertising or include analytics SDKs.
The APK is stored in the app’s private watch storage. Pakkit reads package metadata and signing information, checks size/compatibility and computes a hash. This does not certify that a package is safe. Nothing installs until you explicitly request it on the watch and complete Android’s system approval. Android may independently verify the app under its own policies.
The watch requests permission to ask Android to install a package. It does not silently install applications. Optional watch notifications help you return to a pending system approval screen. You can decline notifications and continue in the app.
Rejected/partial uploads are deleted. Successful installations and dismissed reviews delete the staged APK. Pending packages expire for installation after 24 hours and are cleaned up on the next app launch; they may remain in private storage until then. Local status history holds up to 20 entries of package label, state and timestamp. App backups/device transfer are disabled. Uninstalling Pakkit removes its private data; installed third-party apps are separate.
Only send software from a source you trust. Pakkit's file checks are not a malware scan or a guarantee of safety or watch compatibility. Android and the watch's security policy control whether installation can proceed.
Sessions end automatically within ten minutes, on Wi-Fi loss or when you stop them. Ending a session closes network access; it does not cancel an already committed system installation.
Before publication, the developer must add its legal identity, effective date, support contact and any required jurisdiction-specific terms to a publicly accessible policy. This repository draft is not itself a published policy or completed Play Data safety declaration.
Before publication, add the legal developer identity, support contact and hosted privacy policy URL. Reconcile the final binary, Android system behavior and Google Play Data safety answers; this draft is not a completed Play declaration.
+13 -29
View File
@@ -1,32 +1,16 @@
# Google Play release preparation
This is a release checklist, not an assertion that the app is already approved or ready for a public production rollout.
Pakkit is implemented as a standalone Wear OS app. This checklist does not assert Google Play approval.
## Technical artifacts
- Phone and watch use application ID `meghdad.pakkit`; namespaces differ by module.
- Phone version code: 100001; watch: 100002. Increment monotonically and keep codes unique across form factors.
- Compile SDK 36.1; min SDK 31; target SDK 36. Confirm supported-device filtering in Play Console.
- Separate watch artifact declares required `android.hardware.type.watch` and `standalone=false`.
- Release minification and resource-safe platform UI. Worker constructors are kept for background reconstruction.
- Use the **same app-signing certificate** across phone and watch. Different debug/release certificates cannot communicate through the Data Layer. Play App Signing key upgrades must be evaluated on both devices.
- Optional release signing environment: `PAKKIT_KEYSTORE`, `PAKKIT_KEYSTORE_PASSWORD`, `PAKKIT_KEY_ALIAS`, `PAKKIT_KEY_PASSWORD`. Keep the keystore outside the repository. No secret defaults or debug signing for release. Without a complete set of variables, output is unsigned and must be signed through the release pipeline.
- Build with `./gradlew :app:bundleRelease :wear:bundleRelease`, inspect merged manifests and upload each artifact to the proper form factor/test track. Check version code handling in Play Console before promoting.
## Permission declaration
`REQUEST_INSTALL_PACKAGES` exists only in the watch app. Justification for review: the core function transfers a user-selected APK from the paired phone to the user's watch and requests installation after the user explicitly reviews it on that watch. Submit the permissions declaration and an accurate screencast showing selection, transfer, source approval, app review, system approval, cancellation and unsupported-device handling.
Explain in the listing that firmware and package restrictions apply. Do not advertise one-tap installation, compatibility with all Wear OS devices, malware certification, silent installation or guaranteed approval. No packaged third-party APK, in-app self-update, package catalog or download service is included.
`POST_NOTIFICATIONS` is optional and watch-only, used for pending installer consent. Declining it leaves in-app consent usable. WorkManager contributes its standard boot-rescheduling/network-state/wake permissions through manifest merging; its unused foreground service and permission are explicitly removed. Review the final manifest rather than just source manifests. No broad storage, package visibility, location or Bluetooth runtime permissions are requested.
## Listing and disclosures
1. Finalize legal developer identity, support email and public privacy-policy URL. No invented identity or placeholder contact should be published.
2. Publish privacy text based on [PRIVACY.md](PRIVACY.md); confirm SDK behavior and the final Data safety answers. Google Play services may route encrypted APK data through Google's infrastructure. “No Pakkit server” does not mean all transport is local.
3. Upload genuine phone and round-watch screenshots, adaptive launcher assets and required store artwork. The same premium identity should appear in both listings.
4. State Wear OS support and the companion requirement clearly. Reference-device claims require recorded results for the specific model and firmware.
5. Complete content rating, target audience, ads declaration (none), Data safety, external-package permission declaration and Wear OS quality review.
6. Run internal/closed testing, pre-launch reports and physical-device compatibility matrix. Check current target API and developer-verification requirements again.
7. Promote only after every blocker in VALIDATION.md is resolved and the permission declaration is accepted. Google Play approval cannot be guaranteed.
- Publish only `wear`: application ID `meghdad.pakkit`, version 0.2.0/code100003, standalone=true, required watch feature, min31/target36/compile36.1. The phone module is removed. Increment codes for subsequent uploads.
- Build `./gradlew :wear:bundleRelease`. R8/resource shrinking enabled. Debug fixtures remain only in the test APK.
- Production signing inputs: PAKKIT_KEYSTORE, PAKKIT_KEYSTORE_PASSWORD, PAKKIT_KEY_ALIAS, PAKKIT_KEY_PASSWORD. No secret/default production key is included. Without the full set the release AAB is unsigned and must be signed by the release pipeline.
- Declare REQUEST_INSTALL_PACKAGES accurately as core, user-selected local package transfer with user-initiated installation. Submit the final standalone flow, source approval, transfer, watch review, system approval, cancellation and unsupported-state screencast. Do not claim prior companion permission eligibility automatically applies.
- Declare connectedDevice foreground-service use for a user-started bounded local device transfer, with notification/stop controls and required evidence. Review final merged permissions. No storage, broad package visibility, Bluetooth, location or boot permissions are requested.
- INTERNET/ACCESS_NETWORK_STATE/CHANGE_NETWORK_STATE support the requested Wi-Fi network and socket. WAKE_LOCK supports the bounded session. POST_NOTIFICATIONS is optional for receiving and approval alerts. Foreground service and connected-device foreground permissions are declared explicitly.
- Confirm the [install-package permission policy](https://support.google.com/googleplay/android-developer/answer/12085295) and [foreground service declaration requirements](https://support.google.com/googleplay/android-developer/answer/13392821) with the actual listing. Approval is not guaranteed.
- Add real developer/support identity and hosted privacy policy. Reconcile Data safety with PRIVACY.md and the final binary. No backend/analytics is used, but system installation verification is controlled by Android.
- Use genuine current standalone web and round-watch screenshots. Explain trusted same-Wi-Fi requirement, unencrypted local HTTP, source approval, complete APK limit, device/firmware restrictions and final Android consent. Avoid universal “all APKs” or encrypted/private-network security guarantees.
- Test fresh Play-delivered source approval on Watch7 firmware/regions, screen-off receiving, blocked sources, browser local-network permission, guest/client-isolated networks, user stop, session expiry, interrupted upload, process death, battery and accessibility. Record browser/device versions. Full Safari/iOS/Firefox/Windows/Linux coverage remains required.
- Recheck target SDK, Wear quality and developer verification requirements at submission. Target37 needs runtime ACCESS_LOCAL_NETWORK implementation/testing before adoption; current target36 follows Android’s implicit local network access rules.
- Run internal/closed testing and Play pre-launch/review. Do not promote until VALIDATION.md gates are met and restricted-permission/foreground-service declarations are accepted.
+26 -54
View File
@@ -1,65 +1,37 @@
# Validation record
# Standalone validation — October 15, 2026
Date: October 15, 2026. This record separates what ran from what still needs paired physical devices and Play review.
Version 0.2.0 / 100003. The consumer app is standalone; old companion test results in `validation/brand` and older screenshots are historical evidence only.
## Brand integration update — October 15, 2026
## Automated coverage
The official Pakkit identity is now implemented in both consumer apps. See [the brand guide](../design/README.md) and [current previews](screenshots/brand/). Earlier screenshots outside that subfolder document the previous visual direction. Brand test results are saved in [validation/brand](validation/brand/).
- 13 shared JVM tests: six bounded-stream/expiry/ABI rules, three semantic contrast checks, four HTTP parsing/authentication/size tests. Results: `shared/build/test-results/testDebugUnitTest`.
- Two watch instrumentation tests on the Wear OS API37 round emulator: actual Wi-Fi socket GET/status/raw APK POST; missing-token and cross-origin rejection; invalid APK deletion; duplicate upload refusal; verified fixture metadata; no automatic PackageInstaller session; listener closes and private URL clears at explicit stop. The separate round-review test verifies 48dp actions are reachable and receipt does not create an installation session.
- The emulator needed its virtual Wi-Fi enabled and associated with AndroidWifi. Initial failures while Wi-Fi was disabled were environmental. A repeated run exposed an HTTP test-client bug: reading until EOF could observe a reset after an intentionally early rejected request; the test now reads the response’s exact Content-Length. Final results are saved in `validation/standalone/watch-tests.txt`.
- Debug APK, instrumentation APK, optimized release AAB, shared unit tests and Android lint build successfully. Lint has zero errors; remaining warnings concern SDK/library update suggestions and optional KTX/style changes. Release bundle is unsigned unless production signing inputs are supplied.
- Custom open-parcel mark, adaptive/monochrome launcher assets, unified midnight splash and branded approval notification.
- Lavender light and midnight dark phone themes with a native custom appearance dialog, persisted selection and actual chooser/recreation testing.
- New phone navigation, connection illustration, file review, truthful transfer stages, history, empty states and guide.
- Midnight watch home, review, receiving, consent, success and error components, with proportional round-screen margins, a bezel scroll indicator and native clock.
- 9 shared JVM tests pass, including 3 new contrast checks; 5 phone instrumentation tests and 1 strengthened watch review/target-size test pass. The watch test also passed at an emulated 192-DP round size with 1.3× text, checking that install/dismiss actions remain fully reachable and at least 48 DP tall. This is an additional tested configuration, not physical-device certification.
- Both debug builds and optimized unsigned release bundles build; Android lint reports zero errors. Existing informational dependency/SDK/style warnings remain.
- A local signed QA fixture was updated through the redesigned watch review, genuine system confirmation and success screen.
- Android’s real document picker was used to select the signed local QA APK and verify the phone review screen.
- Package transfer, source approval, explicit install/session consent and policy boundaries are preserved. No capability or fake progress state was added from the creative reference.
## Physical Galaxy Watch 7
## Completed
SM-L310, Android16 firmware `L310XXS2BZF4`, full fingerprint in FEASIBILITY.md. Development ADB installed Pakkit and observed/clicked visible UI for QA. No `pm grant`, `appops set`, hidden installer, root or ADB package installation was used to install the QA fixture. Consumer code contains no ADB/debugging path.
| Check | Result |
| --- | --- |
| Phone debug APK | Built successfully |
| Wear OS debug APK | Built successfully |
| Optimized phone release bundle | Built successfully; unsigned without production signing variables |
| Optimized watch release bundle | Built successfully; unsigned without production signing variables |
| Android lint, phone | 0 errors; informational SDK/dependency/style warnings remain |
| Android lint, watch | 0 errors; informational SDK/style warnings remain |
| Bounded copy, known SHA-256, empty/oversize rejection, identifier safety, expiry, ABI matching | 6 JVM tests passed |
| Phone device tests: navigation and recreation, signed complete APK inspection, self-update rejection, invalid archive/path rejection | 4 passed on Pixel 10 Pro emulator, API 37 |
| Watch review test: signed fixture can be reviewed without creating any install session | 1 passed on round Wear OS 7 emulator, API 37, 454×454 |
| Visual inspection | Phone home and round watch review/controls inspected; explicit illustration height corrected |
| System source approval | Opened via public settings intent; normal system warning and approval completed on watch emulator |
| Watch PackageInstaller path | Explicit Install → pending-user-action callback → Continue → genuine system confirmation → system Install → STATUS_SUCCESS and Pakkit “Installed on your watch” → Open app launched the fixture |
| Installed-file cleanup | Confirmed the successful transfer’s private APK was deleted after installation |
| Merged release manifests | Installation and notification permissions watch-only; no broad storage/visibility/Bluetooth/location permission; unused foreground service and its permission removed |
| Release contents | QA APK absent from consumer bundles; no production signature created in this workspace |
| Git whitespace check | Passed |
1. Existing Pakkit source approval was already allowed. User reports normal prior source approval/installation without ADB, including with ADB debugging disabled. The agent did not reproduce a fresh Play-installed permission setup.
2. Started Pakkit’s explicit receiving session on real Wi-Fi. Watch issued a private IPv4 URL and locally generated QR.
3. Headless Chromium opened **the real watch-hosted site**, authenticated and rendered desktop1440x1100 and mobile390x844 layouts in light/dark modes. Zero JavaScript errors; no mobile horizontal overflow. Screenshots are actual product renders in `screenshots/standalone`.
4. Browser selected our signed `qaFixture-debug.apk` (2,473,486 bytes), uploaded it through XHR to the watch’s socket and received ready. Watch persisted package `meghdad.pakkit.fixture`, correct SHA-256 and source `local-browser`. Receiving stopped at review without an installation session.
5. Watch Install and Continue actions reached the pending system-consent flow. Subsequent InstallReceiver history recorded **installed** for that exact upload UUID, and Android’s package list confirmed the fixture. The user was interacting with the watch during this test. A separate screenshot of the system installer was not captured; the image initially taken after consent had already returned to Pakkit is not presented as system UI evidence.
6. Repeated live HTTP checks: public page200; status without token403; wrong token403; authenticated status200; foreign-Origin upload403; invalid APK400. Recorded in `validation/standalone/live-http.json`. These checks also passed with the physical display explicitly asleep. This is a short screen-off accessibility check, not a long-duration power/Doze certification.
7. Final QR layout centers its square in the circular safe area and sizes with screen width. ZXing decoded the actual physical screenshot after masking all pixels outside the display circle (`validation/standalone/qr-check.txt`); the watch remains scrollable for the URL, disclosure and End session action.
The manual install used `qaFixture`, a small signed local test application. Instrumentation staged it into the watch's private review state to isolate the installation boundary. **This was not a test of Data Layer delivery.** The fixture is packaged only into Android test assets, never consumer APKs or bundles. The UI uses the exact same file revalidation, PackageInstaller session and result receiver as the consumer install flow. Developer tooling deployed Pakkit's debug builds; the fixture itself was installed through ordinary watch UI and system consent, without an ADB package install, app-op grant, root or hidden API.
The temporary QA fixture was removed after verification.
Raw device test summaries: [phone](validation/phone-tests.txt), [watch](validation/watch-tests.txt). Screenshots are in [screenshots](screenshots/): phone home, watch launch/home/controls, real system approval and successful installation. Test fixture screens are labelled accordingly and are not store marketing screenshots.
No release claim is inferred solely from a successful file upload. The observed fixture installation is separate, stronger evidence for this device’s public installation route with trust already granted.
## Not yet verified — release blockers
## Remaining release gates
1. **Paired Data Layer integration:** the available phone/watch emulators were not configured as a paired Wear network, and discovery on the phone returned an availability/connection failure. Capability nonce exchange, real asset delivery, background receive, acknowledgement routing, delayed retries and cloud routing are implemented but remain unverified end-to-end.
2. **Galaxy Watch 7:** test exact One UI Watch / Wear OS / Android build and region. Confirm source settings, resolver behavior, consent UI, blocked cases, normal launch and developer-verification enforcement. No compatibility claim should be made before this.
3. **Interruptions and limits:** Bluetooth off/on, phone process killed, watch process killed, reboot during sync, missed status acknowledgement, system approval dismissed, user denied source/notification permission, second phone or second watch, no space, low battery and 50 MiB boundary. Test expiry while a job or install session is active. Background workers are OS-scheduled and may run later than their target time.
4. **Package coverage:** real compatible standalone APK, wrong ABI, newer minimum SDK, wrong update signature, downgrade, invalid certificate, isolated/config split, base requiring splits, corrupt resource table and restricted packages. Preflight is intentionally not a full certification or malware scan.
5. **Accessibility and layout:** TalkBack, large fonts, touch exploration, reduced animation, rotary input on hardware, 192/208/227 dp round displays and an actual tablet/phone rotation. Semantic controls and scrolling are implemented; full accessibility certification has not been performed.
6. **Performance:** battery and transfer latency on real Bluetooth/cloud links, background job timing and memory on low-RAM watches. The 50 MiB cap, bounded buffers and lack of continuous watch animation are implementation constraints, not measured performance claims.
7. **Release identity and policy:** production signing identity shared across form factors, verified dependency provenance, public privacy URL/support contact, listing assets, completed permission/Data safety declarations, internal/closed testing and Wear OS review. Google Play approval is not guaranteed.
- Fresh Play-delivered installation and source-approval flow without preexisting Pakkit trust, across supported Samsung firmware/regions and security settings. Record denial/revocation/cancellation and developer-verification behavior.
- Google Play restricted-permission and foreground-service declaration acceptance, listing/quality review, developer identity/signing and hosted privacy policy.
- Safari on real iOS/macOS, Firefox, Edge/Windows, Android browser and Linux coverage. The current browser run was Chromium on macOS, with mobile viewport emulation; it is not proof of all browser/platform combinations.
- Full ten-minute expiry on hardware, repeated sessions, long screen-off/Doze, network/IP change, client isolation, local-network permissions, interrupted large upload, low storage and process death. Explicit-stop cleanup is automated; expiry is implemented but not yet a completed elapsed-time hardware test.
- Full TalkBack/rotary/large-text/contrast review of the new receiving screen and web flow; small round physical displays. The prior review screen was tested at192dp/1.3x text, but this does not certify every new state.
- Measured battery/thermal/memory behavior under maximum50MiB transfers and adversarial bounded connections. Locks, buffers, threads and deadlines are bounded by implementation, not a measured battery guarantee.
## Intentional v1 boundaries
Single complete APK, 50 MiB maximum, one in-flight job per phone and one reviewable APK per watch, expiry 24 hours from selection, no percentage estimate, no direct third-party downloads or catalog. Waiting transfers do not currently offer a cross-device cancel action; dismiss on the watch when delivered, or let the job expire. English is the first locale. Background transfers and approval recovery require device validation before public rollout.
## Reproduce
```sh
./gradlew :app:assembleDebug :wear:assembleDebug :shared:testDebugUnitTest :app:lintDebug :wear:lintDebug :app:bundleRelease :wear:bundleRelease
./gradlew :app:assembleDebugAndroidTest :wear:assembleDebugAndroidTest
```
In environments where Google Maven returns HTTP 404, append `-PpakkitGoogleMavenMirror=https://maven.aliyun.com/repository/google` after reviewing the mirror's suitability. Run each instrumentation APK against its matching phone/watch app, rather than deploying both variants to the same device: they intentionally share an application ID. Standard Android Studio device-test tooling can run the tests. The watch test leaves its fixture ready for manual consent checks.
Do not advertise universal firmware/APK compatibility, encrypted transport, unconditional no-setup installation, or Google Play approval.
Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 414 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 231 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 232 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 211 KiB

@@ -0,0 +1,27 @@
{
"unitSuites": [
{
"name": "meghdad.pakkit.core.TransferRulesTest",
"tests": "6",
"failures": "0",
"errors": "0"
},
{
"name": "meghdad.pakkit.core.HttpProtocolTest",
"tests": "4",
"failures": "0",
"errors": "0"
},
{
"name": "meghdad.pakkit.core.BrandPaletteTest",
"tests": "3",
"failures": "0",
"errors": "0"
}
],
"lintErrors": 0,
"lintWarnings": 17,
"version": "0.2.0",
"versionCode": 100003,
"releaseBundleSigned": false
}
@@ -0,0 +1,8 @@
{
"publicPage": 200,
"noToken": 403,
"wrongToken": 403,
"status": 200,
"wrongOrigin": 403,
"invalidApk": 400
}
+1
View File
@@ -0,0 +1 @@
Physical Watch 7 screenshot: QR decodes successfully with circular display mask.
@@ -0,0 +1,9 @@
meghdad.pakkit.wear.LocalReceiveTest:.
meghdad.pakkit.wear.WatchReviewTest:.
Time: 1.492
OK (2 tests)
+1 -2
View File
@@ -1,2 +1 @@
# WorkManager uses class names to recreate persistent work after process death.
-keep class * extends androidx.work.ListenableWorker { public <init>(android.content.Context, androidx.work.WorkerParameters); }
# No reflection-based application components require custom keep rules.
+1 -1
View File
@@ -27,7 +27,7 @@ dependencyResolutionManagement {
}
rootProject.name = "pakkit"
include(":app")
// Pakkit is distributed as a standalone watch app.
include(":shared", ":wear")
// Test-only APK used by instrumentation. Never bundled in either consumer artifact.
include(":qaFixture")
-2
View File
@@ -6,8 +6,6 @@ android {
compileOptions { sourceCompatibility = JavaVersion.VERSION_11; targetCompatibility = JavaVersion.VERSION_11 }
}
dependencies {
api("com.google.android.gms:play-services-wearable:19.0.0")
api("androidx.work:work-runtime-ktx:2.10.1")
api(libs.androidx.core.ktx)
testImplementation(libs.junit)
}
+1 -17
View File
@@ -1,17 +1 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">
<!-- Transfers use normal bounded workers; no foreground worker is started. -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" tools:node="remove"/>
<application>
<service android:name="androidx.work.impl.foreground.SystemForegroundService" tools:node="remove"/>
<service android:name="meghdad.pakkit.core.LinkService" android:exported="true">
<intent-filter>
<action android:name="com.google.android.gms.wearable.DATA_CHANGED" />
<data android:scheme="wear" android:host="*" android:pathPrefix="/pakkit/" />
</intent-filter>
<intent-filter>
<action android:name="com.google.android.gms.wearable.MESSAGE_RECEIVED" />
<data android:scheme="wear" android:host="*" android:path="/pakkit/probe" />
</intent-filter>
</service>
</application>
</manifest>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"/>
@@ -49,7 +49,7 @@ object Design {
"light" -> false
else -> c.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES
}
fun palette(c: Context): BrandPalette = if (Link.isWatch(c) || isDark(c)) BrandPalette.Dark else BrandPalette.Light
fun palette(c: Context): BrandPalette = if (c.packageManager.hasSystemFeature(android.content.pm.PackageManager.FEATURE_WATCH) || isDark(c)) BrandPalette.Dark else BrandPalette.Light
fun dp(c: Context, n: Int) = (n * c.resources.displayMetrics.density).toInt()
fun motionAllowed(c: Context) = ValueAnimator.areAnimatorsEnabled() && !c.getSystemService(PowerManager::class.java).isPowerSaveMode
fun shape(color: Int, radius: Float = 24f, stroke: Int? = null) = GradientDrawable().apply {
@@ -0,0 +1,45 @@
package meghdad.pakkit.core
import java.io.InputStream
import java.security.MessageDigest
/** 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 size = headers["content-length"]?.toLongOrNull() ?: error("Content length required")
require(size in 1..TransferRules.MAX_BYTES) { "Choose an APK up to 50 MiB" }
return size
}
}
@@ -1,65 +0,0 @@
package meghdad.pakkit.core
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import com.google.android.gms.tasks.Tasks
import com.google.android.gms.wearable.*
import org.json.JSONObject
import java.util.concurrent.TimeUnit
object Link {
const val ROOT = "/pakkit/"
const val CAPABILITY = "pakkit_watch_v1"
fun isWatch(c: Context) = c.packageManager.hasSystemFeature(PackageManager.FEATURE_WATCH)
fun settings(c: Context) = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:${c.packageName}"))
fun installer(c: Context): Boolean = Intent(Intent.ACTION_INSTALL_PACKAGE)
.setDataAndType(Uri.parse("content://meghdad.pakkit/probe.apk"), "application/vnd.android.package-archive")
.resolveActivity(c.packageManager) != null
fun capability(c: Context, nonce: String = "") {
val node = Tasks.await(Wearable.getNodeClient(c).localNode, 15, TimeUnit.SECONDS)
val request = PutDataMapRequest.create("${ROOT}cap/${node.id}")
request.dataMap.apply {
putString("nonce", nonce); putLong("time", System.currentTimeMillis()); putInt("sdk", Build.VERSION.SDK_INT)
putStringArrayList("abis", ArrayList(Build.SUPPORTED_ABIS.toList()))
putLong("free", Packages.free(c)); putBoolean("installer", installer(c))
putBoolean("settings", settings(c).resolveActivity(c.packageManager) != null)
putBoolean("allowed", c.packageManager.canRequestPackageInstalls())
}
Tasks.await(Wearable.getDataClient(c).putDataItem(request.asPutDataRequest().setUrgent()), 20, TimeUnit.SECONDS)
}
@Synchronized
fun status(c: Context, job: JSONObject, state: String, detail: String, persist: Boolean = true) {
val store = Store(c)
val revision = store.prefs.getLong("statusRevision", 0) + 1
store.prefs.edit().putLong("statusRevision", revision).commit()
val updated = JSONObject(job.toString()).put("state", state).put("detail", detail).put("revision", revision)
if (persist) Store(c).write("incoming", updated)
Store(c).history(job.getString("id"), job.getJSONObject("apk").getString("label"), state, detail)
val req = PutDataMapRequest.create("${ROOT}status/${job.getString("id")}")
req.dataMap.apply {
putString("id", job.getString("id")); putString("target", job.getString("source"))
putString("state", state); putString("detail", detail.take(400)); putLong("time", System.currentTimeMillis()); putLong("revision", revision)
}
// A durable worker retries publication if connectivity or Play services is temporarily unavailable.
androidx.work.WorkManager.getInstance(c).enqueueUniqueWork("status-${job.getString("id")}",
androidx.work.ExistingWorkPolicy.REPLACE, androidx.work.OneTimeWorkRequestBuilder<StatusWorker>()
.setInputData(androidx.work.workDataOf("path" to req.uri.path, "map" to req.dataMap.toByteArray())).build())
}
fun delete(c: Context, uri: Uri) = Wearable.getDataClient(c).deleteDataItems(uri)
}
class StatusWorker(c: Context, p: androidx.work.WorkerParameters) : androidx.work.Worker(c, p) {
override fun doWork(): Result { return try {
val req = PutDataMapRequest.create(requireNotNull(inputData.getString("path")))
req.dataMap.putAll(DataMap.fromByteArray(requireNotNull(inputData.getByteArray("map"))))
val current = Store(applicationContext).read("incoming")
if (current != null && current.optString("id") == req.dataMap.getString("id") && current.optLong("revision") > req.dataMap.getLong("revision")) return Result.success()
Tasks.await(Wearable.getDataClient(applicationContext).putDataItem(req.asPutDataRequest().setUrgent()), 30, TimeUnit.SECONDS)
Result.success()
} catch (_: Exception) { if (runAttemptCount < 5) Result.retry() else Result.failure() }
}
}
@@ -1,118 +0,0 @@
package meghdad.pakkit.core
import android.net.Uri
import androidx.work.*
import com.google.android.gms.tasks.Tasks
import com.google.android.gms.wearable.*
import org.json.JSONObject
import java.io.File
import java.util.concurrent.TimeUnit
class LinkService : WearableListenerService() {
override fun onMessageReceived(event: MessageEvent) {
if (Link.isWatch(this) && event.path == "/pakkit/probe" && event.data.size <= 100) {
runCatching { Link.capability(this, event.data.toString(Charsets.UTF_8)) }
}
}
override fun onDataChanged(events: DataEventBuffer) {
for (event in events) {
if (event.type != DataEvent.TYPE_CHANGED) continue
val item = event.dataItem
when {
Link.isWatch(this) && item.uri.path?.startsWith("/pakkit/offer/") == true -> {
WorkManager.getInstance(this).enqueueUniqueWork("receive-${item.uri.lastPathSegment}", ExistingWorkPolicy.KEEP,
OneTimeWorkRequestBuilder<ReceiveWorker>().setInputData(workDataOf("uri" to item.uri.toString())).build())
}
!Link.isWatch(this) && item.uri.path?.startsWith("/pakkit/status/") == true -> acceptStatus(item)
}
}
}
private fun acceptStatus(item: DataItem) = synchronized(Store::class.java) {
runCatching {
val map = DataMapItem.fromDataItem(item).dataMap
val store = Store(this)
val job = store.read("outgoing") ?: return@runCatching
if (map.getString("id") != job.optString("id") || item.uri.host != job.optString("target")) return@runCatching
val revision = map.getLong("revision")
if (revision <= job.optLong("revision", -1)) return@runCatching
val state = map.getString("state") ?: return@runCatching
if (state !in setOf("receiving", "ready", "confirm", "installing", "installed", "failed", "declined")) return@runCatching
job.put("revision", revision).put("state", state).put("detail", map.getString("detail").orEmpty().take(400))
store.write("outgoing", job)
store.history(job.getString("id"), job.getJSONObject("apk").getString("label"), state, job.getString("detail"))
if (state in setOf("installed", "failed", "declined")) {
store.file(job.getString("id")).delete()
job.optString("offer").takeIf { it.isNotEmpty() }?.let { Link.delete(this, Uri.parse(it)) }
Link.delete(this, item.uri)
}
}
}
}
class ReceiveWorker(c: android.content.Context, p: WorkerParameters) : Worker(c, p) {
override fun doWork(): Result {
val c = applicationContext
val store = Store(c)
var job: JSONObject? = null
var part: File? = null
var itemUri: Uri? = null
return try {
if (!Link.isWatch(c)) return Result.failure()
val uri = Uri.parse(requireNotNull(inputData.getString("uri")))
itemUri = uri
val item = Tasks.await(Wearable.getDataClient(c).getDataItem(uri), 30, TimeUnit.SECONDS) ?: return Result.success()
val map = DataMapItem.fromDataItem(item).dataMap
val local = Tasks.await(Wearable.getNodeClient(c).localNode, 15, TimeUnit.SECONDS)
if (map.getString("target") != local.id) return Result.success()
val id = requireNotNull(map.getString("id"))
require(TransferRules.validId(id) && uri.lastPathSegment == id)
val expected = Apk.from(JSONObject(requireNotNull(map.getString("apk"))))
job = JSONObject().put("id", id).put("source", uri.host).put("apk", expected.json()).put("created", map.getLong("created"))
if (store.prefs.getStringSet("received", emptySet()).orEmpty().contains(id)) return Result.success()
val old = store.read("incoming")
if (old?.optString("id") == id && old.optString("state") !in setOf("receiving")) return Result.success()
if (old != null && old.optString("id") != id && old.optString("state") !in setOf("installed", "failed", "declined")) {
Link.status(c, job, "failed", "Finish or dismiss the current APK on your watch first.", persist = false)
Link.delete(c, uri)
return Result.success()
}
require(TransferRules.fresh(map.getLong("created"), System.currentTimeMillis())) { "This transfer expired. Send it again from your phone." }
require(expected.bytes in 1..TransferRules.MAX_BYTES)
require(Link.installer(c) && (c.packageManager.canRequestPackageInstalls() || Link.settings(c).resolveActivity(c.packageManager) != null)) { "This watch does not expose the system installation controls. Use Google Play on your watch." }
Packages.checkForWatch(expected, android.os.Build.VERSION.SDK_INT, android.os.Build.SUPPORTED_ABIS.toSet(), Packages.free(c))
WorkManager.getInstance(c).enqueueUniqueWork("expire-$id", ExistingWorkPolicy.KEEP,
OneTimeWorkRequestBuilder<ExpireWorker>().setInitialDelay((map.getLong("created") + TransferRules.TTL_MS - System.currentTimeMillis()).coerceAtLeast(0), TimeUnit.MILLISECONDS)
.setInputData(workDataOf("id" to id)).build())
Link.status(c, job, "receiving", "Verifying the APK on your watch")
part = File(store.directory, "$id.part")
val asset = requireNotNull(map.getAsset("file"))
val response = Tasks.await(Wearable.getDataClient(c).getFdForAsset(asset), 90, TimeUnit.SECONDS)
val result = try {
requireNotNull(response.inputStream).use { input -> part.outputStream().use { output -> TransferRules.copyBounded(input, output) } }
} finally { response.release() }
require(result.first == expected.bytes && result.second == expected.sha256) { "The file did not pass its integrity check. Send it again." }
val actual = Packages.inspect(c, part, result.second)
require(actual.packageName == expected.packageName) { "Package details did not match." }
Packages.checkForWatch(actual, android.os.Build.VERSION.SDK_INT, android.os.Build.SUPPORTED_ABIS.toSet(), Packages.free(c))
require(TransferRules.fresh(map.getLong("created"), System.currentTimeMillis())) { "This transfer expired. Send it again." }
require(part.renameTo(store.file(id))) { "Could not save this APK." }
job.put("apk", actual.json())
Link.status(c, job, "ready", "Ready. Review and install on your watch.")
store.prefs.edit().putStringSet("received", (store.prefs.getStringSet("received", emptySet()).orEmpty().toList().takeLast(99) + id).toSet()).commit()
Link.delete(c, uri)
store.clean()
Result.success()
} catch (e: Exception) {
part?.delete()
if (job != null && e !is IllegalArgumentException && e !is IllegalStateException && runAttemptCount < 3) {
Result.retry()
} else if (job != null) {
runCatching { Link.status(c, job, "failed", e.message ?: "Could not receive this APK. Try again.") }
itemUri?.let { Link.delete(c, it) }
Result.failure()
} else if (runAttemptCount < 3) Result.retry() else Result.failure()
}
}
}
@@ -1,72 +0,0 @@
package meghdad.pakkit.core
import android.content.Context
import android.net.Uri
import androidx.work.*
import com.google.android.gms.tasks.Tasks
import com.google.android.gms.wearable.*
import java.util.concurrent.TimeUnit
class SendWorker(c: Context, p: WorkerParameters) : Worker(c, p) {
override fun doWork(): Result {
val store = Store(applicationContext)
val job = store.read("outgoing") ?: return Result.failure()
if (job.optString("id") != inputData.getString("id") || job.optString("state") != "sending") return Result.success()
return try {
require(TransferRules.fresh(job.getLong("created"), System.currentTimeMillis())) { "This transfer expired. Choose the file again." }
val req = PutDataMapRequest.create("/pakkit/offer/${job.getString("id")}")
req.dataMap.apply {
putString("id", job.getString("id")); putString("target", job.getString("target"))
putLong("created", job.getLong("created")); putString("apk", job.getJSONObject("apk").toString())
putAsset("file", Asset.createFromUri(Uri.fromFile(store.file(job.getString("id")))))
}
val item = Tasks.await(Wearable.getDataClient(applicationContext).putDataItem(req.asPutDataRequest().setUrgent()), 45, TimeUnit.SECONDS)
// Do not overwrite an acknowledgement that arrived while publication was in flight.
synchronized(Store::class.java) {
val latest = store.read("outgoing")
if (latest?.optString("id") == job.getString("id")) {
latest.put("offer", item.uri.toString())
if (latest.optString("state") == "sending") latest.put("state", "syncing")
.put("detail", "Syncing to your watch. Open Pakkit there to continue.")
store.write("outgoing", latest)
}
}
WorkManager.getInstance(applicationContext).enqueueUniqueWork("expire-${job.getString("id")}", ExistingWorkPolicy.KEEP,
OneTimeWorkRequestBuilder<ExpireWorker>().setInitialDelay(24, TimeUnit.HOURS)
.setInputData(workDataOf("id" to job.getString("id"), "uri" to item.uri.toString())).build())
Result.success()
} catch (e: Exception) {
if (runAttemptCount < 3) Result.retry() else {
synchronized(Store::class.java) {
val latest = store.read("outgoing")
if (latest?.optString("id") == job.getString("id") && latest.optString("state") == "sending")
store.write("outgoing", latest.put("state", "failed").put("detail", "Could not sync. Check your connection and choose the file again."))
}
Result.failure()
}
}
}
}
class ExpireWorker(c: Context, p: WorkerParameters) : Worker(c, p) {
override fun doWork(): Result {
val store = Store(applicationContext)
val id = inputData.getString("id") ?: return Result.failure()
return try {
inputData.getString("uri")?.let { Tasks.await(Link.delete(applicationContext, Uri.parse(it)), 30, TimeUnit.SECONDS) }
store.file(id).delete()
for (key in listOf("incoming", "outgoing")) {
val job = store.read(key) ?: continue
if (job.optString("id") == id && job.optString("state") !in setOf("installed", "failed", "declined")) {
if (key == "incoming") {
job.optInt("session", -1).takeIf { it >= 0 }?.let { runCatching { applicationContext.packageManager.packageInstaller.abandonSession(it) } }
applicationContext.getSystemService(android.app.NotificationManager::class.java).cancel(42)
}
if (key == "incoming") Link.status(applicationContext, job, "failed", "This APK expired. Send it again from your phone.")
else store.write(key, job.put("state", "failed").put("detail", "This transfer expired. Choose the file again."))
}
}
store.clean()
Result.success()
} catch (_: Exception) { if (runAttemptCount < 3) Result.retry() else Result.failure() }
}
}
@@ -0,0 +1,29 @@
package meghdad.pakkit.core
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", "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"))
}
}
+3 -3
View File
@@ -6,8 +6,8 @@ android {
applicationId = "meghdad.pakkit"
minSdk = 31
targetSdk = 36
versionCode = 100002
versionName = "0.1.0"
versionCode = 100003
versionName = "0.2.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
val releaseKey = providers.environmentVariable("PAKKIT_KEYSTORE").orNull
@@ -23,7 +23,7 @@ android {
buildTypes { release { signingConfig = signingConfigs.findByName("production"); isMinifyEnabled = true; isShrinkResources = true; proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "../proguard-rules.pro") } }
compileOptions { sourceCompatibility = JavaVersion.VERSION_11; targetCompatibility = JavaVersion.VERSION_11 }
}
dependencies { implementation(project(":shared")); androidTestImplementation(libs.androidx.junit); androidTestImplementation(libs.androidx.espresso.core) }
dependencies { implementation("com.google.zxing:core:3.5.3"); implementation(project(":shared")); androidTestImplementation(libs.androidx.junit); androidTestImplementation(libs.androidx.espresso.core) }
abstract class StageFixtureApk : DefaultTask() {
@get:InputFile abstract val fixtureFile: RegularFileProperty
@@ -0,0 +1,75 @@
package meghdad.pakkit.wear
import android.content.Intent
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import meghdad.pakkit.core.Store
import org.json.JSONObject
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import java.net.Socket
import java.net.URI
@RunWith(AndroidJUnit4::class)
class LocalReceiveTest {
@Test fun authenticatedUploadRequiresWatchConsentAndStopClosesListener() {
val instrumentation = InstrumentationRegistry.getInstrumentation()
val c = instrumentation.targetContext
val store = Store(c)
store.read("incoming")?.let { store.file(it.getString("id")).delete() }
store.clear("incoming")
c.startActivity(Intent(c, WatchActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
instrumentation.waitForIdleSync()
c.startForegroundService(Intent(c, ReceiveService::class.java))
val deadline = System.currentTimeMillis() + 30_000
while (store.prefs.getString("receiveUrl", null) == null && System.currentTimeMillis() < deadline) Thread.sleep(100)
val url = URI(requireNotNull(store.prefs.getString("receiveUrl", null)))
val origin = "http://${url.authority}"
val before = c.packageManager.packageInstaller.mySessions.map { it.sessionId }.toSet()
fun request(method: String, path: String, auth: Boolean = true, source: String = origin, body: ByteArray? = null): String {
return Socket(url.host, url.port).use { socket ->
socket.soTimeout = 10_000
val headers = "$method $path HTTP/1.1\r\nHost: ${url.authority}\r\n" +
(if (auth) "Authorization: Bearer ${url.fragment}\r\n" else "") +
"Origin: $source\r\n" + (body?.let { "Content-Type: application/octet-stream\r\nContent-Length: ${it.size}\r\n" } ?: "") + "\r\n"
socket.getOutputStream().write(headers.toByteArray())
body?.let { socket.getOutputStream().write(it) }
socket.getOutputStream().flush()
val input = socket.getInputStream().buffered()
val head = StringBuilder()
while (!head.endsWith("\r\n\r\n")) {
val next = input.read(); check(next >= 0); head.append(next.toChar())
}
val size = Regex("Content-Length: (\\d+)", RegexOption.IGNORE_CASE).find(head)!!.groupValues[1].toInt()
val bytes = ByteArray(size)
var position = 0
while (position < size) { val n = input.read(bytes, position, size - position); check(n > 0); position += n }
head.toString() + bytes.toString(Charsets.UTF_8)
}
}
try {
assertTrue(request("GET", "/").contains("Pocket"))
assertTrue(request("GET", "/api/status", false).startsWith("HTTP/1.1 403"))
assertTrue(request("POST", "/api/upload", source = "https://evil.example", body = byteArrayOf(1)).startsWith("HTTP/1.1 403"))
assertTrue(request("POST", "/api/upload", body = "invalid APK".toByteArray()).startsWith("HTTP/1.1 400"))
assertNull(store.read("incoming"))
val fixture = instrumentation.context.assets.open("fixture.apk").use { it.readBytes() }
assertTrue(request("POST", "/api/upload", body = fixture).startsWith("HTTP/1.1 200"))
val job = requireNotNull(store.read("incoming"))
assertEquals("ready", job.getString("state"))
assertEquals("meghdad.pakkit.fixture", job.getJSONObject("apk").getString("package"))
assertEquals(before, c.packageManager.packageInstaller.mySessions.map { it.sessionId }.toSet())
assertTrue(request("POST", "/api/upload", body = byteArrayOf(1)).startsWith("HTTP/1.1 409"))
assertTrue(request("GET", "/api/status").contains("ready"))
} finally {
c.stopService(Intent(c, ReceiveService::class.java))
val end = System.currentTimeMillis() + 5000
while (ReceiveService.active && System.currentTimeMillis() < end) Thread.sleep(50)
assertNull(store.prefs.getString("receiveUrl", null))
assertTrue(runCatching { Socket(url.host, url.port).close() }.isFailure)
store.read("incoming")?.let { store.file(it.getString("id")).delete() }
store.clear("incoming")
}
}
}
+8 -1
View File
@@ -2,15 +2,22 @@
<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"/>
<queries>
<intent><action android:name="android.settings.MANAGE_UNKNOWN_APP_SOURCES"/><data android:scheme="package"/></intent>
<intent><action android:name="android.intent.action.INSTALL_PACKAGE"/><data android:mimeType="application/vnd.android.package-archive"/></intent>
</queries>
<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.Wear">
<meta-data android:name="com.google.android.wearable.standalone" android:value="false"/>
<meta-data android:name="com.google.android.wearable.standalone" android:value="true"/>
<activity android:name=".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=".ReceiveService" android:exported="false" android:foregroundServiceType="connectedDevice"/>
<receiver android:name=".InstallReceiver" android:exported="false"/>
</application>
</manifest>
+104
View File
@@ -0,0 +1,104 @@
'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. Nothing was installed.');
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(); });
+16
View File
@@ -0,0 +1,16 @@
<!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>
+3
View File
@@ -0,0 +1,3 @@
: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:.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:.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 .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 .2s,border-color .2s,transform .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:-.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 .18s,box-shadow .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-sizeLine truncated
.brand-icon svg{width:29px;height:29px}
@@ -19,9 +19,9 @@ class InstallReceiver : BroadcastReceiver() {
when(status) {
PackageInstaller.STATUS_PENDING_USER_ACTION -> {
@Suppress("DEPRECATION") val confirmation=intent.getParcelableExtra<Intent>(Intent.EXTRA_INTENT)
if(confirmation==null) { Link.status(context,job,"failed","The system did not provide an approval screen."); return }
if(confirmation==null) { LocalInstall.status(context,job,"failed","The system did not provide an approval screen."); return }
PendingApproval.id=job.getString("id"); PendingApproval.intent=confirmation
Link.status(context,job,"confirm","Continue the system approval on your watch.")
LocalInstall.status(context,job,"confirm","Continue the system approval on your watch.")
val activity=PendingApproval.activity?.get()
if(activity!=null) activity.refresh()
val manager=context.getSystemService(NotificationManager::class.java)
@@ -36,7 +36,7 @@ class InstallReceiver : BroadcastReceiver() {
}
PackageInstaller.STATUS_SUCCESS -> {
PendingApproval.intent=null
Link.status(context,job,"installed","Installed on your watch.")
LocalInstall.status(context,job,"installed","Installed on your watch.")
store.file(job.getString("id")).delete()
context.getSystemService(NotificationManager::class.java).cancel(42)
}
@@ -51,7 +51,7 @@ class InstallReceiver : BroadcastReceiver() {
PackageInstaller.STATUS_FAILURE_STORAGE -> "Your watch needs more free storage."
else -> "The system could not finish installing. Try again or use Google Play."
}
Link.status(context,job,"failed",detail)
LocalInstall.status(context,job,"failed",detail)
context.getSystemService(NotificationManager::class.java).cancel(42)
}
}
@@ -0,0 +1,17 @@
package meghdad.pakkit.wear
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.Settings
import meghdad.pakkit.core.Store
import org.json.JSONObject
object LocalInstall {
fun settings(c: Context) = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:${c.packageName}"))
@Synchronized fun status(c: Context, job: JSONObject, state: String, detail: String) {
val updated = JSONObject(job.toString()).put("state", state).put("detail", detail)
Store(c).write("incoming", updated)
Store(c).history(job.getString("id"), job.getJSONObject("apk").getString("label"), state, detail)
}
}
@@ -0,0 +1,187 @@
package meghdad.pakkit.wear
import android.app.*
import android.content.*
import android.content.pm.ServiceInfo
import android.net.*
import android.os.*
import meghdad.pakkit.core.*
import org.json.JSONObject
import java.io.*
import java.net.*
import java.security.SecureRandom
import java.util.UUID
import java.util.concurrent.*
import java.util.concurrent.atomic.AtomicBoolean
/** A user-started, ten-minute local session. No auto start, discovery broadcast, or cloud traffic. */
class ReceiveService : Service() {
companion object {
const val DURATION = 10 * 60 * 1000L
@Volatile var active = false
const val STOP = "stop"
const val NOTICE = 81
}
private val handler = Handler(Looper.getMainLooper())
private val workers = ThreadPoolExecutor(2, 2, 0, TimeUnit.SECONDS, ArrayBlockingQueue(4), ThreadPoolExecutor.AbortPolicy())
private val sockets = ConcurrentHashMap.newKeySet<Socket>()
private val uploading = AtomicBoolean(false)
private var listener: ServerSocket? = null
private var network: Network? = null
private var registered = false
private var ended = false
private var authority = ""
private var token = ""
private var expires = 0L
private var wake: PowerManager.WakeLock? = null
private lateinit var store: Store
private val connectivity by lazy { getSystemService(ConnectivityManager::class.java) }
private val callback = object : ConnectivityManager.NetworkCallback() {
override fun onLinkPropertiesChanged(network: Network, properties: LinkProperties) {
handler.post { if (!ended && this@ReceiveService.network == null && properties.linkAddresses.isNotEmpty()) open(network, properties) }
}
override fun onLost(network: Network) { handler.post { if (network == this@ReceiveService.network) finish("Wi-Fi disconnected. Start a new session.") } }
override fun onUnavailable() { handler.post { finish("Connect your watch to Wi-Fi, then try again.") } }
}
override fun onBind(intent: Intent?) = null
override fun onCreate() { super.onCreate(); active = true; store = Store(this) }
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent?.action == STOP) { finish("Session ended"); return START_NOT_STICKY }
if (registered) 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(meghdad.pakkit.core.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()
if (Build.VERSION.SDK_INT >= 29) startForeground(NOTICE, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE)
else startForeground(NOTICE, notification)
store.prefs.edit().remove("receiveUrl").putString("receiveState", "Connecting to Wi-Fi…").apply()
expires = SystemClock.elapsedRealtime() + DURATION
handler.postDelayed({ finish("Session expired. Start a new session.") }, DURATION)
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(net: Network, properties: LinkProperties) {
try {
val address = properties.linkAddresses.map { it.address }
.firstOrNull { it is Inet4Address && it.isSiteLocalAddress } ?: error("A local Wi-Fi address is required")
network = net
val server = ServerSocket().apply { reuseAddress = true; bind(InetSocketAddress(address, 0), 4) }
listener = server
token = android.util.Base64.encodeToString(ByteArray(24).also { SecureRandom().nextBytes(it) }, android.util.Base64.URL_SAFE or android.util.Base64.NO_WRAP or android.util.Base64.NO_PADDING)
authority = "${address.hostAddress}:${server.localPort}"
wake = getSystemService(PowerManager::class.java).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "pakkit:receive").apply { acquire((expires - SystemClock.elapsedRealtime()).coerceAtLeast(1)) }
store.prefs.edit().putString("receiveUrl", "http://$authority/#$token")
.putString("receiveState", "Ready to receive").putLong("receiveExpires", System.currentTimeMillis() + (expires - SystemClock.elapsedRealtime())).apply()
Thread({
while (!server.isClosed) {
val socket = try { server.accept() } catch (_: IOException) { break }
socket.soTimeout = 15_000
sockets.add(socket)
try { workers.execute { socket.use { handle(it) }; sockets.remove(socket) } }
catch (_: RejectedExecutionException) { sockets.remove(socket); socket.close() }
}
}, "pakkit-listener").start()
} catch (e: Exception) { android.util.Log.w("PakkitReceive", "Cannot open receiving session", e); finish("Could not open local Wi-Fi. Check the network and try again.") }
}
private fun handle(socket: Socket) {
var replied = false
fun respond(code: Int, type: String, bytes: ByteArray) {
replied = true
val reason = when (code) { 200 -> "OK"; 400 -> "Bad Request"; 403 -> "Forbidden"; 409 -> "Conflict"; 404 -> "Not Found"; else -> "Error" }
val headers = "HTTP/1.1 $code $reason\r\nContent-Type: $type\r\nContent-Length: ${bytes.size}\r\nConnection: close\r\nCache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\nReferrer-Policy: no-referrer\r\nContent-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()); write(bytes); flush() }
}
fun json(code: Int, value: JSONObject) = respond(code, "application/json; charset=utf-8", value.toString().toByteArray())
try {
val input = BufferedInputStream(socket.getInputStream(), 8192)
val request = HttpProtocol.read(input)
require(!ended && SystemClock.elapsedRealtime() < expires)
if (request.headers["host"] != authority) { json(403, JSONObject().put("error", "Open the address shown on your watch.")); return }
if (request.method == "GET" && request.path in setOf("/", "/style.css", "/app.js")) {
val file = when (request.path) { "/" -> "index.html"; else -> request.path.drop(1) }
val type = when (file) { "index.html" -> "text/html; charset=utf-8"; "style.css" -> "text/css"; else -> "text/javascript" }
respond(200, type, assets.open("web/$file").use { it.readBytes() }); return
}
if (!HttpProtocol.authorized(request.headers["authorization"], token)) { json(403, JSONObject().put("error", "Open the private link or scan the QR code on your watch.")); return }
if (request.method == "GET" && request.path == "/api/status") {
val job = store.read("incoming")
val status = JSONObject().put("state", job?.optString("state") ?: "waiting")
.put("detail", job?.optString("detail") ?: "Your watch is ready.")
.put("label", job?.optJSONObject("apk")?.optString("label") ?: "")
.put("received", store.prefs.getLong("received", 0)).put("total", store.prefs.getLong("receiveTotal", 0))
.put("expiresIn", ((expires - SystemClock.elapsedRealtime()) / 1000).coerceAtLeast(0))
json(200, status); return
}
if (request.method != "POST" || request.path != "/api/upload") { json(404, JSONObject().put("error", "Not found")); return }
if (request.headers["origin"] != "http://$authority") { json(403, JSONObject().put("error", "Use Pakkit’s local page.")); return }
val length = HttpProtocol.uploadLength(request.headers)
if (!uploading.compareAndSet(false, true)) { json(409, JSONObject().put("error", "A transfer is already in progress.")); return }
var destination: File? = null
try {
if (store.read("incoming") != null) { json(409, JSONObject().put("error", "Finish or dismiss the current app on your watch first.")); return }
require(Packages.free(this) > length * 3 + 20 * 1024 * 1024) { "Free some storage on your watch first." }
val id = UUID.randomUUID().toString()
val file = store.file(id); destination = file
store.prefs.edit().putLong("receiveTotal", length).putLong("received", 0).putString("receiveState", "Receiving APK…").apply()
var received = 0L
var lastUpdate = 0L
val limited = object : InputStream() {
override fun read(): Int { val b = ByteArray(1); return if (read(b, 0, 1) < 0) -1 else b[0].toInt() and 255 }
override fun read(b: ByteArray, off: Int, len: Int): Int {
if (received == length) return -1
val n = input.read(b, off, minOf(len.toLong(), length - received).toInt())
require(n > 0) { "Transfer interrupted. Choose the file again." }
received += n
if (SystemClock.elapsedRealtime() - lastUpdate > 250 || received == length) {
lastUpdate = SystemClock.elapsedRealtime()
store.prefs.edit().putLong("received", received).apply()
}
return n
}
}
val digest = file.outputStream().use { TransferRules.copyBounded(limited, it).second }
store.prefs.edit().putString("receiveState", "Checking APK…").apply()
val apk = Packages.inspect(this, file, digest)
Packages.checkForWatch(apk, Build.VERSION.SDK_INT, Build.SUPPORTED_ABIS.toSet(), Packages.free(this))
require(!ended) { "The receiving session ended. Try again." }
store.write("incoming", JSONObject().put("id", id).put("created", System.currentTimeMillis())
.put("source", "local-browser").put("apk", apk.json()).put("state", "ready")
.put("detail", "Review this app and approve installation on your watch."))
destination = null
store.prefs.edit().putString("receiveState", "Ready to install").apply()
json(200, JSONObject().put("label", apk.label).put("state", "ready"))
} finally {
destination?.delete(); uploading.set(false)
store.prefs.edit().putLong("received", 0).putLong("receiveTotal", 0).apply()
}
} catch (e: Exception) {
store.prefs.edit().putString("receiveState", "Ready to receive").apply()
if (!replied) runCatching { json(400, JSONObject().put("error", e.message?.take(180) ?: "Transfer interrupted. Try again.")) }
}
}
private fun finish(message: String) {
if (ended) return
ended = true
store.prefs.edit().remove("receiveUrl").putString("receiveState", message).apply()
stopForeground(STOP_FOREGROUND_REMOVE); stopSelf()
}
override fun onDestroy() {
ended = true
active = false
handler.removeCallbacksAndMessages(null)
listener?.close()
sockets.forEach { runCatching { it.close() } }
workers.shutdownNow()
if (registered) runCatching { connectivity.unregisterNetworkCallback(callback) }
wake?.let { if (it.isHeld) it.release() }
store.prefs.edit().remove("receiveUrl").putLong("received", 0).putLong("receiveTotal", 0).apply()
super.onDestroy()
}
}
@@ -25,9 +25,18 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
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 = Store(this)
if (!ReceiveService.active) store.prefs.edit().remove("receiveUrl").apply()
store.read("incoming")?.let { job ->
if (!TransferRules.fresh(job.optLong("created"), System.currentTimeMillis())) {
runCatching { store.file(job.getString("id")).delete() }; store.clear("incoming")
}
}
store.clean()
acceptIntent(intent)
refresh()
savedInstanceState?.getInt("scroll")?.let { y -> scroll.post { scroll.scrollTo(0, y) } }
@@ -50,12 +59,12 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
PendingApproval.activity = WeakReference(this)
store.prefs.registerOnSharedPreferenceChangeListener(this)
refresh()
io.execute { runCatching { Link.capability(this) } }
}
override fun onPause() { store.prefs.unregisterOnSharedPreferenceChangeListener(this); PendingApproval.activity = null; super.onPause() }
override fun onDestroy() { io.shutdown(); super.onDestroy() }
override fun onSharedPreferenceChanged(prefs: SharedPreferences?, key: String?) {
if (key == "incoming" || key == null) runOnUiThread { refresh() }
if (key == "incoming" || key == null || key == "receiveState" || key == "receiveUrl" || key == "received") runOnUiThread { refresh() }
}
private fun dp(n: Int) = Design.dp(this, n)
private fun line(value: String, size: Float = 14f, color: Int = colors.text, bold: Boolean = false) = Design.text(this, value, size, color, bold).apply {
@@ -115,7 +124,10 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
gravity = Gravity.CENTER; textSize = 12f; setTextColor(colors.secondary)
importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
})
if (job == null) home() else incoming(job)
if (job == null) home() else {
incoming(job)
if (store.prefs.getString("receiveUrl", null) != 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
@@ -124,35 +136,65 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
scroll.post { scroll.scrollTo(0, y) }
}
private fun home() {
parcel(54)
add(line("Pakkit", 25f, bold = true), 4)
add(line(getString(meghdad.pakkit.core.R.string.brand_tagline), 12f, colors.secondary), 5)
val supported = Link.installer(this)
val allowed = packageManager.canRequestPackageInstalls()
when {
!supported -> {
badge("Use Google Play")
add(line("This watch does not expose a system installer.", 13f, colors.secondary), 12)
button("Open Google Play") { play() }
val url = store.prefs.getString("receiveUrl", null)
if (url == null) {
parcel(54)
add(line("Pakkit", 25f, bold = true), 4)
add(line(getString(meghdad.pakkit.core.R.string.brand_tagline), 12f, colors.secondary), 5)
}
if (url != null) {
val received = store.prefs.getLong("received", 0)
val total = store.prefs.getLong("receiveTotal", 0)
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)
}
allowed -> {
badge("Ready to receive", positive = true)
add(line("Choose an APK on your phone. Review it here before installing.", 13f, 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("Send an APK straight to your wrist. No phone app needed.", 14f, colors.secondary), 12)
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() }
}
Link.settings(this).resolveActivity(packageManager) != null -> {
badge("One small permission")
add(line("Allow Pakkit to request installs. You still approve every app.", 13f, colors.secondary), 12)
button("Allow installs") { settings() }
}
else -> {
badge("Use Google Play")
add(line("External installation is not available on this watch’s software.", 13f, colors.secondary), 12)
button("Open Google Play") { play() }
add(line(store.prefs.getString("receiveState", "Connect your watch and browser to the same Wi-Fi.").orEmpty(), 12f, colors.secondary), 12)
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) {
add(line("Optional alerts bring you back to system approval.", 12f, colors.secondary), 18)
button("Enable alerts", false) { requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), 52) }
button("Enable session alerts", false) { requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), 52) }
}
}
private fun incoming(job: JSONObject) {
@@ -185,7 +227,7 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
}
"ready", "failed" -> {
if (!TransferRules.fresh(job.optLong("created"), System.currentTimeMillis())) {
add(line("This APK expired. Send it again from your phone.", 13f, colors.error), 12)
add(line("This APK expired. Upload it again from your browser.", 13f, colors.error), 12)
} else if (store.file(job.getString("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)
@@ -217,7 +259,7 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
}
}
private fun settings() {
runCatching { startActivity(Link.settings(this)) }.onFailure { error="This watch does not offer that setting. Install compatible apps through Google Play."; refresh() }
runCatching { startActivity(LocalInstall.settings(this)) }.onFailure { error="This watch does not offer that setting. Install compatible apps through Google Play."; refresh() }
}
private fun install(job:JSONObject) {
if(busy) return
@@ -241,7 +283,7 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
}
sessionId=installer.createSession(params)
job.put("session",sessionId)
Link.status(this,job,"installing","Waiting for the watch’s system installer.")
LocalInstall.status(this,job,"installing","Waiting for the watch’s system installer.")
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(this,InstallReceiver::class.java).putExtra("job",job.getString("id"))
@@ -250,13 +292,13 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
}
} catch(e:Exception) {
sessionId?.let { runCatching { installer.abandonSession(it) } }
Link.status(this,job,"failed",e.message ?: "Could not open the system installer. Use Google Play.")
LocalInstall.status(this,job,"failed",e.message ?: "Could not open the system installer. Use Google Play.")
}
runOnUiThread { busy=false; refresh() }
}
}
private fun dismiss(job:JSONObject) {
Link.status(this,job,"declined","Dismissed on your watch.")
LocalInstall.status(this,job,"declined","Dismissed on your watch.")
store.file(job.getString("id")).delete(); store.clear("incoming"); refresh()
}
private fun launch(packageName:String) {
-1
View File
@@ -1 +0,0 @@
<resources xmlns:tools="http://schemas.android.com/tools" tools:keep="@array/android_wear_capabilities"/>
-1
View File
@@ -1 +0,0 @@
<resources xmlns:tools="http://schemas.android.com/tools"><string-array name="android_wear_capabilities" translatable="false" tools:ignore="Typos,UnusedResources"><item>pakkit_watch_v1</item></string-array></resources>