Add offline QR sharing for the watch public key
This commit is contained in:
15 files changed
+281
-13
No files matched your search
@@ -35,6 +35,7 @@ android {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(libs.zxing.core)
|
||||
implementation(libs.androidx.annotation.experimental)
|
||||
implementation(libs.wear.tiles)
|
||||
implementation(libs.wear.protolayout)
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
package meghdad.remember
|
||||
|
||||
import android.content.Intent
|
||||
import android.graphics.Bitmap
|
||||
import android.os.SystemClock
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.widget.Button
|
||||
import android.widget.EditText
|
||||
import androidx.test.espresso.Espresso.onView
|
||||
import androidx.test.espresso.Espresso.pressBack
|
||||
import androidx.test.espresso.action.ViewActions.click
|
||||
import androidx.test.espresso.action.ViewActions.scrollTo
|
||||
import androidx.test.espresso.matcher.ViewMatchers.withText
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import com.google.zxing.BinaryBitmap
|
||||
import com.google.zxing.RGBLuminanceSource
|
||||
import com.google.zxing.common.HybridBinarizer
|
||||
import com.google.zxing.qrcode.QRCodeReader
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import java.io.File
|
||||
|
||||
/** Uses only a disposable watch identity; no network connection or recording is needed. */
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class PublicKeyQrScreenTest {
|
||||
@Test fun serverShowsScannablePublicKeyAndBackPreservesTheWatchIdentity() {
|
||||
val instrumentation = InstrumentationRegistry.getInstrumentation()
|
||||
val context = instrumentation.targetContext
|
||||
val settings = BackupSettings(context)
|
||||
val key = settings.generateKey()
|
||||
val encryptedIdentity = settings.preferences.getString("key", null)
|
||||
val activity = instrumentation.startActivitySync(Intent(context, BackupActivity::class.java)
|
||||
.putExtra(BackupActivity.EXTRA_PAGE, "server").addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
fun descendants(view: View): List<View> = listOf(view) + if (view is ViewGroup)
|
||||
(0 until view.childCount).flatMap { descendants(view.getChildAt(it)) } else emptyList()
|
||||
fun awaitView(match: (View) -> Boolean): View {
|
||||
var found: View? = null
|
||||
val end = SystemClock.elapsedRealtime() + 6000
|
||||
while (found == null && SystemClock.elapsedRealtime() < end) {
|
||||
instrumentation.runOnMainSync { found = descendants(activity.window.decorView).firstOrNull(match) }
|
||||
if (found == null) SystemClock.sleep(50)
|
||||
}
|
||||
return found ?: error("Public-key page did not open")
|
||||
}
|
||||
try {
|
||||
instrumentation.runOnMainSync {
|
||||
descendants(activity.window.decorView).filterIsInstance<EditText>().first().setText("backup.example")
|
||||
}
|
||||
onView(withText("Show watch key")).perform(scrollTo(), click())
|
||||
awaitView { it is Button && it.text == "Show QR code" }
|
||||
onView(withText("Show QR code")).perform(scrollTo(), click())
|
||||
val qr = awaitView { it is PublicKeyQrView }
|
||||
instrumentation.waitForIdleSync()
|
||||
SystemClock.sleep(3300) // Let the touch-revealed menu hide before the scan/screenshot.
|
||||
val snapshot = instrumentation.uiAutomation.takeScreenshot()!!
|
||||
try {
|
||||
val pixels = IntArray(snapshot.width * snapshot.height)
|
||||
snapshot.getPixels(pixels, 0, snapshot.width, 0, 0, snapshot.width, snapshot.height)
|
||||
assertEquals(key.trim(), QRCodeReader().decode(BinaryBitmap(HybridBinarizer(
|
||||
RGBLuminanceSource(snapshot.width, snapshot.height, pixels)))).text)
|
||||
File(context.getExternalFilesDir(null), "public-key-qr.png").outputStream().use { snapshot.compress(Bitmap.CompressFormat.PNG, 100, it) }
|
||||
instrumentation.runOnMainSync {
|
||||
val point = IntArray(2); qr.getLocationOnScreen(point)
|
||||
val radius = snapshot.width / 2.0
|
||||
for (x in listOf(point[0], point[0] + qr.width)) for (y in listOf(point[1], point[1] + qr.height)) {
|
||||
assertTrue("QR quiet border must fit the round screen", kotlin.math.hypot(x - radius, y - snapshot.height / 2.0) < radius)
|
||||
}
|
||||
assertTrue(qr.keepScreenOn)
|
||||
assertFalse(qr.contentDescription.isNullOrBlank())
|
||||
}
|
||||
} finally { snapshot.recycle() }
|
||||
pressBack()
|
||||
awaitView { it is Button && it.text == "Copy on watch" }
|
||||
pressBack()
|
||||
awaitView { it is Button && it.text == "Show watch key" }
|
||||
instrumentation.runOnMainSync {
|
||||
assertEquals("backup.example", descendants(activity.window.decorView).filterIsInstance<EditText>().first().text.toString())
|
||||
}
|
||||
assertEquals(key, settings.publicKey())
|
||||
assertEquals(encryptedIdentity, settings.preferences.getString("key", null))
|
||||
assertNull(RecordingService.activeId)
|
||||
} finally { instrumentation.runOnMainSync { activity.finish() } }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
--------------------------------------------------------------------------------
|
||||
NOTICES FOR BARCODE4J
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
Barcode4J
|
||||
Copyright 2002-2010 Jeremias Märki
|
||||
Copyright 2005-2006 Dietmar Bürkle
|
||||
|
||||
Portions of this software were contributed under section 5 of the
|
||||
Apache License. Contributors are listed under:
|
||||
http://barcode4j.sourceforge.net/contributors.html
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
NOTICES FOR JCOMMANDER
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
Copyright 2010 Cedric Beust cedric@beust.com
|
||||
@@ -44,6 +44,8 @@ class BackupActivity : Activity() {
|
||||
private var remoteClips: List<RemoteClip> = emptyList()
|
||||
private var serverDraft: BackupServer? = null
|
||||
private var pendingTrust: BackupServer? = null
|
||||
private var displayedPublicKey: String? = null
|
||||
private var publicKeyQr: com.google.zxing.common.BitMatrix? = null
|
||||
private var summary: TextView? = null
|
||||
private var progress: TextView? = null
|
||||
private var playbackButton: Button? = null
|
||||
@@ -146,6 +148,8 @@ class BackupActivity : Activity() {
|
||||
}
|
||||
when (page) {
|
||||
"server" -> serverPage()
|
||||
"public_key" -> publicKeyPage()
|
||||
"public_key_qr" -> publicKeyQrPage()
|
||||
"trust" -> trustPage()
|
||||
"trust_fingerprint" -> {
|
||||
title(getString(R.string.backup_server_identity))
|
||||
@@ -157,7 +161,7 @@ class BackupActivity : Activity() {
|
||||
"playback" -> playbackPage()
|
||||
"automatic" -> automaticPage()
|
||||
"advanced" -> advancedPage()
|
||||
"licenses" -> { title(getString(R.string.backup_open_source_licenses)); text(listOf("JSch.txt", "Bouncy-Castle.txt").joinToString("\n\n") { name -> assets.open("licenses/$name").bufferedReader().use { it.readText() } }, 10f, muted); button(getString(R.string.backup_back)) { navigate("advanced") } }
|
||||
"licenses" -> { title(getString(R.string.backup_open_source_licenses)); text(listOf("JSch.txt", "Bouncy-Castle.txt", "Apache-2.0.txt", "ZXing-NOTICE.txt").joinToString("\n\n") { name -> assets.open("licenses/$name").bufferedReader().use { it.readText() } }, 10f, muted); button(getString(R.string.backup_back)) { navigate("advanced") } }
|
||||
else -> overview()
|
||||
}
|
||||
scroll.requestFocus()
|
||||
@@ -249,6 +253,7 @@ class BackupActivity : Activity() {
|
||||
text("02 / WATCH IDENTITY", 9f, lime)
|
||||
button(if (settings.publicKey() == null) "Create watch key" else "Show watch key") {
|
||||
runTask("Preparing key…", { settings.generateKey() }) { key ->
|
||||
serverDraft = draft()
|
||||
showPublicKey(key)
|
||||
}
|
||||
}
|
||||
@@ -295,15 +300,43 @@ class BackupActivity : Activity() {
|
||||
button(getString(R.string.backup_view_fingerprint)) { navigate("trust_fingerprint") }
|
||||
}
|
||||
private fun showPublicKey(key: String) {
|
||||
AlertDialog.Builder(this).setTitle("Watch public key").setMessage("Add this public key to the backup account's authorized_keys:\n\n$key")
|
||||
.setPositiveButton("Export") { _, _ ->
|
||||
runCatching {
|
||||
startActivityForResult(Intent(Intent.ACTION_CREATE_DOCUMENT).addCategory(Intent.CATEGORY_OPENABLE)
|
||||
.setType("text/plain").putExtra(Intent.EXTRA_TITLE, "remember-watch.pub"), 20)
|
||||
}.onFailure { toast("No file picker available. Copy the public key instead.") }
|
||||
}.setNeutralButton("Copy") { _, _ ->
|
||||
getSystemService(ClipboardManager::class.java).setPrimaryClip(ClipData.newPlainText("Watch public key", key)); toast(getString(R.string.backup_public_key_copied))
|
||||
}.setNegativeButton("Close", null).show()
|
||||
displayedPublicKey = key.trim()
|
||||
publicKeyQr = null
|
||||
navigate("public_key")
|
||||
}
|
||||
private fun publicKeyPage() {
|
||||
val key = displayedPublicKey ?: settings.publicKey()?.trim()
|
||||
if (key == null) { page = "server"; serverPage(); return }
|
||||
displayedPublicKey = key
|
||||
title(getString(R.string.backup_watch_public_key))
|
||||
primary(getString(R.string.backup_show_qr)) {
|
||||
runTask(getString(R.string.backup_show_qr), { runCatching { PublicKeyQr.encode(key) } }) { result ->
|
||||
if (page == "public_key" && displayedPublicKey == key) result.onSuccess { code ->
|
||||
publicKeyQr = code; navigate("public_key_qr")
|
||||
}.onFailure { toast(getString(R.string.backup_public_key_qr_failed)) }
|
||||
}
|
||||
}
|
||||
text(getString(R.string.backup_public_key_instructions), 11f, muted)
|
||||
button(getString(R.string.backup_copy_on_watch)) {
|
||||
getSystemService(ClipboardManager::class.java).setPrimaryClip(ClipData.newPlainText(getString(R.string.backup_watch_public_key), key))
|
||||
toast(getString(R.string.backup_public_key_copied))
|
||||
}
|
||||
button(getString(R.string.backup_export_public_key)) {
|
||||
runCatching {
|
||||
startActivityForResult(Intent(Intent.ACTION_CREATE_DOCUMENT).addCategory(Intent.CATEGORY_OPENABLE)
|
||||
.setType("text/plain").putExtra(Intent.EXTRA_TITLE, "remember-watch.pub"), 20)
|
||||
}.onFailure { toast(getString(R.string.backup_could_not_export_key)) }
|
||||
}
|
||||
text(key, 10f, muted).setTextIsSelectable(true)
|
||||
button(getString(R.string.backup_back)) { back() }
|
||||
}
|
||||
private fun publicKeyQrPage() {
|
||||
val code = publicKeyQr ?: run { page = "public_key"; publicKeyPage(); return }
|
||||
text(getString(R.string.backup_scan_with_phone), 10f, lime)
|
||||
val side = dp((resources.configuration.screenWidthDp * .62f).toInt())
|
||||
body.addView(PublicKeyQrView(this, code), LinearLayout.LayoutParams(side, side))
|
||||
text(getString(R.string.backup_qr_instructions), 10f, muted)
|
||||
button(getString(R.string.backup_back)) { back() }
|
||||
}
|
||||
@Deprecated("Framework document picker result")
|
||||
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
|
||||
@@ -516,6 +549,8 @@ class BackupActivity : Activity() {
|
||||
}
|
||||
"trust" -> cancelTrust()
|
||||
"trust_fingerprint" -> navigate("trust")
|
||||
"public_key_qr" -> navigate("public_key")
|
||||
"public_key" -> navigate("server")
|
||||
else -> navigate(when (page) { "playback" -> "remote"; "licenses" -> "advanced"; else -> "overview" })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package meghdad.remember
|
||||
|
||||
import com.google.zxing.BarcodeFormat
|
||||
import com.google.zxing.EncodeHintType
|
||||
import com.google.zxing.common.BitMatrix
|
||||
import com.google.zxing.qrcode.QRCodeWriter
|
||||
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel
|
||||
|
||||
/** Plain OpenSSH public-key text, encoded locally with a four-module quiet border. */
|
||||
internal object PublicKeyQr {
|
||||
fun encode(publicKey: String): BitMatrix {
|
||||
val line = publicKey.trim()
|
||||
require(line.length <= 2048 && !line.contains('\n') && !line.contains('\r') &&
|
||||
(line.startsWith("ssh-ed25519 ") || line.startsWith("ssh-rsa "))) { "Expected a watch public key" }
|
||||
return QRCodeWriter().encode(line, BarcodeFormat.QR_CODE, 0, 0, mapOf(
|
||||
EncodeHintType.CHARACTER_SET to "UTF-8",
|
||||
EncodeHintType.ERROR_CORRECTION to ErrorCorrectionLevel.M,
|
||||
EncodeHintType.MARGIN to 4,
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package meghdad.remember
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Color
|
||||
import android.graphics.Paint
|
||||
import android.view.View
|
||||
import com.google.zxing.common.BitMatrix
|
||||
import kotlin.math.min
|
||||
|
||||
/** Integer-sized, unfiltered modules keep the code sharp on a small watch display. */
|
||||
internal class PublicKeyQrView(context: Context, private val code: BitMatrix) : View(context) {
|
||||
private val ink = Paint().apply { color = Color.BLACK; isAntiAlias = false }
|
||||
init {
|
||||
contentDescription = context.getString(R.string.backup_public_key_qr_description)
|
||||
setBackgroundColor(Color.WHITE)
|
||||
keepScreenOn = true
|
||||
}
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
super.onDraw(canvas)
|
||||
val scale = min(width / code.width, height / code.height)
|
||||
if (scale < 1) return
|
||||
val left = (width - code.width * scale) / 2
|
||||
val top = (height - code.height * scale) / 2
|
||||
for (y in 0 until code.height) for (x in 0 until code.width) if (code[x, y]) {
|
||||
canvas.drawRect((left + x * scale).toFloat(), (top + y * scale).toFloat(),
|
||||
(left + (x + 1) * scale).toFloat(), (top + (y + 1) * scale).toFloat(), ink)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,13 @@
|
||||
<resources>
|
||||
<string name="backup_watch_public_key">Watch public key</string>
|
||||
<string name="backup_public_key_instructions">Add this public key to your server’s authorized_keys.</string>
|
||||
<string name="backup_show_qr">Show QR code</string>
|
||||
<string name="backup_scan_with_phone">Scan with your phone</string>
|
||||
<string name="backup_qr_instructions">Use your phone’s camera or QR scanner, then copy the text. Works offline.</string>
|
||||
<string name="backup_public_key_qr_description">QR code containing the watch public key</string>
|
||||
<string name="backup_copy_on_watch">Copy on watch</string>
|
||||
<string name="backup_export_public_key">Export public key</string>
|
||||
<string name="backup_public_key_qr_failed">Could not create the QR code. You can still copy or export the public key.</string>
|
||||
<string name="recorder_start">Start recording</string>
|
||||
<string name="recorder_recording_part">● RECORDING · %1$d</string>
|
||||
<string name="recorder_moment_marked">Moment marked</string>
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package meghdad.remember
|
||||
|
||||
import com.google.zxing.BinaryBitmap
|
||||
import com.google.zxing.RGBLuminanceSource
|
||||
import com.google.zxing.common.HybridBinarizer
|
||||
import com.google.zxing.qrcode.QRCodeReader
|
||||
import com.jcraft.jsch.KeyPair
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
import java.io.ByteArrayOutputStream
|
||||
|
||||
class PublicKeyQrTest {
|
||||
@Test fun phoneScannableCodesPreserveEd25519AndLegacyRsaPublicKeysAtWatchSizes() {
|
||||
for (type in listOf(KeyPair.ED25519, KeyPair.RSA)) {
|
||||
val pair = KeyPair.genKeyPair(SshCrypto.client(), type, 2048)
|
||||
val key = try { ByteArrayOutputStream().also { pair.writePublicKey(it, "remember-watch") }.toString("UTF-8").trim() }
|
||||
finally { pair.dispose() }
|
||||
val code = PublicKeyQr.encode("$key\n")
|
||||
for (side in listOf(238, 280)) {
|
||||
val scale = side / code.width
|
||||
assertTrue("Watch code must retain at least two pixels per module", scale >= 2)
|
||||
val offset = (side - code.width * scale) / 2
|
||||
val pixels = IntArray(side * side) { -1 }
|
||||
for (y in 0 until code.height) for (x in 0 until code.width) if (code[x, y]) {
|
||||
for (dy in 0 until scale) for (dx in 0 until scale) pixels[(offset + y * scale + dy) * side + offset + x * scale + dx] = 0xff000000.toInt()
|
||||
}
|
||||
val decoded = QRCodeReader().decode(BinaryBitmap(HybridBinarizer(RGBLuminanceSource(side, side, pixels))))
|
||||
assertEquals(key, decoded.text)
|
||||
}
|
||||
for (i in 0 until code.width) for (margin in 0..3) {
|
||||
assertFalse(code[i, margin]); assertFalse(code[margin, i])
|
||||
assertFalse(code[i, code.height - 1 - margin]); assertFalse(code[code.width - 1 - margin, i])
|
||||
}
|
||||
}
|
||||
}
|
||||
@Test fun privateKeyAndMultilinePayloadsAreRejected() {
|
||||
for (payload in listOf("-----BEGIN OPENSSH PRIVATE KEY-----", "ssh-ed25519 aaa\nsecret", "ssh-rsa aaa\rsecret", "ssh-rsa " + "a".repeat(2048))) {
|
||||
assertThrows(IllegalArgumentException::class.java) { PublicKeyQr.encode(payload) }
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user