feat: simplify receiving and remove arbitrary limits
- Use fixed port 8787 and reconnect automatically after Wi-Fi loss - Remove session expiry, APK expiry, size caps, and upload deadlines - Replace manual keys with watch-approved browser access - Improve streaming, storage recovery, and resource cleanup - Preserve explicit Android installation consent - Document retained safeguards and expand emulator coverage
This commit is contained in:
41 files changed
+1241
-561
No files matched your search
@@ -14,16 +14,17 @@ import org.junit.runner.RunWith
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class LocalReceiveTest : WatchTest() {
|
||||
@Test
|
||||
fun authenticatedUploadVerifiesPackageAndStopRevokesPrivateLink() {
|
||||
fun watchApprovedBrowserCanUploadAndStoppingRevokesAccess() {
|
||||
openWatch()
|
||||
context.startForegroundService(Intent(context, ReceiveService::class.java))
|
||||
await(30_000) { Receiving.state.url != null }
|
||||
val url = URI(requireNotNull(Receiving.state.url))
|
||||
val sessions = context.packageManager.packageInstaller.mySessions.map { it.sessionId }
|
||||
var browserCredential: String? = null
|
||||
fun request(
|
||||
method: String,
|
||||
path: String,
|
||||
token: String? = url.fragment,
|
||||
credential: String? = browserCredential,
|
||||
origin: String = "http://${url.authority}",
|
||||
host: String = url.authority,
|
||||
body: ByteArray? = null,
|
||||
@@ -33,8 +34,8 @@ class LocalReceiveTest : WatchTest() {
|
||||
socket.soTimeout = 10_000
|
||||
val headers =
|
||||
"$method $path HTTP/1.1\r\nHost: $host\r\n" +
|
||||
(token?.let { "Authorization: Bearer $it\r\n" } ?: "") +
|
||||
"Origin: $origin\r\n" +
|
||||
(credential?.let { "Authorization: Bearer $it\r\n" } ?: "") +
|
||||
"Origin: $origin\r\nUser-Agent: Chrome Android\r\n" +
|
||||
(contentLength?.let {
|
||||
"Content-Type: application/octet-stream\r\nContent-Length: $it\r\n"
|
||||
} ?: "") +
|
||||
@@ -67,11 +68,26 @@ class LocalReceiveTest : WatchTest() {
|
||||
head.toString() + bytes.toString(Charsets.UTF_8)
|
||||
}
|
||||
}
|
||||
fun assertUploadWakeReleased() {
|
||||
await { Receiving.state.total == 0L }
|
||||
val dump =
|
||||
instrumentation.uiAutomation.executeShellCommand("dumpsys power").use { descriptor
|
||||
->
|
||||
android.os.ParcelFileDescriptor.AutoCloseInputStream(descriptor).use {
|
||||
it.readBytes().toString(Charsets.UTF_8)
|
||||
}
|
||||
}
|
||||
assertTrue("Power state must be observable", dump.contains("Wake Locks:"))
|
||||
assertFalse(
|
||||
"Completed requests must not hold an upload wake lock",
|
||||
Regex("(?m)^\\s*PARTIAL_WAKE_LOCK.*pakkit:upload.*$").containsMatchIn(dump),
|
||||
)
|
||||
}
|
||||
assertTrue(request("GET", "/").contains("Pack it."))
|
||||
assertTrue(request("GET", "/api/status", token = null).startsWith("HTTP/1.1 403"))
|
||||
assertTrue(request("GET", "/api/status", token = "wrong").startsWith("HTTP/1.1 403"))
|
||||
assertTrue(request("GET", "/api/status", credential = null).startsWith("HTTP/1.1 403"))
|
||||
assertTrue(request("GET", "/api/status", credential = "wrong").startsWith("HTTP/1.1 403"))
|
||||
assertTrue(
|
||||
request("GET", "/api/status", host = "attacker.example").startsWith("HTTP/1.1 403"),
|
||||
request("GET", "/api/status", host = "attacker.example").startsWith("HTTP/1.1 403")
|
||||
)
|
||||
assertTrue(
|
||||
request(
|
||||
@@ -80,23 +96,33 @@ class LocalReceiveTest : WatchTest() {
|
||||
origin = "https://attacker.example",
|
||||
body = byteArrayOf(1),
|
||||
)
|
||||
.startsWith("HTTP/1.1 403"),
|
||||
.startsWith("HTTP/1.1 403")
|
||||
)
|
||||
val connection = request("POST", "/api/connect")
|
||||
browserCredential =
|
||||
org.json.JSONObject(connection.substringAfter("\r\n\r\n")).getString("credential")
|
||||
assertFalse(connection.contains("Set-Cookie:"))
|
||||
assertTrue(request("POST", "/api/upload", body = byteArrayOf(1)).startsWith("HTTP/1.1 403"))
|
||||
assertTrue(request("GET", "/api/status").contains("pending"))
|
||||
assertTrue(Receiving.answerBrowser(requireNotNull(Receiving.state.browserRequest).id, true))
|
||||
assertTrue(request("GET", "/api/status").startsWith("HTTP/1.1 200"))
|
||||
assertFalse(request("GET", "/api/status").contains("expiresIn"))
|
||||
assertTrue(
|
||||
request("POST", "/api/upload", contentLength = 52_428_801).startsWith("HTTP/1.1 400"),
|
||||
request("POST", "/api/upload", contentLength = Long.MAX_VALUE).contains("storage")
|
||||
)
|
||||
assertTrue(
|
||||
request("POST", "/api/upload", body = "invalid APK".toByteArray())
|
||||
.startsWith("HTTP/1.1 400"),
|
||||
.startsWith("HTTP/1.1 400")
|
||||
)
|
||||
assertNull(store.pending())
|
||||
assertTrue(
|
||||
request("POST", "/api/upload", body = "short".toByteArray(), contentLength = 100)
|
||||
.startsWith("HTTP/1.1 400"),
|
||||
.startsWith("HTTP/1.1 400")
|
||||
)
|
||||
assertNull(store.pending())
|
||||
assertEquals(0L, Receiving.state.total)
|
||||
assertEquals("Ready to receive", Receiving.state.detail)
|
||||
assertUploadWakeReleased()
|
||||
val fixture = instrumentation.context.assets.open("fixture.apk").use { it.readBytes() }
|
||||
assertTrue(request("POST", "/api/upload", body = fixture).startsWith("HTTP/1.1 200"))
|
||||
assertEquals(InstallState.READY, store.pending()?.state)
|
||||
@@ -107,10 +133,48 @@ class LocalReceiveTest : WatchTest() {
|
||||
)
|
||||
assertTrue(request("POST", "/api/upload", body = byteArrayOf(1)).startsWith("HTTP/1.1 409"))
|
||||
assertTrue(request("GET", "/api/status").contains("ready"))
|
||||
assertUploadWakeReleased()
|
||||
// A finished install does not require a separate Done tap before the next upload.
|
||||
for (terminal in listOf(InstallState.INSTALLED, InstallState.FAILED)) {
|
||||
store.update(requireNotNull(store.pending()).id, terminal, "Finished")
|
||||
assertTrue(request("POST", "/api/upload", body = fixture).startsWith("HTTP/1.1 200"))
|
||||
assertEquals(InstallState.READY, store.pending()?.state)
|
||||
}
|
||||
context.stopService(Intent(context, ReceiveService::class.java))
|
||||
await { !Receiving.state.active }
|
||||
assertNull(Receiving.state.url)
|
||||
assertTrue(runCatching { Socket(url.host, url.port).close() }.isFailure)
|
||||
context.startForegroundService(Intent(context, ReceiveService::class.java))
|
||||
await(30_000) { Receiving.state.url != null }
|
||||
assertEquals(url.toString(), Receiving.state.url)
|
||||
assertTrue(request("GET", "/api/status").startsWith("HTTP/1.1 403"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun losingWifiWaitsForReconnectionWithoutEndingReceiving() {
|
||||
openWatch()
|
||||
context.startForegroundService(Intent(context, ReceiveService::class.java))
|
||||
await(30_000) { Receiving.state.url != null }
|
||||
fun shell(command: String) {
|
||||
instrumentation.uiAutomation.executeShellCommand(command).use { descriptor ->
|
||||
android.os.ParcelFileDescriptor.AutoCloseInputStream(descriptor).use {
|
||||
it.readBytes()
|
||||
}
|
||||
}
|
||||
}
|
||||
try {
|
||||
shell("cmd wifi set-wifi-enabled disabled")
|
||||
await(15_000) { Receiving.state.url == null }
|
||||
assertTrue(Receiving.state.active)
|
||||
shell("cmd wifi set-wifi-enabled enabled")
|
||||
shell("cmd wifi connect-network AndroidWifi open")
|
||||
await(30_000) { Receiving.state.url != null }
|
||||
assertTrue(Receiving.state.active)
|
||||
assertEquals(8787, URI(requireNotNull(Receiving.state.url)).port)
|
||||
} finally {
|
||||
shell("cmd wifi set-wifi-enabled enabled")
|
||||
shell("cmd wifi connect-network AndroidWifi open")
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -7,16 +7,30 @@ import java.util.zip.ZipEntry
|
||||
import java.util.zip.ZipOutputStream
|
||||
import meghdad.pakkit.apk.ApkRules
|
||||
import meghdad.pakkit.apk.PackageInspector
|
||||
import meghdad.pakkit.apk.userMessage
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class PackageInspectionTest : WatchTest() {
|
||||
@Test
|
||||
fun runningOutOfSpaceHasActionableFeedbackWithoutRawPaths() {
|
||||
val failure =
|
||||
java.io.IOException(
|
||||
"/data/private/file.apk",
|
||||
android.system.ErrnoException("write", android.system.OsConstants.ENOSPC),
|
||||
)
|
||||
assertEquals(
|
||||
"Free some space on your watch, then try again.",
|
||||
failure.userMessage("Try again."),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun selfUpdateIsRejectedBeforeCreatingAnInstallSession() {
|
||||
val ownApk = File(context.applicationInfo.sourceDir)
|
||||
val digest = ownApk.inputStream().use { ApkRules.copyBounded(it).second }
|
||||
val digest = ownApk.inputStream().use { ApkRules.copyAndHash(it).second }
|
||||
val result = runCatching { PackageInspector.inspect(context, ownApk, digest) }
|
||||
assertTrue(result.isFailure)
|
||||
assertTrue(result.exceptionOrNull()?.message.orEmpty().contains("Google Play"))
|
||||
@@ -31,7 +45,7 @@ class PackageInspectionTest : WatchTest() {
|
||||
it.write("Not an app".toByteArray())
|
||||
it.closeEntry()
|
||||
}
|
||||
val digest = file.inputStream().use { ApkRules.copyBounded(it).second }
|
||||
val digest = file.inputStream().use { ApkRules.copyAndHash(it).second }
|
||||
assertTrue(runCatching { PackageInspector.inspect(context, file, digest) }.isFailure)
|
||||
} finally {
|
||||
file.delete()
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package meghdad.pakkit
|
||||
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import meghdad.pakkit.apk.ApkRules
|
||||
import meghdad.pakkit.apk.InstallState
|
||||
import meghdad.pakkit.data.PackageStore
|
||||
import org.junit.Assert.*
|
||||
@@ -10,6 +9,49 @@ import org.junit.runner.RunWith
|
||||
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class PackageStoreTest : WatchTest() {
|
||||
@Test
|
||||
fun failedMetadataWriteRestoresThePreviousReview() {
|
||||
val apk = fixture()
|
||||
store.stage(apk)
|
||||
var failNext = true
|
||||
val real = store.preferences
|
||||
val faulty =
|
||||
object : android.content.SharedPreferences by real {
|
||||
override fun edit(): android.content.SharedPreferences.Editor {
|
||||
val editor = real.edit()
|
||||
return object : android.content.SharedPreferences.Editor by editor {
|
||||
override fun putString(
|
||||
key: String,
|
||||
value: String?,
|
||||
): android.content.SharedPreferences.Editor {
|
||||
editor.putString(key, value)
|
||||
return this
|
||||
}
|
||||
|
||||
override fun commit(): Boolean {
|
||||
val written = editor.commit()
|
||||
if (failNext) {
|
||||
failNext = false
|
||||
return false
|
||||
}
|
||||
return written
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
val wrapped =
|
||||
object : android.content.ContextWrapper(context) {
|
||||
override fun getSharedPreferences(name: String, mode: Int) = faulty
|
||||
}
|
||||
assertTrue(
|
||||
runCatching {
|
||||
PackageStore(wrapped).update(apk.id, InstallState.INSTALLING, "Preparing")
|
||||
}
|
||||
.isFailure
|
||||
)
|
||||
assertEquals(apk, store.pending())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun persistsReviewAcrossStoreInstancesAndRejectsReplacement() {
|
||||
val apk = fixture()
|
||||
@@ -20,14 +62,14 @@ class PackageStoreTest : WatchTest() {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun expiredReviewAndOrphanedFileAreRemoved() {
|
||||
val apk = fixture().copy(created = System.currentTimeMillis() - ApkRules.TTL_MS)
|
||||
fun oldReviewsRemainAvailableAndUncommittedFilesAreCleaned() {
|
||||
val apk = fixture().copy(created = 1L)
|
||||
store.stage(apk)
|
||||
val orphan = fixture()
|
||||
store.file(orphan.id).setLastModified(System.currentTimeMillis() - ApkRules.TTL_MS - 1000)
|
||||
store.file(orphan.id).setLastModified(System.currentTimeMillis())
|
||||
store.clean()
|
||||
assertNull(store.pending())
|
||||
assertFalse(store.file(apk.id).exists())
|
||||
assertEquals(apk, store.pending())
|
||||
assertTrue(store.file(apk.id).exists())
|
||||
assertFalse(store.file(orphan.id).exists())
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
package meghdad.pakkit
|
||||
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import java.net.BindException
|
||||
import java.net.Inet4Address
|
||||
import java.net.InetAddress
|
||||
import meghdad.pakkit.transfer.LocalHttpServer
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class ReceiverLifecycleTest : WatchTest() {
|
||||
@Test
|
||||
fun ipv6ListenerAcceptsCanonicalBrowserAuthority() {
|
||||
LocalHttpServer(context, InetAddress.getByName("::1"), Any()).use { server ->
|
||||
server.start()
|
||||
val response =
|
||||
java.net.Socket(InetAddress.getByName("::1"), 8787).use { socket ->
|
||||
socket.soTimeout = 5000
|
||||
socket
|
||||
.getOutputStream()
|
||||
.write("GET / HTTP/1.1\r\nHost: [::1]:8787\r\n\r\n".toByteArray())
|
||||
socket.getInputStream().bufferedReader().readText()
|
||||
}
|
||||
assertTrue(response.startsWith("HTTP/1.1 200"))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun portIsFixedAndBusyPortsNeverSilentlyChangeTheAddress() {
|
||||
val address = InetAddress.getByName("127.0.0.1") as Inet4Address
|
||||
LocalHttpServer(context, address, Any()).use { server ->
|
||||
assertEquals("http://127.0.0.1:8787/", server.url)
|
||||
val failure = runCatching {
|
||||
LocalHttpServer(context, address, Any()).close()
|
||||
}
|
||||
.exceptionOrNull()
|
||||
assertTrue(failure is BindException)
|
||||
}
|
||||
LocalHttpServer(context, address, Any()).use {
|
||||
assertEquals("http://127.0.0.1:8787/", it.url)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
package meghdad.pakkit
|
||||
|
||||
import android.os.SystemClock
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import java.net.Inet4Address
|
||||
import java.net.InetAddress
|
||||
import java.net.Socket
|
||||
import java.net.URI
|
||||
import meghdad.pakkit.transfer.LocalHttpServer
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class ServerExpiryTest : WatchTest() {
|
||||
@Test
|
||||
fun expiredSessionRefusesRequestsEvenWithTheCorrectKey() {
|
||||
val address = InetAddress.getByName("127.0.0.1") as Inet4Address
|
||||
LocalHttpServer(context, address, SystemClock.elapsedRealtime() - 1, Any()).use { server ->
|
||||
server.start()
|
||||
val url = URI(server.url)
|
||||
val response =
|
||||
Socket(url.host, url.port).use { socket ->
|
||||
socket.soTimeout = 5000
|
||||
val request =
|
||||
"GET /api/status HTTP/1.1\r\nHost: ${url.authority}\r\nAuthorization: Bearer ${url.fragment}\r\n\r\n"
|
||||
socket.getOutputStream().write(request.toByteArray())
|
||||
socket.getInputStream().bufferedReader().readText()
|
||||
}
|
||||
assertTrue(response.startsWith("HTTP/1.1 400"))
|
||||
assertTrue(response.contains("didn’t arrive"))
|
||||
assertNull(store.pending())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -104,21 +104,24 @@ class WatchExperienceTest : WatchTest() {
|
||||
val owner = Any()
|
||||
try {
|
||||
Receiving.begin(owner)
|
||||
Receiving.update(owner) { it.copy(url = "http://10.0.2.16:8080/#test-display-link") }
|
||||
Receiving.update(owner) { it.copy(url = "http://10.0.2.16:8787/") }
|
||||
openWatch()
|
||||
capture("scan")
|
||||
instrumentation.runOnMainSync {
|
||||
screen().filterIsInstance<Button>().single { it.text == "View link" }.performClick()
|
||||
assertActionsReachable()
|
||||
Receiving.update(owner) {
|
||||
it.copy(
|
||||
browserRequest =
|
||||
meghdad.pakkit.transfer.BrowserAccess.Request(
|
||||
"test-browser",
|
||||
"Chrome on Android",
|
||||
"10.0.2.17",
|
||||
)
|
||||
)
|
||||
}
|
||||
instrumentation.waitForIdleSync()
|
||||
assertActionsReachable()
|
||||
capture("link")
|
||||
instrumentation.runOnMainSync {
|
||||
screen()
|
||||
.filterIsInstance<Button>()
|
||||
.single { it.text == "Back to code" }
|
||||
.performClick()
|
||||
}
|
||||
capture("browser-approval")
|
||||
Receiving.update(owner) { it.copy(browserRequest = null) }
|
||||
Receiving.update(owner) { it.copy(total = 1000, received = 420) }
|
||||
instrumentation.waitForIdleSync()
|
||||
capture("sending")
|
||||
|
||||
@@ -34,7 +34,7 @@ abstract class WatchTest {
|
||||
val monitor = instrumentation.addMonitor(WatchActivity::class.java.name, null, false)
|
||||
context.startActivity(
|
||||
Intent(context, WatchActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK),
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
|
||||
)
|
||||
activity = requireNotNull(monitor.waitForActivityWithTimeout(5000))
|
||||
instrumentation.removeMonitor(monitor)
|
||||
@@ -46,7 +46,7 @@ abstract class WatchTest {
|
||||
val file = store.file(id)
|
||||
val digest =
|
||||
instrumentation.context.assets.open("fixture.apk").use { input ->
|
||||
file.outputStream().use { ApkRules.copyBounded(input, it).second }
|
||||
file.outputStream().use { ApkRules.copyAndHash(input, it).second }
|
||||
}
|
||||
return PendingApk(
|
||||
id,
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE" />
|
||||
|
||||
<application
|
||||
android:name=".PakkitApplication"
|
||||
android:allowBackup="false"
|
||||
android:dataExtractionRules="@xml/pakkit_data_rules"
|
||||
android:icon="@mipmap/pakkit_launcher"
|
||||
|
||||
@@ -1,18 +1,25 @@
|
||||
'use strict';
|
||||
const $ = (id) => document.getElementById(id);
|
||||
let token = location.hash.slice(1),
|
||||
file = null,
|
||||
let file = null,
|
||||
upload = null,
|
||||
online = false,
|
||||
pending = false;
|
||||
pending = false,
|
||||
choosingNext = false;
|
||||
// Storage is isolated by scheme + host + port. No cookie can leak access to another
|
||||
// app's server on a different port of the same watch. Nothing is copied by the user.
|
||||
let credential = '';
|
||||
function accessHeaders() {
|
||||
try {
|
||||
credential = localStorage.getItem('pakkitAccess') || credential;
|
||||
} catch {}
|
||||
return credential ? { Authorization: 'Bearer ' + credential } : {};
|
||||
}
|
||||
const initialTheme = window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark';
|
||||
document.documentElement.dataset.theme = initialTheme;
|
||||
$('theme').onclick = () => {
|
||||
document.documentElement.dataset.theme =
|
||||
document.documentElement.dataset.theme === 'dark' ? 'light' : 'dark';
|
||||
};
|
||||
// Keep the secret out of subsequent navigation, referrers and visible browser history.
|
||||
if (token) history.replaceState(null, '', location.pathname);
|
||||
function setText(id, value) {
|
||||
if ($(id).textContent !== value) $(id).textContent = value;
|
||||
}
|
||||
@@ -27,25 +34,21 @@ function panel(id) {
|
||||
item.classList.toggle('complete', index < step);
|
||||
});
|
||||
$('progress-panel').setAttribute('aria-busy', String(id === 'progress-panel'));
|
||||
['dropzone', 'selection', 'progress-panel', 'result'].forEach(
|
||||
['pairing', 'dropzone', 'selection', 'progress-panel', 'result'].forEach(
|
||||
(key) => ($(key).hidden = key !== id),
|
||||
);
|
||||
}
|
||||
function selected(next) {
|
||||
if (!online || pending || upload) return;
|
||||
message();
|
||||
if (
|
||||
!next ||
|
||||
!next.name.toLowerCase().endsWith('.apk') ||
|
||||
next.size === 0 ||
|
||||
next.size > 50 * 1024 * 1024
|
||||
) {
|
||||
message('Choose a single APK up to 50 MB. Bundles and split APKs won’t work here.');
|
||||
if (!next || next.size === 0) {
|
||||
message('This file is empty. Choose an app to send.');
|
||||
return;
|
||||
}
|
||||
file = next;
|
||||
$('filename').textContent = file.name;
|
||||
$('filesize').textContent = (file.size / 1048576).toFixed(1) + ' MB · ready to send';
|
||||
$('filesize').dataset.bytes = String(file.size);
|
||||
$('filesize').textContent = formatSize(file.size) + ' · ready to send';
|
||||
panel('selection');
|
||||
$('send').focus({ preventScroll: true });
|
||||
}
|
||||
@@ -100,9 +103,9 @@ $('send').onclick = () => {
|
||||
const xhr = new XMLHttpRequest();
|
||||
upload = xhr;
|
||||
xhr.open('POST', '/api/upload');
|
||||
xhr.setRequestHeader('Authorization', 'Bearer ' + token);
|
||||
Object.entries(accessHeaders()).forEach(([name, value]) => xhr.setRequestHeader(name, value));
|
||||
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
|
||||
xhr.timeout = 300000;
|
||||
// No total upload timeout. A slow, progressing transfer is allowed to finish.
|
||||
xhr.upload.onprogress = (e) => {
|
||||
if (!e.lengthComputable) return;
|
||||
const percent = Math.floor((e.loaded / e.total) * 100);
|
||||
@@ -133,14 +136,13 @@ $('send').onclick = () => {
|
||||
return;
|
||||
}
|
||||
pending = true;
|
||||
choosingNext = false;
|
||||
file = null;
|
||||
result('Made it to your watch', 'Review ' + data.label + ' on your watch.');
|
||||
poll();
|
||||
};
|
||||
xhr.onerror = () =>
|
||||
failed('Connection lost. Check that both devices are on the same Wi-Fi, then try again.');
|
||||
xhr.ontimeout = () =>
|
||||
failed('That took too long. Open a fresh link from your watch and try again.');
|
||||
failed('Connection lost. Your file is ready to send again when your watch reconnects.');
|
||||
xhr.onabort = () => failed('Transfer cancelled. Your app may have arrived—check your watch.');
|
||||
xhr.send(file);
|
||||
};
|
||||
@@ -148,54 +150,88 @@ $('cancel').onclick = () => upload?.abort();
|
||||
$('again').onclick = () => {
|
||||
if (!pending) {
|
||||
file = null;
|
||||
choosingNext = true;
|
||||
panel('dropzone');
|
||||
message();
|
||||
}
|
||||
};
|
||||
$('access-form').onsubmit = (e) => {
|
||||
e.preventDefault();
|
||||
token = $('access').value.trim().replace(/^.*#/, '');
|
||||
$('access').value = '';
|
||||
poll();
|
||||
function formatSize(bytes) {
|
||||
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
|
||||
const unit = Math.min(Math.floor(Math.log10(Math.max(bytes, 1)) / 3), units.length - 1);
|
||||
return (
|
||||
new Intl.NumberFormat(undefined, { maximumFractionDigits: 1 }).format(bytes / 1000 ** unit) +
|
||||
' ' +
|
||||
units[unit]
|
||||
);
|
||||
}
|
||||
function pairing(state) {
|
||||
online = false;
|
||||
document.querySelector('.connection').dataset.online = 'false';
|
||||
setText('connection', state === 'denied' ? 'Not connected' : 'Waiting for your watch');
|
||||
$('choose').disabled = true;
|
||||
$('send').disabled = true;
|
||||
panel('pairing');
|
||||
setText('pairing-title', state === 'denied' ? 'Maybe next time?' : 'A quick hello');
|
||||
setText(
|
||||
'pairing-detail',
|
||||
state === 'denied'
|
||||
? 'Your watch declined this browser.'
|
||||
: state === 'busy'
|
||||
? 'Your watch is connecting another browser. We’ll wait here.'
|
||||
: 'Tap Allow browser on your watch. You only need to do this once while receiving is on.',
|
||||
);
|
||||
$('retry-connection').hidden = state !== 'denied';
|
||||
}
|
||||
async function connect(retry = false) {
|
||||
const response = await fetch(retry ? '/api/retry' : '/api/connect', {
|
||||
method: 'POST',
|
||||
headers: accessHeaders(),
|
||||
});
|
||||
if (!response.ok) throw new Error('disconnected');
|
||||
const data = await response.json();
|
||||
if (data.credential) {
|
||||
credential = data.credential;
|
||||
try {
|
||||
localStorage.setItem('pakkitAccess', credential);
|
||||
} catch {}
|
||||
}
|
||||
pairing(data.connection);
|
||||
}
|
||||
$('retry-connection').onclick = () => {
|
||||
connect(true).catch(() => message('Open Pakkit on your watch and start receiving.'));
|
||||
};
|
||||
let polling = false;
|
||||
async function poll() {
|
||||
if (polling || !token) return;
|
||||
if (polling) return;
|
||||
polling = true;
|
||||
try {
|
||||
const response = await fetch('/api/status', {
|
||||
headers: { Authorization: 'Bearer ' + token },
|
||||
headers: accessHeaders(),
|
||||
cache: 'no-store',
|
||||
signal: AbortSignal.timeout ? AbortSignal.timeout(5000) : undefined,
|
||||
});
|
||||
if (response.status === 403) {
|
||||
online = false;
|
||||
document.querySelector('.connection').dataset.online = 'false';
|
||||
$('access-form').hidden = false;
|
||||
$('choose').disabled = true;
|
||||
$('connection').textContent = 'Let’s connect';
|
||||
message('Scan the code on your watch to reconnect.');
|
||||
const data = await response.json();
|
||||
if (data.connection === 'unknown') await connect();
|
||||
else pairing(data.connection);
|
||||
return;
|
||||
}
|
||||
if (!response.ok) throw new Error('disconnected');
|
||||
const data = await response.json();
|
||||
if (!online) message();
|
||||
if (!online) {
|
||||
message();
|
||||
if (!pending && !upload) panel(file ? 'selection' : 'dropzone');
|
||||
}
|
||||
online = true;
|
||||
$('send').disabled = false;
|
||||
$('access-form').hidden = true;
|
||||
setText('connection', 'Connected to your watch');
|
||||
document.querySelector('.connection').dataset.online = 'true';
|
||||
$('expiry').textContent =
|
||||
'· ' +
|
||||
Math.floor(data.expiresIn / 60) +
|
||||
':' +
|
||||
String(data.expiresIn % 60).padStart(2, '0') +
|
||||
' remaining';
|
||||
$('choose').disabled = false;
|
||||
if (upload) return;
|
||||
const waiting = data.state === 'waiting';
|
||||
if (!waiting) {
|
||||
pending = true;
|
||||
if (['installed', 'failed'].includes(data.state) && choosingNext) return;
|
||||
pending = !['installed', 'failed'].includes(data.state);
|
||||
const states = {
|
||||
ready: ['Made it to your watch', 'Review ' + data.label + ' on your watch.'],
|
||||
confirm: ['One tap closer', 'Approve installation on your watch.'],
|
||||
@@ -206,9 +242,10 @@ async function poll() {
|
||||
const content = states[data.state] || ['Check your watch.', data.detail];
|
||||
result(content[0], content[1], data.state === 'installed');
|
||||
$('result').dataset.state = data.state;
|
||||
if (['installed', 'failed'].includes(data.state)) $('again').hidden = false;
|
||||
if (data.state === 'failed') $('result-icon').textContent = '!';
|
||||
} else if (pending) {
|
||||
pending = false;
|
||||
((pending = false), (choosingNext = false));
|
||||
result('Ready for another?', 'Your watch is ready to receive a new app.', true);
|
||||
$('again').hidden = false;
|
||||
}
|
||||
@@ -220,17 +257,13 @@ async function poll() {
|
||||
$('choose').disabled = true;
|
||||
if (!upload)
|
||||
message(
|
||||
'Check your watch’s Wi-Fi. If receiving has stopped, start again and scan the new code.',
|
||||
'Check Wi-Fi on your watch. If its address has changed, open the new one shown in Pakkit.',
|
||||
);
|
||||
} finally {
|
||||
polling = false;
|
||||
}
|
||||
}
|
||||
if (!token) {
|
||||
$('access-form').hidden = false;
|
||||
$('choose').disabled = true;
|
||||
$('connection').textContent = 'Let’s connect';
|
||||
}
|
||||
panel('pairing');
|
||||
poll();
|
||||
setInterval(() => {
|
||||
if (!document.hidden) poll();
|
||||
|
||||
@@ -145,18 +145,12 @@
|
||||
</div>
|
||||
<h2 id="card-title">Good things<br />come in Pakkits.</h2>
|
||||
<p class="card-description">Choose an app for your watch. We’ll deliver it.</p>
|
||||
<form id="access-form" hidden>
|
||||
<label for="access">Connect your watch</label>
|
||||
<p>Scan the code on your watch, or paste its full link here.</p>
|
||||
<input
|
||||
id="access"
|
||||
type="password"
|
||||
aria-label="Watch link"
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
required
|
||||
/><button class="primary" type="submit">Connect to watch</button>
|
||||
</form>
|
||||
<div id="pairing" role="status" aria-live="polite">
|
||||
<div class="pairing-symbol" aria-hidden="true">↗</div>
|
||||
<h3 id="pairing-title">A quick hello</h3>
|
||||
<p id="pairing-detail">Tap Allow browser on your watch.</p>
|
||||
<button id="retry-connection" class="secondary" type="button" hidden>Try again</button>
|
||||
</div>
|
||||
<ol class="steps" aria-label="Transfer steps">
|
||||
<li aria-current="step">Choose</li>
|
||||
<li>Send</li>
|
||||
@@ -173,7 +167,7 @@
|
||||
type="file"
|
||||
accept=".apk,application/vnd.android.package-archive"
|
||||
hidden
|
||||
/><small>APK files · up to 50 MB</small>
|
||||
/><small>APK files · sent directly to your watch</small>
|
||||
</div>
|
||||
<div id="selection" hidden>
|
||||
<div class="file-row">
|
||||
@@ -214,12 +208,11 @@
|
||||
><details class="connection-help">
|
||||
<summary>About this connection</summary>
|
||||
<p>
|
||||
Use Wi-Fi you trust. Files travel across your network without encryption. Keep your
|
||||
watch’s link private.
|
||||
Use Wi-Fi you trust. Files travel across your network without encryption. Approve only
|
||||
browsers you recognize.
|
||||
</p>
|
||||
</details>
|
||||
<span id="expiry"></span
|
||||
></span>
|
||||
</span>
|
||||
</footer>
|
||||
</div>
|
||||
</body>
|
||||
|
||||
@@ -532,20 +532,6 @@ h3 {
|
||||
margin: 12px 0;
|
||||
}
|
||||
|
||||
#access-form {
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
#access-form label {
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
#access-form p {
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
input:not([type='file']) {
|
||||
width: 100%;
|
||||
background: var(--bg);
|
||||
@@ -667,10 +653,6 @@ input:not([type='file']) {
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
#expiry {
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.dropzone > span,
|
||||
small {
|
||||
font-size: 12px;
|
||||
@@ -886,3 +868,25 @@ small {
|
||||
font-size: 11px;
|
||||
}
|
||||
}
|
||||
|
||||
#pairing {
|
||||
text-align: center;
|
||||
padding: 24px 4px;
|
||||
min-height: 230px;
|
||||
}
|
||||
#pairing-detail {
|
||||
color: var(--muted);
|
||||
font-size: 14px;
|
||||
line-height: 1.7;
|
||||
}
|
||||
.pairing-symbol {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 56px;
|
||||
height: 56px;
|
||||
margin: 0 auto 20px;
|
||||
border-radius: 18px;
|
||||
color: var(--violet);
|
||||
background: #9e82ff12;
|
||||
font-size: 28px;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package meghdad.pakkit
|
||||
|
||||
import android.app.Application
|
||||
import meghdad.pakkit.data.PackageStore
|
||||
|
||||
class PakkitApplication : Application() {
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
PackageStore(this).clean()
|
||||
}
|
||||
}
|
||||
@@ -5,21 +5,15 @@ import java.io.OutputStream
|
||||
import java.security.MessageDigest
|
||||
|
||||
object ApkRules {
|
||||
const val MAX_BYTES = 50L * 1024 * 1024
|
||||
const val TTL_MS = 24L * 60 * 60 * 1000
|
||||
|
||||
fun validId(id: String) =
|
||||
Regex("[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}").matches(id)
|
||||
|
||||
fun fresh(created: Long, now: Long) = created <= now + 60_000 && now - created < TTL_MS
|
||||
|
||||
fun compatibleAbis(packageAbis: Set<String>, deviceAbis: Set<String>) =
|
||||
packageAbis.isEmpty() || packageAbis.any { it in deviceAbis }
|
||||
|
||||
fun copyBounded(
|
||||
fun copyAndHash(
|
||||
input: InputStream,
|
||||
output: OutputStream? = null,
|
||||
max: Long = MAX_BYTES,
|
||||
): Pair<Long, String> {
|
||||
val hash = MessageDigest.getInstance("SHA-256")
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
@@ -29,7 +23,6 @@ object ApkRules {
|
||||
if (count < 0) break
|
||||
if (count == 0) continue
|
||||
total += count
|
||||
requireUser(total <= max) { "Choose an APK up to 50 MB." }
|
||||
hash.update(buffer, 0, count)
|
||||
output?.write(buffer, 0, count)
|
||||
}
|
||||
|
||||
@@ -9,28 +9,14 @@ import java.util.zip.ZipFile
|
||||
object PackageInspector {
|
||||
@Suppress("DEPRECATION")
|
||||
fun inspect(context: Context, file: File, hash: String): Apk {
|
||||
requireUser(file.length() in 1..ApkRules.MAX_BYTES) { "Choose an APK up to 50 MB." }
|
||||
requireUser(file.length() > 0) { "This file is empty. Choose another APK." }
|
||||
val abis = mutableSetOf<String>()
|
||||
ZipFile(file).use { zip ->
|
||||
requireUser(zip.getEntry("AndroidManifest.xml") != null) {
|
||||
"This file is not an Android APK."
|
||||
}
|
||||
requireUser(zip.size() < 100_000) {
|
||||
"This file is too complex to open. Try another APK."
|
||||
}
|
||||
var expanded = 0L
|
||||
// Inspect directory metadata only; never inflate the package into memory.
|
||||
zip.entries().asSequence().forEach { entry ->
|
||||
requireUser(entry.size >= 0 && entry.size <= 128L * 1024 * 1024) {
|
||||
"This app is too large to unpack. Try a smaller APK."
|
||||
}
|
||||
expanded += entry.size
|
||||
requireUser(expanded <= 200L * 1024 * 1024) {
|
||||
"This app is too large to unpack. Try a smaller APK."
|
||||
}
|
||||
if (entry.name == "AndroidManifest.xml")
|
||||
requireUser(entry.size <= 2 * 1024 * 1024) {
|
||||
"This file can’t be opened. Try another APK."
|
||||
}
|
||||
val parts = entry.name.split('/')
|
||||
if (parts.size >= 3 && parts[0] == "lib" && entry.name.endsWith(".so"))
|
||||
abis += parts[1]
|
||||
@@ -91,18 +77,17 @@ object PackageInspector {
|
||||
)
|
||||
}
|
||||
|
||||
fun checkForWatch(apk: Apk, sdk: Int, abis: Set<String>, free: Long) {
|
||||
fun checkForWatch(apk: Apk, sdk: Int, abis: Set<String>) {
|
||||
requireUser(apk.minSdk <= sdk) {
|
||||
"This app needs a newer version of Android. Check your watch for updates."
|
||||
}
|
||||
requireUser(ApkRules.compatibleAbis(apk.abis, abis)) {
|
||||
"This version doesn’t work on your watch. Try a version made for it."
|
||||
}
|
||||
requireSpace(apk.bytes, free)
|
||||
}
|
||||
|
||||
fun requireSpace(bytes: Long, free: Long) {
|
||||
requireUser(free > bytes * 3 + 20 * 1024 * 1024) {
|
||||
requireUser(bytes > 0 && bytes <= free) {
|
||||
"Free more storage on your watch, then try again."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,4 +8,11 @@ inline fun requireUser(value: Boolean, message: () -> String) {
|
||||
}
|
||||
|
||||
fun Throwable.userMessage(fallback: String): String =
|
||||
if (this is UserMessage) message ?: fallback else fallback
|
||||
when {
|
||||
this is UserMessage -> message ?: fallback
|
||||
generateSequence(this) { it.cause }
|
||||
.any {
|
||||
it is android.system.ErrnoException && it.errno == android.system.OsConstants.ENOSPC
|
||||
} -> "Free some space on your watch, then try again."
|
||||
else -> fallback
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import java.io.File
|
||||
import meghdad.pakkit.apk.ApkRules
|
||||
import meghdad.pakkit.apk.InstallState
|
||||
import meghdad.pakkit.apk.PendingApk
|
||||
import meghdad.pakkit.apk.UserMessage
|
||||
import org.json.JSONObject
|
||||
|
||||
/** One private package and its review, stored atomically under a stable on-disk schema. */
|
||||
@@ -38,7 +39,7 @@ class PackageStore(context: Context) {
|
||||
state = state,
|
||||
detail = detail,
|
||||
sessionId = sessionId ?: current.sessionId,
|
||||
),
|
||||
)
|
||||
)
|
||||
true
|
||||
}
|
||||
@@ -50,19 +51,27 @@ class PackageStore(context: Context) {
|
||||
check(preferences.edit().remove(PENDING_KEY).commit())
|
||||
}
|
||||
|
||||
/** Expiry prevents installation; disk cleanup is intentionally lazy, on the next app launch. */
|
||||
fun clean(now: Long = System.currentTimeMillis()) =
|
||||
/** Called at process startup, before any transfer can own an uncommitted file. */
|
||||
fun clean() =
|
||||
synchronized(lock) {
|
||||
pending()?.takeUnless { ApkRules.fresh(it.created, now) }?.let { dismiss(it.id) }
|
||||
val keep = pending()?.id
|
||||
directory.listFiles()?.forEach { file ->
|
||||
if (file.name != "$keep.apk" && now - file.lastModified() >= ApkRules.TTL_MS)
|
||||
file.delete()
|
||||
if (file.name != "$keep.apk") file.delete()
|
||||
}
|
||||
}
|
||||
|
||||
private fun persist(apk: PendingApk) {
|
||||
check(preferences.edit().putString(PENDING_KEY, apk.json().toString()).commit())
|
||||
val previous = preferences.getString(PENDING_KEY, null)
|
||||
if (!preferences.edit().putString(PENDING_KEY, apk.json().toString()).commit()) {
|
||||
// SharedPreferences updates memory before its disk write; restore both views on
|
||||
// failure.
|
||||
if (!preferences.edit().putString(PENDING_KEY, previous).commit()) {
|
||||
android.util.Log.w("PakkitStore", "Could not persist review rollback")
|
||||
}
|
||||
throw UserMessage(
|
||||
"Couldn’t save this app. Free some space on your watch and try again."
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
|
||||
@@ -31,21 +31,19 @@ class ApkInstaller(private val context: Context) {
|
||||
requireUser(context.packageManager.canRequestPackageInstalls()) {
|
||||
"Allow Pakkit to install apps, then try again."
|
||||
}
|
||||
requireUser(ApkRules.fresh(apk.created, System.currentTimeMillis())) {
|
||||
"This file has expired. Send it again to install."
|
||||
}
|
||||
val file = store.file(apk.id)
|
||||
val digest = file.inputStream().use { ApkRules.copyBounded(it).second }
|
||||
val digest = file.inputStream().use { ApkRules.copyAndHash(it).second }
|
||||
requireUser(digest == apk.apk.sha256) {
|
||||
"This file has changed. Send a fresh copy to install."
|
||||
}
|
||||
val inspected = PackageInspector.inspect(context, file, digest)
|
||||
// Receipt already inspected these bytes; the digest proves they are unchanged.
|
||||
val inspected = apk.apk
|
||||
PackageInspector.checkForWatch(
|
||||
inspected,
|
||||
Build.VERSION.SDK_INT,
|
||||
Build.SUPPORTED_ABIS.toSet(),
|
||||
PackageInspector.free(context),
|
||||
)
|
||||
PackageInspector.requireSpace(file.length(), PackageInspector.free(context))
|
||||
apk.sessionId?.let { runCatching { installer.abandonSession(it) } }
|
||||
val params =
|
||||
PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL)
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
package meghdad.pakkit.transfer
|
||||
|
||||
import java.security.SecureRandom
|
||||
import java.util.Base64
|
||||
import java.util.UUID
|
||||
|
||||
/**
|
||||
* Session-only browser access. Credentials stay in the exact browser origin, never in the product
|
||||
* UI.
|
||||
*/
|
||||
class BrowserAccess(private val changed: (Request?) -> Unit = {}) {
|
||||
data class Request(val id: String, val label: String, val address: String)
|
||||
|
||||
enum class State {
|
||||
APPROVED,
|
||||
PENDING,
|
||||
DENIED,
|
||||
BUSY,
|
||||
UNKNOWN,
|
||||
}
|
||||
|
||||
data class Connection(val state: State, val credential: String? = null)
|
||||
|
||||
// Unapproved peers share one pending slot. Further records require a watch decision,
|
||||
// so network traffic alone cannot grow this map. Approvals do not have a time/device quota.
|
||||
private val decisions = mutableMapOf<String, State>()
|
||||
private var pending: Pair<String, Request>? = null
|
||||
|
||||
@Synchronized
|
||||
fun state(credential: String?): State =
|
||||
if (credential == null) State.UNKNOWN else decisions[credential] ?: State.UNKNOWN
|
||||
|
||||
@Synchronized
|
||||
fun connect(credential: String?, label: String, address: String): Connection {
|
||||
val current = state(credential)
|
||||
if (current != State.UNKNOWN) return Connection(current)
|
||||
if (pending != null) return Connection(State.BUSY)
|
||||
val secret =
|
||||
Base64.getUrlEncoder()
|
||||
.withoutPadding()
|
||||
.encodeToString(ByteArray(32).also { SecureRandom().nextBytes(it) })
|
||||
val request = Request(UUID.randomUUID().toString(), label, address)
|
||||
decisions[secret] = State.PENDING
|
||||
pending = secret to request
|
||||
changed(request)
|
||||
return Connection(State.PENDING, secret)
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun answer(id: String, allow: Boolean): Boolean {
|
||||
val (credential, request) = pending?.takeIf { it.second.id == id } ?: return false
|
||||
decisions[credential] = if (allow) State.APPROVED else State.DENIED
|
||||
pending = null
|
||||
changed(null)
|
||||
return true
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun retry(credential: String?) {
|
||||
if (credential != null && state(credential) == State.DENIED) decisions.remove(credential)
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun close() {
|
||||
decisions.clear()
|
||||
pending = null
|
||||
changed(null)
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun credential(header: String?): String? =
|
||||
header
|
||||
?.takeIf { it.startsWith("Bearer ") }
|
||||
?.removePrefix("Bearer ")
|
||||
?.takeIf { it.matches(Regex("[A-Za-z0-9_-]{43}")) }
|
||||
|
||||
fun label(agent: String): String {
|
||||
val browser =
|
||||
when {
|
||||
"Edg" in agent -> "Edge"
|
||||
"Firefox" in agent -> "Firefox"
|
||||
"Chrome" in agent || "CriOS" in agent -> "Chrome"
|
||||
"Safari" in agent -> "Safari"
|
||||
else -> "Browser"
|
||||
}
|
||||
val device =
|
||||
when {
|
||||
"Android" in agent -> "Android"
|
||||
"iPhone" in agent || "iPad" in agent -> "iOS"
|
||||
"Windows" in agent -> "Windows"
|
||||
"Macintosh" in agent -> "Mac"
|
||||
"Linux" in agent -> "Linux"
|
||||
else -> null
|
||||
}
|
||||
return if (device == null) browser else "$browser on $device"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,21 @@
|
||||
package meghdad.pakkit.transfer
|
||||
|
||||
import java.io.InputStream
|
||||
import java.security.MessageDigest
|
||||
import meghdad.pakkit.apk.ApkRules
|
||||
import java.net.InetAddress
|
||||
import java.net.URI
|
||||
import meghdad.pakkit.apk.requireUser
|
||||
|
||||
/** Deliberately small HTTP/1.1 subset: one request per socket, no pipelining or chunked uploads. */
|
||||
object HttpProtocol {
|
||||
data class Request(val method: String, val path: String, val headers: Map<String, String>)
|
||||
|
||||
fun read(input: InputStream): Request {
|
||||
fun read(input: InputStream, clock: () -> Long = System::nanoTime): Request {
|
||||
val started = clock()
|
||||
var total = 0
|
||||
fun line(): String {
|
||||
val out = StringBuilder()
|
||||
while (true) {
|
||||
require(clock() - started <= 5_000_000_000L) { "Request headers stalled" }
|
||||
val b = input.read()
|
||||
require(b >= 0 && ++total <= 8192) { "Invalid request headers" }
|
||||
if (b == 13) {
|
||||
@@ -41,18 +44,47 @@ object HttpProtocol {
|
||||
return Request(first[0], first[1], headers)
|
||||
}
|
||||
|
||||
fun authorized(header: String?, token: String): Boolean =
|
||||
MessageDigest.isEqual(
|
||||
(header ?: "").toByteArray(Charsets.UTF_8),
|
||||
"Bearer $token".toByteArray(Charsets.UTF_8),
|
||||
/** Accept only this listener's literal address/port, including equivalent IPv6 spellings. */
|
||||
fun sameAuthority(authority: String?, address: InetAddress, port: Int): Boolean = runCatching {
|
||||
if (authority == null) return false
|
||||
val uri = URI("http://$authority")
|
||||
if (
|
||||
uri.rawUserInfo != null ||
|
||||
!uri.rawPath.isNullOrEmpty() ||
|
||||
uri.rawQuery != null ||
|
||||
uri.rawFragment != null ||
|
||||
uri.port != port
|
||||
)
|
||||
return false
|
||||
val host = uri.host?.removeSurrounding("[", "]") ?: return false
|
||||
val parsed =
|
||||
if (':' in host && host.matches(Regex("[0-9a-fA-F:.]+"))) {
|
||||
InetAddress.getByName(
|
||||
host
|
||||
) // A colon-containing numeric literal cannot trigger DNS.
|
||||
} else {
|
||||
val parts = host.split('.')
|
||||
if (
|
||||
parts.size != 4 ||
|
||||
parts.any {
|
||||
it.isEmpty() ||
|
||||
!it.all(Char::isDigit) ||
|
||||
(it.toIntOrNull() ?: -1) !in 0..255
|
||||
}
|
||||
)
|
||||
return false
|
||||
InetAddress.getByAddress(parts.map { it.toInt().toByte() }.toByteArray())
|
||||
}
|
||||
parsed == address
|
||||
}
|
||||
.getOrDefault(false)
|
||||
|
||||
fun uploadLength(headers: Map<String, String>): Long {
|
||||
require(headers["content-type"] == "application/octet-stream") { "Send a complete APK" }
|
||||
val raw = headers["content-length"] ?: error("Content length required")
|
||||
require(raw.matches(Regex("[0-9]+"))) { "Invalid content length" }
|
||||
val size = raw.toLongOrNull() ?: error("Invalid content length")
|
||||
require(size in 1..ApkRules.MAX_BYTES) { "Choose an APK up to 50 MiB" }
|
||||
requireUser(size > 0) { "This file is empty. Choose another APK." }
|
||||
return size
|
||||
}
|
||||
}
|
||||
@@ -1,19 +1,19 @@
|
||||
package meghdad.pakkit.transfer
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import android.os.SystemClock
|
||||
import android.util.Base64
|
||||
import android.os.PowerManager
|
||||
import java.io.BufferedInputStream
|
||||
import java.io.Closeable
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.io.InputStream
|
||||
import java.net.Inet4Address
|
||||
import java.net.Inet6Address
|
||||
import java.net.InetAddress
|
||||
import java.net.InetSocketAddress
|
||||
import java.net.ServerSocket
|
||||
import java.net.Socket
|
||||
import java.security.SecureRandom
|
||||
import java.util.UUID
|
||||
import java.util.concurrent.ArrayBlockingQueue
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
@@ -22,8 +22,10 @@ import java.util.concurrent.ThreadPoolExecutor
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import meghdad.pakkit.apk.ApkRules
|
||||
import meghdad.pakkit.apk.InstallState
|
||||
import meghdad.pakkit.apk.PackageInspector
|
||||
import meghdad.pakkit.apk.PendingApk
|
||||
import meghdad.pakkit.apk.requireUser
|
||||
import meghdad.pakkit.apk.userMessage
|
||||
import meghdad.pakkit.data.PackageStore
|
||||
import org.json.JSONObject
|
||||
@@ -31,27 +33,32 @@ import org.json.JSONObject
|
||||
/** Bounded HTTP endpoint. Wi-Fi acquisition, notifications and power belong to ReceiveService. */
|
||||
class LocalHttpServer(
|
||||
private val context: Context,
|
||||
address: Inet4Address,
|
||||
private val deadline: Long,
|
||||
private val address: InetAddress,
|
||||
private val owner: Any,
|
||||
private val access: BrowserAccess = BrowserAccess(),
|
||||
) : Closeable {
|
||||
private val store = PackageStore(context)
|
||||
private val listener =
|
||||
ServerSocket().apply {
|
||||
reuseAddress = true
|
||||
bind(InetSocketAddress(address, 0), 4)
|
||||
ServerSocket().also { socket ->
|
||||
try {
|
||||
socket.reuseAddress = true
|
||||
socket.bind(InetSocketAddress(address, PORT), 4)
|
||||
} catch (error: Exception) {
|
||||
runCatching { socket.close() }
|
||||
throw error
|
||||
}
|
||||
}
|
||||
private val workers = ThreadPoolExecutor(2, 2, 0, TimeUnit.SECONDS, ArrayBlockingQueue(4))
|
||||
private val sockets = ConcurrentHashMap.newKeySet<Socket>()
|
||||
private val uploading = AtomicBoolean(false)
|
||||
private val closed = AtomicBoolean(false)
|
||||
private val token =
|
||||
Base64.encodeToString(
|
||||
ByteArray(24).also { SecureRandom().nextBytes(it) },
|
||||
Base64.URL_SAFE or Base64.NO_WRAP or Base64.NO_PADDING,
|
||||
)
|
||||
private val authority = "${address.hostAddress}:${listener.localPort}"
|
||||
val url = "http://$authority/#$token"
|
||||
private val commitLock = Any()
|
||||
private val host =
|
||||
address.hostAddress.orEmpty().substringBefore('%').let {
|
||||
if (address is Inet6Address) "[$it]" else it
|
||||
}
|
||||
private val authority = "$host:${listener.localPort}"
|
||||
val url = "http://$authority/"
|
||||
|
||||
fun start() {
|
||||
Thread(
|
||||
@@ -93,11 +100,11 @@ class LocalHttpServer(
|
||||
val response = Response(socket)
|
||||
try {
|
||||
val input = BufferedInputStream(socket.getInputStream(), 8192)
|
||||
socket.soTimeout = 5_000
|
||||
val request = HttpProtocol.read(input)
|
||||
check(!closed.get() && SystemClock.elapsedRealtime() < deadline) {
|
||||
"Receiving has ended. Open a fresh link from your watch."
|
||||
}
|
||||
if (request.headers["host"] != authority) {
|
||||
socket.soTimeout = 15_000
|
||||
requireUser(!closed.get()) { "Receiving has stopped. Open Pakkit to start again." }
|
||||
if (!HttpProtocol.sameAuthority(request.headers["host"], address, PORT)) {
|
||||
response.error(403, "Open the address shown on your watch.")
|
||||
return
|
||||
}
|
||||
@@ -110,18 +117,37 @@ class LocalHttpServer(
|
||||
)
|
||||
return
|
||||
}
|
||||
if (!HttpProtocol.authorized(request.headers["authorization"], token)) {
|
||||
response.error(403, "Open the private link or scan the QR code on your watch.")
|
||||
if (request.method == "POST" && !validOrigin(request.headers["origin"])) {
|
||||
response.error(403, "Open the address shown on your watch to send an app.")
|
||||
return
|
||||
}
|
||||
val credential = BrowserAccess.credential(request.headers["authorization"])
|
||||
if (request.method == "POST" && request.path in setOf("/api/connect", "/api/retry")) {
|
||||
if (request.path == "/api/retry") access.retry(credential)
|
||||
val connection =
|
||||
access.connect(
|
||||
credential,
|
||||
BrowserAccess.label(request.headers["user-agent"].orEmpty()),
|
||||
socket.inetAddress.hostAddress.orEmpty(),
|
||||
)
|
||||
response.json(
|
||||
200,
|
||||
JSONObject().put("connection", connection.state.name.lowercase()).apply {
|
||||
connection.credential?.let { put("credential", it) }
|
||||
},
|
||||
)
|
||||
return
|
||||
}
|
||||
val browser = access.state(credential)
|
||||
if (browser != BrowserAccess.State.APPROVED) {
|
||||
response.json(403, JSONObject().put("connection", browser.name.lowercase()))
|
||||
return
|
||||
}
|
||||
when {
|
||||
request.method == "GET" && request.path == "/api/status" ->
|
||||
response.json(200, status())
|
||||
request.method == "POST" && request.path == "/api/upload" -> {
|
||||
if (request.headers["origin"] != "http://$authority")
|
||||
response.error(403, "Open the link shown on your watch to send an app.")
|
||||
else upload(request, input, response)
|
||||
}
|
||||
request.method == "POST" && request.path == "/api/upload" ->
|
||||
upload(request, input, response)
|
||||
else -> response.error(404, "Not found")
|
||||
}
|
||||
} catch (error: Exception) {
|
||||
@@ -135,6 +161,10 @@ class LocalHttpServer(
|
||||
}
|
||||
}
|
||||
|
||||
private fun validOrigin(origin: String?): Boolean =
|
||||
origin?.startsWith("http://") == true &&
|
||||
HttpProtocol.sameAuthority(origin.removePrefix("http://"), address, PORT)
|
||||
|
||||
private fun status(): JSONObject {
|
||||
val pending = store.pending()
|
||||
val live = Receiving.state
|
||||
@@ -144,9 +174,12 @@ class LocalHttpServer(
|
||||
.put("label", pending?.apk?.label.orEmpty())
|
||||
.put("received", live.received)
|
||||
.put("total", live.total)
|
||||
.put("expiresIn", ((deadline - SystemClock.elapsedRealtime()) / 1000).coerceAtLeast(0))
|
||||
.put("connection", "approved")
|
||||
}
|
||||
|
||||
// The read-idle socket timeout and close() bound stalled I/O; no total transfer deadline.
|
||||
// Release in finally also covers validation failures, cancellation and running out of space.
|
||||
@SuppressLint("WakelockTimeout")
|
||||
private fun upload(request: HttpProtocol.Request, input: InputStream, response: Response) {
|
||||
val length = HttpProtocol.uploadLength(request.headers)
|
||||
if (!uploading.compareAndSet(false, true)) {
|
||||
@@ -154,46 +187,60 @@ class LocalHttpServer(
|
||||
return
|
||||
}
|
||||
var partial: File? = null
|
||||
val wake =
|
||||
context
|
||||
.getSystemService(PowerManager::class.java)
|
||||
.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "pakkit:upload")
|
||||
try {
|
||||
store
|
||||
.pending()
|
||||
?.takeIf { it.state in setOf(InstallState.INSTALLED, InstallState.FAILED) }
|
||||
?.let { store.dismiss(it.id) }
|
||||
if (store.pending() != null) {
|
||||
response.error(409, "Finish with the app on your watch before sending another.")
|
||||
return
|
||||
}
|
||||
PackageInspector.requireSpace(length, PackageInspector.free(context))
|
||||
val id = UUID.randomUUID().toString()
|
||||
val file = store.file(id)
|
||||
partial = file
|
||||
Receiving.update(owner) {
|
||||
it.copy(detail = "Your app is on its way…", total = length, received = 0)
|
||||
}
|
||||
val body =
|
||||
UploadBody(
|
||||
input,
|
||||
length,
|
||||
progress = { received ->
|
||||
Receiving.update(owner) { it.copy(received = received) }
|
||||
},
|
||||
wake.acquire()
|
||||
try {
|
||||
val id = UUID.randomUUID().toString()
|
||||
val file = store.file(id)
|
||||
partial = file
|
||||
updateLive {
|
||||
it.copy(detail = "Your app is on its way…", total = length, received = 0)
|
||||
}
|
||||
val body =
|
||||
UploadBody(
|
||||
input,
|
||||
length,
|
||||
progress = { received ->
|
||||
updateLive { it.copy(received = received) }
|
||||
},
|
||||
)
|
||||
val digest = file.outputStream().use { ApkRules.copyAndHash(body, it).second }
|
||||
updateLive { it.copy(detail = "Getting your app ready…") }
|
||||
val apk = PackageInspector.inspect(context, file, digest)
|
||||
PackageInspector.checkForWatch(
|
||||
apk,
|
||||
Build.VERSION.SDK_INT,
|
||||
Build.SUPPORTED_ABIS.toSet(),
|
||||
)
|
||||
val digest = file.outputStream().use { ApkRules.copyBounded(body, it).second }
|
||||
Receiving.update(owner) { it.copy(detail = "Getting your app ready…") }
|
||||
val apk = PackageInspector.inspect(context, file, digest)
|
||||
PackageInspector.checkForWatch(
|
||||
apk,
|
||||
Build.VERSION.SDK_INT,
|
||||
Build.SUPPORTED_ABIS.toSet(),
|
||||
PackageInspector.free(context),
|
||||
)
|
||||
check(!closed.get() && SystemClock.elapsedRealtime() < deadline) {
|
||||
"Receiving has ended. Open a fresh link from your watch."
|
||||
synchronized(commitLock) {
|
||||
requireUser(!closed.get()) {
|
||||
"Receiving has stopped. Start again to send this app."
|
||||
}
|
||||
store.stage(PendingApk(id, System.currentTimeMillis(), apk))
|
||||
}
|
||||
partial = null
|
||||
updateLive { it.copy(detail = "Ready to install") }
|
||||
response.json(200, JSONObject().put("label", apk.label).put("state", "ready"))
|
||||
} finally {
|
||||
wake.release()
|
||||
}
|
||||
store.stage(PendingApk(id, System.currentTimeMillis(), apk))
|
||||
partial = null
|
||||
Receiving.update(owner) { it.copy(detail = "Ready to install") }
|
||||
response.json(200, JSONObject().put("label", apk.label).put("state", "ready"))
|
||||
} finally {
|
||||
partial?.delete()
|
||||
uploading.set(false)
|
||||
Receiving.update(owner) {
|
||||
updateLive {
|
||||
it.copy(
|
||||
received = 0,
|
||||
total = 0,
|
||||
@@ -204,8 +251,16 @@ class LocalHttpServer(
|
||||
}
|
||||
}
|
||||
|
||||
private fun updateLive(change: (Receiving.State) -> Receiving.State) {
|
||||
synchronized(commitLock) {
|
||||
if (!closed.get()) Receiving.update(owner, change)
|
||||
}
|
||||
}
|
||||
|
||||
override fun close() {
|
||||
if (!closed.compareAndSet(false, true)) return
|
||||
synchronized(commitLock) {
|
||||
if (!closed.compareAndSet(false, true)) return
|
||||
}
|
||||
try {
|
||||
listener.close()
|
||||
} finally {
|
||||
@@ -252,6 +307,7 @@ class LocalHttpServer(
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val PORT = 8787
|
||||
private val ASSETS =
|
||||
mapOf(
|
||||
"/" to ("index.html" to "text/html; charset=utf-8"),
|
||||
|
||||
@@ -14,48 +14,58 @@ import android.net.NetworkCapabilities
|
||||
import android.net.NetworkRequest
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.PowerManager
|
||||
import android.os.SystemClock
|
||||
import java.net.BindException
|
||||
import java.net.Inet4Address
|
||||
import java.net.InetAddress
|
||||
import meghdad.pakkit.R
|
||||
import meghdad.pakkit.ui.WatchActivity
|
||||
|
||||
/** Owns the user-started session and releases all network/power resources on every exit path. */
|
||||
/** User-controlled receiving; network loss suspends the listener, never the user's intent. */
|
||||
class ReceiveService : Service() {
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
private val connectivity by lazy { getSystemService(ConnectivityManager::class.java) }
|
||||
private var server: LocalHttpServer? = null
|
||||
private var network: Network? = null
|
||||
private var address: Inet4Address? = null
|
||||
private var address: InetAddress? = null
|
||||
private var registered = false
|
||||
private var ended = false
|
||||
private var deadline = 0L
|
||||
private var wake: PowerManager.WakeLock? = null
|
||||
private val access = BrowserAccess { request ->
|
||||
Receiving.update(this) { it.copy(browserRequest = request) }
|
||||
}
|
||||
private val callback =
|
||||
object : ConnectivityManager.NetworkCallback() {
|
||||
override fun onLinkPropertiesChanged(network: Network, properties: LinkProperties) {
|
||||
main.post {
|
||||
if (ended) return@post
|
||||
if (this@ReceiveService.network == null) {
|
||||
if (properties.linkAddresses.isNotEmpty()) open(network, properties)
|
||||
} else if (
|
||||
this@ReceiveService.network == network &&
|
||||
properties.linkAddresses.none { it.address == address }
|
||||
) {
|
||||
finish("Wi-Fi changed. Ready to reconnect?")
|
||||
val candidates =
|
||||
properties.linkAddresses
|
||||
.map { it.address }
|
||||
.filter {
|
||||
!it.isLoopbackAddress &&
|
||||
!it.isAnyLocalAddress &&
|
||||
!it.isMulticastAddress
|
||||
}
|
||||
val ipv4 =
|
||||
candidates.firstOrNull { it is Inet4Address }
|
||||
?: candidates.firstOrNull { !it.isLinkLocalAddress }
|
||||
if (ipv4 == null) {
|
||||
if (network == this@ReceiveService.network) suspendListener()
|
||||
return@post
|
||||
}
|
||||
if (server != null && network == this@ReceiveService.network && ipv4 == address)
|
||||
return@post
|
||||
open(network, ipv4)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onLost(network: Network) {
|
||||
main.post {
|
||||
if (network == this@ReceiveService.network)
|
||||
finish("Wi-Fi disconnected. Ready to reconnect?")
|
||||
if (!ended && network == this@ReceiveService.network) suspendListener()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onUnavailable() {
|
||||
main.post { finish("Connect your watch to Wi-Fi, then try again.") }
|
||||
main.post { if (!ended) suspendListener() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,17 +73,13 @@ class ReceiveService : Service() {
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
if (intent?.action == STOP) {
|
||||
finish("Session ended")
|
||||
finish("Receiving stopped")
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
if (registered || ended) return START_NOT_STICKY
|
||||
val manager = getSystemService(NotificationManager::class.java)
|
||||
manager.createNotificationChannel(
|
||||
NotificationChannel(
|
||||
"receive",
|
||||
"App transfers",
|
||||
NotificationManager.IMPORTANCE_LOW,
|
||||
),
|
||||
NotificationChannel("receive", "App transfers", NotificationManager.IMPORTANCE_LOW)
|
||||
)
|
||||
val open =
|
||||
PendingIntent.getActivity(
|
||||
@@ -92,20 +98,18 @@ class ReceiveService : Service() {
|
||||
val notification =
|
||||
Notification.Builder(this, "receive")
|
||||
.setSmallIcon(R.drawable.pakkit_mark)
|
||||
.setContentTitle("Ready for your next app")
|
||||
.setContentTitle("Receiving is on")
|
||||
.setContentText("Open Pakkit to connect your browser.")
|
||||
.setContentIntent(open)
|
||||
.setOngoing(true)
|
||||
.addAction(Notification.Action.Builder(null, "End session", stop).build())
|
||||
.addAction(Notification.Action.Builder(null, "Stop receiving", stop).build())
|
||||
.build()
|
||||
startForeground(
|
||||
NOTIFICATION,
|
||||
notification,
|
||||
ServiceInfo.FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE,
|
||||
)
|
||||
Receiving.begin(this)
|
||||
deadline = SystemClock.elapsedRealtime() + DURATION_MS
|
||||
main.postDelayed({ finish("Time’s up. Ready for another app?") }, DURATION_MS)
|
||||
Receiving.begin(this, access)
|
||||
try {
|
||||
registered = true
|
||||
connectivity.requestNetwork(
|
||||
@@ -114,35 +118,41 @@ class ReceiveService : Service() {
|
||||
.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
|
||||
.build(),
|
||||
callback,
|
||||
25_000,
|
||||
)
|
||||
} catch (_: Exception) {
|
||||
} catch (error: Exception) {
|
||||
android.util.Log.w("PakkitReceive", "Cannot request Wi-Fi", error)
|
||||
finish("Can’t reach Wi-Fi. Check your watch’s connection.")
|
||||
}
|
||||
// A killed process does not silently reopen network access. The user starts it again.
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
|
||||
private fun open(network: Network, properties: LinkProperties) {
|
||||
private fun open(network: Network, address: InetAddress) {
|
||||
suspendListener()
|
||||
this.network = network
|
||||
this.address = address
|
||||
try {
|
||||
val address =
|
||||
properties.linkAddresses
|
||||
.map { it.address }
|
||||
.filterIsInstance<Inet4Address>()
|
||||
.firstOrNull { it.isSiteLocalAddress }
|
||||
?: error("A private IPv4 Wi-Fi address is required")
|
||||
this.network = network
|
||||
this.address = address
|
||||
val listener = LocalHttpServer(applicationContext, address, deadline, this)
|
||||
val listener = LocalHttpServer(applicationContext, address, this, access)
|
||||
server = listener
|
||||
wake =
|
||||
getSystemService(PowerManager::class.java)
|
||||
.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "pakkit:receive")
|
||||
.apply { acquire((deadline - SystemClock.elapsedRealtime()).coerceAtLeast(1)) }
|
||||
listener.start()
|
||||
Receiving.update(this) { it.copy(url = listener.url, detail = "Ready to receive") }
|
||||
} catch (error: Exception) {
|
||||
android.util.Log.w("PakkitReceive", "Cannot open receiving session", error)
|
||||
finish("Couldn’t connect. Check Wi-Fi and try again.")
|
||||
android.util.Log.w("PakkitReceive", "Cannot open receiver", error)
|
||||
finish(
|
||||
if (error is BindException)
|
||||
"Port ${LocalHttpServer.PORT} is in use. Close the other receiver and try again."
|
||||
else "Couldn’t connect. Check Wi-Fi and try again."
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun suspendListener() {
|
||||
server?.close()
|
||||
server = null
|
||||
network = null
|
||||
address = null
|
||||
Receiving.update(this) {
|
||||
it.copy(url = null, received = 0, total = 0, detail = "Waiting for Wi-Fi…")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -160,19 +170,21 @@ class ReceiveService : Service() {
|
||||
server = null
|
||||
if (registered) runCatching { connectivity.unregisterNetworkCallback(callback) }
|
||||
registered = false
|
||||
wake?.let { if (it.isHeld) it.release() }
|
||||
wake = null
|
||||
access.close()
|
||||
Receiving.end(this, message)
|
||||
}
|
||||
|
||||
override fun onTimeout(startId: Int, fgsType: Int) {
|
||||
finish("Your watch paused receiving. Open Pakkit to start again.")
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
ended = true
|
||||
release("Session ended")
|
||||
release("Receiving stopped")
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val DURATION_MS = 10 * 60 * 1000L
|
||||
const val STOP = "stop"
|
||||
private const val NOTIFICATION = 81
|
||||
}
|
||||
|
||||
@@ -4,14 +4,13 @@ import android.os.Handler
|
||||
import android.os.Looper
|
||||
import java.util.concurrent.CopyOnWriteArraySet
|
||||
|
||||
/**
|
||||
* Live session state is never persisted: process death immediately invalidates its private link.
|
||||
*/
|
||||
/** Live session state is never persisted: process death revokes browser approvals. */
|
||||
object Receiving {
|
||||
data class State(
|
||||
val active: Boolean = false,
|
||||
val url: String? = null,
|
||||
val detail: String = "Connect your watch and browser to the same Wi-Fi.",
|
||||
val browserRequest: BrowserAccess.Request? = null,
|
||||
val received: Long = 0,
|
||||
val total: Long = 0,
|
||||
)
|
||||
@@ -21,6 +20,7 @@ object Receiving {
|
||||
private set
|
||||
|
||||
private var owner: Any? = null
|
||||
private var access: BrowserAccess? = null
|
||||
private val listeners = CopyOnWriteArraySet<() -> Unit>()
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
private val notify = Runnable { listeners.forEach { it() } }
|
||||
@@ -34,7 +34,8 @@ object Receiving {
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun begin(owner: Any) {
|
||||
fun begin(owner: Any, access: BrowserAccess? = null) {
|
||||
this.access = access
|
||||
this.owner = owner
|
||||
publish(State(active = true, detail = "Connecting to Wi-Fi…"))
|
||||
}
|
||||
@@ -48,9 +49,15 @@ object Receiving {
|
||||
fun end(owner: Any, detail: String) {
|
||||
if (this.owner !== owner) return
|
||||
this.owner = null
|
||||
this.access = null
|
||||
publish(State(detail = detail))
|
||||
}
|
||||
|
||||
fun answerBrowser(id: String, allow: Boolean): Boolean {
|
||||
val current = synchronized(this) { access }
|
||||
return current?.answer(id, allow) ?: false
|
||||
}
|
||||
|
||||
private fun publish(state: State) {
|
||||
this.state = state
|
||||
main.removeCallbacks(notify)
|
||||
|
||||
@@ -19,12 +19,13 @@ import android.widget.TextClock
|
||||
import java.util.concurrent.Executors
|
||||
import kotlin.math.roundToInt
|
||||
import meghdad.pakkit.R
|
||||
import meghdad.pakkit.apk.ApkRules
|
||||
import meghdad.pakkit.apk.InstallState
|
||||
import meghdad.pakkit.apk.PendingApk
|
||||
import meghdad.pakkit.apk.userMessage
|
||||
import meghdad.pakkit.data.PackageStore
|
||||
import meghdad.pakkit.install.ApkInstaller
|
||||
import meghdad.pakkit.install.PendingApproval
|
||||
import meghdad.pakkit.transfer.BrowserAccess
|
||||
import meghdad.pakkit.transfer.ReceiveService
|
||||
import meghdad.pakkit.transfer.Receiving
|
||||
|
||||
@@ -38,31 +39,26 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
|
||||
private var busy = false
|
||||
private var error: String? = null
|
||||
private var renderedState = ""
|
||||
private var showingLink = false
|
||||
private var backRegistered = false
|
||||
private val linkBack =
|
||||
if (Build.VERSION.SDK_INT >= 33)
|
||||
android.window.OnBackInvokedCallback {
|
||||
showingLink = false
|
||||
refresh()
|
||||
}
|
||||
else null
|
||||
private var resumed = false
|
||||
private var approvalLaunched: Int? = null
|
||||
private var requestedInstallId: String? = null
|
||||
private var qrUrl = ""
|
||||
private var qrBitmap: android.graphics.Bitmap? = null
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
store = PackageStore(this)
|
||||
store.clean()
|
||||
acceptIntent(intent)
|
||||
showingLink = savedInstanceState?.getBoolean("showingLink") ?: false
|
||||
requestedInstallId = savedInstanceState?.getString("requestedInstallId")
|
||||
approvalLaunched = savedInstanceState?.getInt("approvalLaunched", -1)?.takeIf { it >= 0 }
|
||||
refresh()
|
||||
savedInstanceState?.getInt("scroll")?.let { y -> scroll.post { scroll.scrollTo(0, y) } }
|
||||
}
|
||||
|
||||
override fun onSaveInstanceState(outState: Bundle) {
|
||||
outState.putInt("scroll", scroll.scrollY)
|
||||
outState.putBoolean("showingLink", showingLink)
|
||||
outState.putString("requestedInstallId", requestedInstallId)
|
||||
approvalLaunched?.let { outState.putInt("approvalLaunched", it) }
|
||||
super.onSaveInstanceState(outState)
|
||||
}
|
||||
|
||||
@@ -89,21 +85,25 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
resumed = true
|
||||
store.preferences.registerOnSharedPreferenceChangeListener(this)
|
||||
Receiving.observe(sessionObserver)
|
||||
refresh()
|
||||
val requested = requestedInstallId
|
||||
requestedInstallId = null
|
||||
if (requested != null && packageManager.canRequestPackageInstalls()) {
|
||||
store.pending()?.takeIf { it.id == requested }?.let { install(it) }
|
||||
}
|
||||
}
|
||||
|
||||
override fun onPause() {
|
||||
resumed = false
|
||||
Receiving.removeObserver(sessionObserver)
|
||||
store.preferences.unregisterOnSharedPreferenceChangeListener(this)
|
||||
super.onPause()
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
if (Build.VERSION.SDK_INT >= 33 && backRegistered) {
|
||||
onBackInvokedDispatcher.unregisterOnBackInvokedCallback(requireNotNull(linkBack))
|
||||
}
|
||||
io.shutdown()
|
||||
super.onDestroy()
|
||||
}
|
||||
@@ -198,29 +198,17 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
|
||||
if (isDestroyed || isFinishing) return
|
||||
val job = store.pending()
|
||||
val live = Receiving.state
|
||||
if (live.url == null || job != null || live.total > 0) showingLink = false
|
||||
val stateKey =
|
||||
job?.let { "${it.id}:${it.state}" }
|
||||
live.browserRequest?.let { "browser:${it.id}" }
|
||||
?: job?.let { "${it.id}:${it.state}" }
|
||||
?: when {
|
||||
showingLink && live.url != null -> "link"
|
||||
live.total > 0 -> "uploading"
|
||||
live.url != null -> "receiving"
|
||||
live.active -> "connecting"
|
||||
else -> "home"
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= 33) {
|
||||
val handleBack = showingLink && job == null && live.url != null && live.total == 0L
|
||||
if (handleBack && !backRegistered) {
|
||||
onBackInvokedDispatcher.registerOnBackInvokedCallback(
|
||||
android.window.OnBackInvokedDispatcher.PRIORITY_DEFAULT,
|
||||
requireNotNull(linkBack),
|
||||
)
|
||||
} else if (!handleBack && backRegistered) {
|
||||
onBackInvokedDispatcher.unregisterOnBackInvokedCallback(requireNotNull(linkBack))
|
||||
}
|
||||
backRegistered = handleBack
|
||||
}
|
||||
val previousState = renderedState
|
||||
if (stateKey != previousState) error = null
|
||||
val y = if (::scroll.isInitialized && stateKey == renderedState) scroll.scrollY else 0
|
||||
renderedState = stateKey
|
||||
scroll = RoundScrollView(this).apply { setBackgroundColor(colors.canvas) }
|
||||
@@ -247,16 +235,20 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
|
||||
importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
|
||||
}
|
||||
)
|
||||
if (job == null) home()
|
||||
error?.let { add(line(it, 13f, colors.error), 12) }
|
||||
if (live.browserRequest != null) browserRequest(live.browserRequest)
|
||||
else if (job == null) home()
|
||||
else {
|
||||
incoming(job)
|
||||
if (Receiving.state.url != null)
|
||||
if (live.active) {
|
||||
button(getString(R.string.watch_end_session), false) {
|
||||
stopService(Intent(this, ReceiveService::class.java))
|
||||
refresh()
|
||||
}
|
||||
} else {
|
||||
button(getString(R.string.watch_start_receiving), false) { startReceiving() }
|
||||
}
|
||||
}
|
||||
error?.let { add(line(it, 13f, colors.error), 12) }
|
||||
|
||||
scroll.isFocusable = true
|
||||
scroll.isFocusableInTouchMode = true
|
||||
setContentView(scroll)
|
||||
@@ -269,17 +261,31 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
|
||||
column.alpha = 0f
|
||||
column.animate().alpha(1f).setDuration(180).start()
|
||||
}
|
||||
scroll.post { scroll.scrollTo(0, y) }
|
||||
scroll.post {
|
||||
scroll.scrollTo(0, y)
|
||||
val approval = PendingApproval.intent
|
||||
if (
|
||||
resumed &&
|
||||
job?.state == InstallState.CONFIRM &&
|
||||
job.sessionId != null &&
|
||||
PendingApproval.id == job.id &&
|
||||
approval != null &&
|
||||
approvalLaunched != job.sessionId
|
||||
) {
|
||||
approvalLaunched = job.sessionId
|
||||
runCatching { startActivity(approval) }
|
||||
.onFailure {
|
||||
error = getString(R.string.watch_approval_error)
|
||||
refresh()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun home() {
|
||||
val live = Receiving.state
|
||||
val url = live.url
|
||||
if (url != null) {
|
||||
if (showingLink && live.total == 0L) {
|
||||
showLink(url)
|
||||
return
|
||||
}
|
||||
if (live.total > 0) {
|
||||
parcel(48)
|
||||
val percent = (live.received * 100 / live.total).coerceAtMost(100)
|
||||
@@ -356,11 +362,13 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
|
||||
)
|
||||
add(line(getString(R.string.watch_scan_to_send), 20f, bold = true), 12)
|
||||
add(line(getString(R.string.watch_scan_description), 13f, colors.secondary), 8)
|
||||
add(line(getString(R.string.watch_ready_for_10_minutes), 12f, colors.mint), 10)
|
||||
button(getString(R.string.watch_view_link), false) {
|
||||
showingLink = true
|
||||
refresh()
|
||||
}
|
||||
add(
|
||||
line(url, 12f, colors.mint).apply {
|
||||
textDirection = View.TEXT_DIRECTION_LTR
|
||||
setTextIsSelectable(true)
|
||||
},
|
||||
10,
|
||||
)
|
||||
}
|
||||
button(getString(R.string.watch_end_session), false) {
|
||||
stopService(Intent(this, ReceiveService::class.java))
|
||||
@@ -387,60 +395,49 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
|
||||
)
|
||||
if (live.active) {
|
||||
badge(getString(R.string.watch_finding_wi_fi))
|
||||
add(line(getString(R.string.watch_connecting_description), 13f, colors.secondary), 12)
|
||||
button(getString(R.string.watch_cancel), false) {
|
||||
add(line(live.detail, 13f, colors.secondary), 12)
|
||||
button(getString(R.string.watch_end_session), false) {
|
||||
stopService(Intent(this, ReceiveService::class.java))
|
||||
}
|
||||
} else {
|
||||
button(getString(R.string.watch_start_receiving)) {
|
||||
error = null
|
||||
runCatching { startForegroundService(Intent(this, ReceiveService::class.java)) }
|
||||
.onFailure {
|
||||
error = getString(R.string.watch_connection_error)
|
||||
refresh()
|
||||
}
|
||||
}
|
||||
button(getString(R.string.watch_start_receiving)) { startReceiving() }
|
||||
add(line(getString(R.string.brand_tagline), 12f, colors.accent), 14)
|
||||
if (live.detail != Receiving.State().detail)
|
||||
if (live.detail != Receiving.State().detail && live.detail != "Receiving stopped")
|
||||
add(line(live.detail, 13f, colors.secondary), 12)
|
||||
button(getString(R.string.watch_wi_fi), false) {
|
||||
runCatching {
|
||||
startActivity(Intent(android.provider.Settings.ACTION_WIFI_SETTINGS))
|
||||
}
|
||||
.onFailure {
|
||||
error = getString(R.string.watch_wifi_unavailable)
|
||||
refresh()
|
||||
}
|
||||
}
|
||||
button(getString(R.string.watch_wi_fi), false) {
|
||||
runCatching {
|
||||
startActivity(Intent(android.provider.Settings.ACTION_WIFI_SETTINGS))
|
||||
}
|
||||
.onFailure {
|
||||
error = getString(R.string.watch_wifi_unavailable)
|
||||
refresh()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun showLink(url: String) {
|
||||
add(line(getString(R.string.watch_your_watch_link), 20f, bold = true), 14)
|
||||
add(line(getString(R.string.watch_link_description), 13f, colors.secondary), 12)
|
||||
add(
|
||||
line(url, 12f, colors.mint).apply {
|
||||
textDirection = View.TEXT_DIRECTION_LTR
|
||||
setTextIsSelectable(true)
|
||||
},
|
||||
14,
|
||||
)
|
||||
add(line(getString(R.string.watch_connection_privacy), 12f, colors.secondary), 14)
|
||||
button(getString(R.string.watch_back_to_code), false) {
|
||||
showingLink = false
|
||||
refresh()
|
||||
}
|
||||
private fun startReceiving() {
|
||||
error = null
|
||||
runCatching { startForegroundService(Intent(this, ReceiveService::class.java)) }
|
||||
.onFailure {
|
||||
error = getString(R.string.watch_connection_error)
|
||||
refresh()
|
||||
}
|
||||
}
|
||||
|
||||
// Android 12 uses this callback; Android 13+ registers the platform callback above.
|
||||
@Suppress("DEPRECATION")
|
||||
@android.annotation.SuppressLint("GestureBackNavigation")
|
||||
@Deprecated("Legacy callback for Android 12")
|
||||
override fun onBackPressed() {
|
||||
if (showingLink) {
|
||||
showingLink = false
|
||||
refresh()
|
||||
} else super.onBackPressed()
|
||||
private fun browserRequest(request: BrowserAccess.Request) {
|
||||
add(line(getString(R.string.watch_connect_browser), 21f, bold = true), 8)
|
||||
add(line(request.label, 15f, colors.secondary), 10)
|
||||
add(line(request.address, 12f, colors.secondary), 5)
|
||||
button(getString(R.string.watch_allow_browser)) {
|
||||
Receiving.answerBrowser(request.id, true)
|
||||
}
|
||||
button(getString(R.string.watch_not_now), false) {
|
||||
Receiving.answerBrowser(request.id, false)
|
||||
}
|
||||
button(getString(R.string.watch_end_session), false) {
|
||||
stopService(Intent(this, ReceiveService::class.java))
|
||||
}
|
||||
}
|
||||
|
||||
private fun incoming(job: PendingApk) {
|
||||
@@ -481,25 +478,7 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
|
||||
when (state) {
|
||||
InstallState.READY,
|
||||
InstallState.FAILED -> {
|
||||
if (!ApkRules.fresh(job.created, System.currentTimeMillis())) {
|
||||
add(
|
||||
line(
|
||||
getString(R.string.watch_file_expired),
|
||||
13f,
|
||||
colors.error,
|
||||
),
|
||||
12,
|
||||
)
|
||||
} else if (store.file(job.id).exists()) {
|
||||
if (!apk.wear)
|
||||
add(
|
||||
line(
|
||||
getString(R.string.watch_fit_notice),
|
||||
12f,
|
||||
colors.error,
|
||||
),
|
||||
10,
|
||||
)
|
||||
if (store.file(job.id).exists()) {
|
||||
if (packageManager.canRequestPackageInstalls())
|
||||
button(
|
||||
if (state == InstallState.FAILED) getString(R.string.watch_try_again)
|
||||
@@ -516,11 +495,13 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
|
||||
),
|
||||
10,
|
||||
)
|
||||
button(getString(R.string.watch_allow_installs)) { settings() }
|
||||
button(getString(R.string.watch_allow_installs)) {
|
||||
requestedInstallId = job.id
|
||||
settings()
|
||||
}
|
||||
button(getString(R.string.watch_google_play), false) { play() }
|
||||
}
|
||||
}
|
||||
add(line(getString(R.string.watch_trust_notice), 12f, colors.secondary), 10)
|
||||
button(getString(R.string.watch_remove_file), false) { dismiss(job) }
|
||||
}
|
||||
InstallState.CONFIRM -> {
|
||||
@@ -589,6 +570,7 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
|
||||
private fun settings() {
|
||||
runCatching { startActivity(ApkInstaller.settings(this)) }
|
||||
.onFailure {
|
||||
requestedInstallId = null
|
||||
error = getString(R.string.watch_permission_unavailable)
|
||||
refresh()
|
||||
}
|
||||
@@ -604,8 +586,11 @@ class WatchActivity : Activity(), SharedPreferences.OnSharedPreferenceChangeList
|
||||
error = null
|
||||
refresh()
|
||||
io.execute {
|
||||
ApkInstaller(applicationContext).install(job)
|
||||
val result = runCatching { ApkInstaller(applicationContext).install(job) }
|
||||
runOnUiThread {
|
||||
result.exceptionOrNull()?.let {
|
||||
error = it.userMessage(getString(R.string.watch_save_error))
|
||||
}
|
||||
busy = false
|
||||
refresh()
|
||||
}
|
||||
|
||||
@@ -1,32 +1,21 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="watch_end_session">End session</string>
|
||||
<string name="watch_end_session">Stop receiving</string>
|
||||
<string name="watch_just_checking">Just checking…</string>
|
||||
<string name="watch_on_its_way">On its way</string>
|
||||
<string name="watch_getting_your_app_ready">Getting your app ready.</string>
|
||||
<string name="watch_keep_your_browser_open">Keep your browser open.</string>
|
||||
<string name="watch_scan_to_send">Scan to send</string>
|
||||
<string name="watch_scan_to_send">Scan to connect</string>
|
||||
<string name="watch_scan_description">Both devices on the same Wi-Fi.</string>
|
||||
<string name="watch_ready_for_10_minutes">Ready for 10 minutes</string>
|
||||
<string name="watch_view_link">View link</string>
|
||||
<string name="watch_finding_wi_fi">Finding Wi-Fi</string>
|
||||
<string name="watch_connecting_description">Getting ready for your next app.</string>
|
||||
<string name="watch_cancel">Cancel</string>
|
||||
<string name="watch_start_receiving">Start receiving</string>
|
||||
<string name="watch_connection_error">Couldn’t connect. Check Wi-Fi and try again.</string>
|
||||
<string name="watch_wi_fi">Wi-Fi</string>
|
||||
<string name="watch_wifi_unavailable">Open Wi-Fi in your watch’s Settings.</string>
|
||||
<string name="watch_your_watch_link">Your watch link</string>
|
||||
<string name="watch_link_description">Open this link on a device using the same Wi-Fi.</string>
|
||||
<string name="watch_connection_privacy">Use Wi-Fi you trust. Transfers aren’t encrypted. Keep this link private.</string>
|
||||
<string name="watch_back_to_code">Back to code</string>
|
||||
<string name="watch_all_yours">All yours.</string>
|
||||
<string name="watch_couldn_t_install">Couldn’t install</string>
|
||||
<string name="watch_getting_ready">Getting ready…</string>
|
||||
<string name="watch_ready_to_install">Ready to install</string>
|
||||
<string name="watch_file_expired">This file has expired. Send it again to install.</string>
|
||||
<string name="watch_fit_notice">Made for a phone? It may not fit your watch.</string>
|
||||
<string name="watch_trust_notice">Only install apps you trust.</string>
|
||||
<string name="watch_try_again">Try again</string>
|
||||
<string name="watch_install">Install</string>
|
||||
<string name="watch_permission_description">Allow Pakkit to install apps. You’ll approve each one.</string>
|
||||
@@ -43,7 +32,11 @@
|
||||
<string name="watch_permission_unavailable">Your watch doesn’t offer this setting. Find apps on Google Play instead.</string>
|
||||
<string name="watch_launch_unavailable">This app can’t be opened here. Check your watch’s app list.</string>
|
||||
<string name="watch_play_unavailable">Find Google Play in your watch’s app list.</string>
|
||||
<string name="scan_code_description">QR code to connect your browser. Use View link for the full address.</string>
|
||||
<string name="scan_code_description">QR code to connect your browser. The address is below.</string>
|
||||
<string name="watch_percent_received">%1$d%% received</string>
|
||||
<string name="watch_app_summary">%1$s · %2$s MB</string>
|
||||
<string name="watch_connect_browser">Connect browser?</string>
|
||||
<string name="watch_allow_browser">Allow browser</string>
|
||||
<string name="watch_not_now">Not now</string>
|
||||
<string name="watch_save_error">Couldn’t save this app. Free some space and try again.</string>
|
||||
</resources>
|
||||
@@ -9,7 +9,7 @@ class ApkRulesTest {
|
||||
@Test
|
||||
fun copyComputesKnownDigest() {
|
||||
val output = ByteArrayOutputStream()
|
||||
val result = ApkRules.copyBounded(ByteArrayInputStream("abc".toByteArray()), output)
|
||||
val result = ApkRules.copyAndHash(ByteArrayInputStream("abc".toByteArray()), output)
|
||||
assertEquals(3L, result.first)
|
||||
assertEquals(
|
||||
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
|
||||
@@ -18,14 +18,29 @@ class ApkRulesTest {
|
||||
assertEquals("abc", output.toString("UTF-8"))
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException::class)
|
||||
fun stopsBeforeWritingOverLimit() {
|
||||
ApkRules.copyBounded(ByteArrayInputStream(ByteArray(1025)), ByteArrayOutputStream(), 1024)
|
||||
@Test
|
||||
fun streamsBeyondThePreviousFileLimitWithABoundedBuffer() {
|
||||
val length = 64L * 1024 * 1024
|
||||
var remaining = length
|
||||
val input =
|
||||
object : java.io.InputStream() {
|
||||
override fun read(): Int = error("Bulk reads only")
|
||||
|
||||
override fun read(bytes: ByteArray, offset: Int, count: Int): Int {
|
||||
assertTrue("Copy buffer stays bounded", bytes.size <= 64 * 1024)
|
||||
if (remaining == 0L) return -1
|
||||
val size = minOf(count.toLong(), remaining).toInt()
|
||||
bytes.fill(0, offset, offset + size)
|
||||
remaining -= size
|
||||
return size
|
||||
}
|
||||
}
|
||||
assertEquals(length, ApkRules.copyAndHash(input).first)
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException::class)
|
||||
fun refusesEmptyFiles() {
|
||||
ApkRules.copyBounded(ByteArrayInputStream(byteArrayOf()), ByteArrayOutputStream())
|
||||
ApkRules.copyAndHash(ByteArrayInputStream(byteArrayOf()), ByteArrayOutputStream())
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -35,14 +50,6 @@ class ApkRulesTest {
|
||||
assertTrue(ApkRules.validId("05b414ab-a230-42f8-9a6d-1be25dcc3224"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun expirationAndClockSkewAreBounded() {
|
||||
val now = 1_000_000_000L
|
||||
assertTrue(ApkRules.fresh(now - 1000, now))
|
||||
assertFalse(ApkRules.fresh(now - ApkRules.TTL_MS, now))
|
||||
assertFalse(ApkRules.fresh(now + 120000, now))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun nativeLibrariesNeedMatchingProcessor() {
|
||||
assertTrue(ApkRules.compatibleAbis(emptySet(), setOf("arm64-v8a")))
|
||||
|
||||
@@ -7,25 +7,25 @@ class CompatibilityTest {
|
||||
private val apk = Apk("Test", "test.app", "1", 31, 1024, "digest", setOf("arm64-v8a"), true)
|
||||
|
||||
@Test
|
||||
fun acceptsCompatibleSdkAbiAndStorage() {
|
||||
PackageInspector.checkForWatch(apk, 36, setOf("arm64-v8a"), 100L * 1024 * 1024)
|
||||
fun acceptsCompatibleSdkAndProcessor() {
|
||||
PackageInspector.checkForWatch(apk, 36, setOf("arm64-v8a"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun rejectsIncompatibleSdkProcessorAndInsufficientStorage() {
|
||||
fun rejectsActualPlatformIncompatibility() {
|
||||
assertTrue(
|
||||
runCatching {
|
||||
PackageInspector.checkForWatch(apk, 30, setOf("arm64-v8a"), Long.MAX_VALUE)
|
||||
}
|
||||
.isFailure,
|
||||
runCatching { PackageInspector.checkForWatch(apk, 30, setOf("arm64-v8a")) }.isFailure
|
||||
)
|
||||
assertTrue(
|
||||
runCatching { PackageInspector.checkForWatch(apk, 36, setOf("x86_64"), Long.MAX_VALUE) }
|
||||
.isFailure,
|
||||
)
|
||||
assertTrue(
|
||||
runCatching { PackageInspector.checkForWatch(apk, 36, setOf("arm64-v8a"), 1024) }
|
||||
.isFailure,
|
||||
runCatching { PackageInspector.checkForWatch(apk, 36, setOf("x86_64")) }.isFailure
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun storageUsesAvailableBytesWithoutAMultiplierOrOverflow() {
|
||||
PackageInspector.requireSpace(100, 100)
|
||||
PackageInspector.requireSpace(Long.MAX_VALUE, Long.MAX_VALUE)
|
||||
assertTrue(runCatching { PackageInspector.requireSpace(101, 100) }.isFailure)
|
||||
assertTrue(runCatching { PackageInspector.requireSpace(Long.MAX_VALUE, 1024) }.isFailure)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package meghdad.pakkit.transfer
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class BrowserAccessTest {
|
||||
@Test
|
||||
fun approvingAnotherBrowserDoesNotEvictEarlierApprovals() {
|
||||
var request: BrowserAccess.Request? = null
|
||||
val access = BrowserAccess { request = it }
|
||||
val first = access.connect(null, "Browser", "ip").credential
|
||||
access.answer(requireNotNull(request).id, true)
|
||||
repeat(64) {
|
||||
access.connect(null, "Browser", "ip")
|
||||
access.answer(requireNotNull(request).id, true)
|
||||
}
|
||||
assertEquals(BrowserAccess.State.APPROVED, access.state(first))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun onlyTheWatchCanApproveAndDecisionsAreSessionScoped() {
|
||||
var pending: BrowserAccess.Request? = null
|
||||
val access = BrowserAccess { pending = it }
|
||||
val connection = access.connect(null, "Chrome", "192.168.1.2")
|
||||
val credential = requireNotNull(connection.credential)
|
||||
assertEquals(BrowserAccess.State.PENDING, access.state(credential))
|
||||
assertFalse(access.answer("forged", true))
|
||||
assertTrue(access.answer(requireNotNull(pending).id, true))
|
||||
repeat(100) { assertEquals(BrowserAccess.State.APPROVED, access.state(credential)) }
|
||||
assertNull(access.connect(credential, "Chrome", "192.168.1.2").credential)
|
||||
access.close()
|
||||
assertEquals(BrowserAccess.State.UNKNOWN, access.state(credential))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun unknownPeersCannotReplacePendingRequestsOrAutoRetryDenial() {
|
||||
var pending: BrowserAccess.Request? = null
|
||||
val access = BrowserAccess { pending = it }
|
||||
val first = access.connect(null, "Chrome", "ip")
|
||||
val id = requireNotNull(pending).id
|
||||
repeat(1000) {
|
||||
assertEquals(BrowserAccess.State.BUSY, access.connect(null, "Unknown", "ip").state)
|
||||
}
|
||||
assertEquals(id, pending?.id)
|
||||
access.answer(id, false)
|
||||
assertEquals(
|
||||
BrowserAccess.State.DENIED,
|
||||
access.connect(first.credential, "Chrome", "ip").state,
|
||||
)
|
||||
access.retry(first.credential)
|
||||
assertEquals(
|
||||
BrowserAccess.State.PENDING,
|
||||
access.connect(first.credential, "Chrome", "ip").state,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun credentialsArePrivateOpaqueValuesWithExactHeaderFraming() {
|
||||
val credential = requireNotNull(BrowserAccess().connect(null, "Browser", "ip").credential)
|
||||
assertEquals(credential, BrowserAccess.credential("Bearer $credential"))
|
||||
assertNull(BrowserAccess.credential("Bearer $credential extra"))
|
||||
assertNull(BrowserAccess.credential("bearer $credential"))
|
||||
assertNull(BrowserAccess.credential("Bearer guessed"))
|
||||
assertEquals("Chrome on Android", BrowserAccess.label("Mozilla Android Chrome Safari"))
|
||||
}
|
||||
}
|
||||
@@ -6,11 +6,30 @@ import org.junit.Test
|
||||
class HttpProtocolTest {
|
||||
private fun request(value: String) = HttpProtocol.read(value.byteInputStream())
|
||||
|
||||
@Test
|
||||
fun authorityChecksNumericAddressesWithoutAssumingPrivateIpv4() {
|
||||
val v6 = java.net.InetAddress.getByName("fd00::1")
|
||||
assertTrue(HttpProtocol.sameAuthority("[fd00:0:0:0:0:0:0:1]:8787", v6, 8787))
|
||||
assertTrue(HttpProtocol.sameAuthority("[fd00::1]:8787", v6, 8787))
|
||||
val v4 = java.net.InetAddress.getByName("100.64.1.2")
|
||||
assertTrue(HttpProtocol.sameAuthority("100.64.1.2:8787", v4, 8787))
|
||||
for (host in
|
||||
listOf(
|
||||
"evil.example:8787",
|
||||
"100.64.1.2:9999",
|
||||
"evil@100.64.1.2:8787",
|
||||
"100.64.1.2:8787/path",
|
||||
"100.64.1.2:8787?q=x",
|
||||
)) {
|
||||
assertFalse(host, HttpProtocol.sameAuthority(host, v4, 8787))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun acceptsBoundedRawUpload() {
|
||||
val r =
|
||||
request(
|
||||
"POST /api/upload HTTP/1.1\r\nHost: 192.168.1.4:8080\r\nContent-Length: 42\r\nContent-Type: application/octet-stream\r\n\r\n",
|
||||
"POST /api/upload HTTP/1.1\r\nHost: 192.168.1.4:8080\r\nContent-Length: 42\r\nContent-Type: application/octet-stream\r\n\r\n"
|
||||
)
|
||||
assertEquals(42L, HttpProtocol.uploadLength(r.headers))
|
||||
assertEquals("/api/upload", r.path)
|
||||
@@ -27,41 +46,57 @@ class HttpProtocolTest {
|
||||
"Long: " + "a".repeat(9000),
|
||||
)) {
|
||||
assertTrue(
|
||||
runCatching { request("POST /api/upload HTTP/1.1\r\n$headers\r\n\r\n") }.isFailure,
|
||||
runCatching { request("POST /api/upload HTTP/1.1\r\n$headers\r\n\r\n") }.isFailure
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun rejectsInvalidLengthsAndTypes() {
|
||||
for (length in listOf("-1", "+1", "1,1", "0", "52428801", "wat", "9223372036854775808")) {
|
||||
for (length in listOf("-1", "+1", "1,1", "0", "wat", "9223372036854775808")) {
|
||||
assertTrue(
|
||||
runCatching {
|
||||
HttpProtocol.uploadLength(
|
||||
mapOf(
|
||||
"content-type" to "application/octet-stream",
|
||||
"content-length" to length,
|
||||
),
|
||||
)
|
||||
)
|
||||
}
|
||||
.isFailure,
|
||||
.isFailure
|
||||
)
|
||||
}
|
||||
assertTrue(
|
||||
runCatching {
|
||||
HttpProtocol.uploadLength(
|
||||
mapOf("content-type" to "text/plain", "content-length" to "42"),
|
||||
mapOf("content-type" to "text/plain", "content-length" to "42")
|
||||
)
|
||||
}
|
||||
.isFailure,
|
||||
.isFailure
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun requiresExactBearerToken() {
|
||||
assertTrue(HttpProtocol.authorized("Bearer secret", "secret"))
|
||||
assertFalse(HttpProtocol.authorized(null, "secret"))
|
||||
assertFalse(HttpProtocol.authorized("Bearer secretX", "secret"))
|
||||
assertFalse(HttpProtocol.authorized("bearer secret", "secret"))
|
||||
fun slowHeadersCannotHoldAWorkerIndefinitely() {
|
||||
var time = 0L
|
||||
val result = runCatching {
|
||||
HttpProtocol.read("GET / HTTP/1.1\r\n\r\n".byteInputStream()) {
|
||||
time += 1_000_000_000
|
||||
time
|
||||
}
|
||||
}
|
||||
assertTrue(result.isFailure)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun acceptsLargeContentLengthsWithoutIntegerTruncation() {
|
||||
for (size in listOf(52_428_801L, 4L * 1024 * 1024 * 1024, Long.MAX_VALUE)) {
|
||||
assertEquals(
|
||||
size,
|
||||
HttpProtocol.uploadLength(
|
||||
mapOf("content-type" to "application/octet-stream", "content-length" to "$size")
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user