Add offline QR sharing for the watch public key

This commit is contained in:
Meghdad committed 2026-10-16 09:17:16 +03:30
1 parent 8a86b4186f
commit 27cf823959
15 files changed
+281 -13

No files matched your search

+1 -1
View File
@@ -5,7 +5,7 @@ Remember records audio only after the user starts capture and grants microphone
- Recordings and bookmark metadata are stored in the app's private local storage.
- The app has internet/network-state permission for optional SFTP backups and remote playback. It connects to the server you configure when you request a connection, upload, or remote recording, or enable scheduled backup. Automatic backup is off by default. There are no app accounts, analytics, advertising, or third-party upload services.
- Backups send audio, titles, timestamps, duration, bookmarks, file size, and checksums to your server. SSH encrypts the connection; these files remain readable on that server. Local deletion does not remove server copies.
- The watch generates its own SSH key. The private key is encrypted with an Android Keystore key; only the public key can be exported. Server configuration and transfer status remain in app-private preferences. The app fetches a server fingerprint without sending watch credentials, then asks for explicit first-time approval. Approved fingerprints are saved and checked before authentication; changed keys are blocked. Forgetting trust is an explicit action that pauses backups.
- The watch generates its own SSH key. The private key is encrypted with an Android Keystore key; only the public key can be exported. The optional QR page encodes that public key locally for scanning with a phone; it uses no online QR service and contains no private key, server credentials, or recordings. Server configuration and transfer status remain in app-private preferences. The app fetches a server fingerprint without sending watch credentials, then asks for explicit first-time approval. Approved fingerprints are saved and checked before authentication; changed keys are blocked. Forgetting trust is an explicit action that pauses backups.
- Remote playback downloads audio into the app's private temporary cache. You can clear it under Backup → Advanced; Android may also evict cached files.
- Scheduled backups use Android JobScheduler with your selected charging/network constraints. Boot permission allows scheduled jobs to persist after restarting the watch. Jobs may retry failed transfers within your configured retry limit.
- Storage monitoring reads device capacity and Remember's own usage; it does not request access to another app's data.
+1 -1
View File
@@ -154,7 +154,7 @@ Open **Menu → Backup** for the dashboard. **Server**, **Transfers**, **Server
<img src="docs/advanced.png" width="240" alt="Inline selected chips for retry attempts and connection timeout" />
</p>
- **Server:** configure address, port, username, and an existing absolute backup folder. **Connect & trust** fetches the fingerprint without typing; approve the server once to remember it. Create the watch key, export or copy its public key, and authorize it on your server. Test connection before uploading. See [server setup](docs/backup.md).
- **Server:** configure address, port, username, and an existing absolute backup folder. **Connect & trust** fetches the fingerprint without typing; approve the server once to remember it. Create the watch key, open **Show watch key → Show QR code** to scan the public key with your phone, or copy/export it on the watch, then authorize it on your server. The QR works offline and contains only the public key. Test connection before uploading. See [server setup](docs/backup.md).
- **Transfers:** shows saved recordings and their status. **Back up / Retry** queues unfinished or changed recordings. **Pause all** cancels transfers and turns automatic backup off. Local recordings are never deleted by backup; local deletion does not delete server copies.
- **Server recordings:** Refresh lists completed Remember backups (up to 1,000 per folder). Select a recording to download a verified temporary copy and play it with seeking and bookmark buttons. This is cached playback, not live streaming; sufficient watch storage is required. Leaving the activity pauses playback.
- **Automatic backup:** opt in to checks every hour, every six hours, or daily. Charging and unmetered connections are required by default and can be changed. Unmetered does not necessarily mean Wi-Fi. Android schedules work when conditions allow, rather than at an exact clock time; jobs persist across reboot.
+4
View File
@@ -16,6 +16,10 @@ The app includes [mwiede/JSch 2.28.8](https://github.com/mwiede/jsch/tree/jsch-2
[Bouncy Castle bcprov-jdk18on 1.86](https://www.bouncycastle.org/) provides Android-compatible Ed25519 key generation and signatures through JSch's BC backend. It is distributed under the Bouncy Castle license (MIT-style), retained in [licenses/Bouncy-Castle.txt](licenses/Bouncy-Castle.txt) and bundled in the app's license assets. Android's installed security providers are not replaced.
## ZXing QR encoding
[ZXing Core 3.5.4](https://github.com/zxing/zxing/tree/zxing-3.5.4) generates public-key QR codes locally. It is distributed under Apache License 2.0, retained in [licenses/Apache-2.0.txt](licenses/Apache-2.0.txt) and bundled in the app. The upstream [NOTICE](licenses/ZXing-NOTICE.txt) is retained in the repository and app license assets. Only the core library is included; no camera/scanner UI or online QR service is used.
## AndroidX Tiles and concurrency
The recording tile uses AndroidX Wear Tiles 1.6.2, ProtoLayout/ProtoLayout Expression 1.4.2, Concurrent Futures 1.3.0, and Annotation Experimental 1.6.0 (API opt-in markers for native tile transitions), distributed under the Apache License, Version 2.0. The transitive Guava `listenablefuture` API is also Apache-2.0 licensed. A copy of the license is retained in [licenses/Apache-2.0.txt](licenses/Apache-2.0.txt) and bundled in the app's license assets. These libraries and their notices retain their upstream licenses; they are not relicensed under MIT. The tile renderer dependency is used only in device tests.
+1
View File
@@ -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)
}
}
}
+9
View File
@@ -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) }
}
}
}
+5 -1
View File
@@ -13,7 +13,7 @@ Remember needs an existing SSH server with SFTP enabled. No database or custom a
```
Compare the `SHA256:...` value with the watch's read-only display if desired. Subsequent fingerprint mismatches block authentication and transfers. For a legitimate server-key change, verify it first, then use **Menu → Advanced → Server identity → Forget trust** and approve the new identity. Forgetting trust pauses backups and turns automatic backup off.
4. In Remember, open **Menu → Server**, then **Create watch key**. Export or copy the public key and add its single line to the dedicated account's `~/.ssh/authorized_keys`. Keep normal OpenSSH ownership and permissions: the account owns `.ssh` and its files, `.ssh` is mode 700, and `authorized_keys` is mode 600.
4. In Remember, open **Menu → Server**, then **Create watch key**. Choose **Show QR code** on the public-key page, scan it with your phone’s camera or QR scanner, and copy the text (scanner support varies). This works offline without a phone companion app. **Copy on watch** and **Export public key** remain available. Add the public key’s single line to the dedicated account's `~/.ssh/authorized_keys`. Keep normal OpenSSH ownership and permissions: the account owns `.ssh` and its files, `.ssh` is mode 700, and `authorized_keys` is mode 600.
5. Restrict the account to SFTP and its intended storage area using your server's supported configuration. For OpenSSH, a dedicated-user `Match` block can disable shell use and forwarding:
```text
@@ -32,6 +32,10 @@ Enter the address without `ssh://`, SSH port, account name, and an **existing ab
Choose **Back up now** to queue saved recordings. Automatic backup remains off until enabled on its dedicated page. Retry attempts and socket timeouts are adjustable under Advanced. Pausing all backups also disables automatic backup.
<img src="public-key-qr.png" width="240" alt="Offline public-key QR code on a round Wear OS emulator using a disposable watch identity" />
This screenshot contains a disposable test key. Scan the QR shown on your own watch when configuring your server.
Password login and private-key import are not currently supported. The private watch key is encrypted locally using Android Keystore and cannot be exported through the UI. After uninstalling or changing watches, authorize a newly generated public key on the server.
## Files and integrity
Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

+2
View File
@@ -9,8 +9,10 @@ wearTiles = "1.6.2"
protoLayout = "1.4.2"
concurrentFutures = "1.3.0"
annotationExperimental = "1.6.0"
zxing = "3.5.4"
[libraries]
zxing-core = { group = "com.google.zxing", name = "core", version.ref = "zxing" }
androidx-annotation-experimental = { group = "androidx.annotation", name = "annotation-experimental", version.ref = "annotationExperimental" }
wear-tiles = { group = "androidx.wear.tiles", name = "tiles", version.ref = "wearTiles" }
wear-protolayout = { group = "androidx.wear.protolayout", name = "protolayout", version.ref = "protoLayout" }
+17
View File
@@ -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