Add SFTP backups and remote playback for Wear OS

Add server settings, transfer status, and automatic backups

Support Ed25519 keys and one-time server trust approval

Resume uploads, verify checksums, and preserve local recordings

Add cached remote playback, tests, and setup documentation
This commit is contained in:
Meghdad committed 2026-10-14 20:15:18 +03:30
1 parent f3b4006337
commit d9cfb017d7
31 files changed
+1799 -9

No files matched your search

+13 -2
View File
@@ -2,7 +2,7 @@
## Scope & Project Status
These instructions apply throughout the repository. Remember is an experimental, local-only microphone recorder for round Wear OS watches, with Galaxy Watch 7 as the primary design target. Physical-watch validation is still pending; successful builds or emulator tests do not establish production or Play Store readiness. Keep changes focused on the requested behavior and preserve unrelated work.
These instructions apply throughout the repository. Remember is an experimental microphone recorder with optional self-hosted SFTP backup for round Wear OS watches, with Galaxy Watch 7 as the primary design target. Physical-watch validation is still pending; successful builds or emulator tests do not establish production or Play Store readiness. Keep changes focused on the requested behavior and preserve unrelated work.
## Project Structure & Module Organization
@@ -60,6 +60,17 @@ The UI uses native Android views and custom drawing, without Compose or a runtim
- Preserve five-second storage refresh while that page is open, manual Refresh, and stale-result guards. Do not request usage access to other apps for this feature.
- Stop decorative motion when animations are disabled, battery saver is active, the activity is backgrounded, or capture is paused. Avoid extra background polling or animation work.
## Backup Invariants
- `BackupActivity.kt` owns backup pages; `BackupSettings.kt` stores destination details, encrypted key material, and receipts. `BackupTransport.kt` handles pinned-key SFTP; `BackupWorker.kt` schedules persisted Android jobs and serializes network actions with `BackupGate`.
- Require an explicit server configuration and an approved SHA256 host-key fingerprint. First-time discovery must reject the fetched key before authentication and save nothing until the user approves the approval screen. Block changed identities; explicit Forget trust pauses backups. Never disable host verification, authenticate an unapproved server, or log/export private keys. Encrypt stored SSH private keys using Android Keystore.
- Generate new watch identities as Ed25519 using the Android-compatible BC backend and OpenSSH private-key format. Preserve existing RSA identities until explicit replacement; pause backups and require server authorization of the new public key when replacing one.
- Upload only finalized clips. Preserve local audio, metadata, and bookmarks. Local deletion must not propagate to server backups. Scope receipts to the destination; acknowledge only the snapshot actually uploaded.
- Resume temporary uploads, verify full-file SHA-256, then publish metadata as the completion marker. Do not mark a failed or incomplete upload as backed up. Respect cancellation, socket timeouts, bounded buffers, and one active connection at a time.
- Keep automatic uploads opt-in, constrained to charging and unmetered connections by default. Use Android JobScheduler; scheduling is approximate and must not claim exact-time execution.
- Remote listening uses a verified temporary cache, not streaming. Pause playback outside the foreground and retain the previous cache if download verification fails. Remote filenames and manifests are untrusted: enforce safe IDs, sizes, and bounded metadata reads.
- SSH encrypts transport, not stored server files. Do not present at-rest encryption, restore, or remote deletion controls until implemented.
## Testing Guidelines
Use JUnit 4 for JVM tests and AndroidJUnit4/AndroidX instrumentation for device tests; Espresso is available. Name test classes `*Test` and methods after expected behavior. Cover changed boundaries and recording behavior; no numeric coverage threshold is configured. Recording-service changes require device tests on a disposable microphone-enabled emulator. Ensure only the intended emulator is connected, and never test during a personal recording.
@@ -76,6 +87,6 @@ Use concise, descriptive commit subjects. Keep PRs focused, explain behavior cha
Preserve audio and bookmarks, rotary access, spoken descriptions, and animation/battery preferences. Discuss accounts, networking, or analytics before introducing them. Keep personal audio, credentials, signing keys, local configuration, and build output untracked. See `CONTRIBUTING.md` and `PRIVACY.md` for additional guidance.
Keep the app standalone and local-only, with no internet permission, accounts, analytics, ads, or uploads unless an explicitly discussed feature changes that scope. Backups are disabled; uninstalling removes recordings and preferences. Do not include private recordings, identifying logs, or machine-specific paths in documentation, issues, or screenshots.
Keep capture standalone and local. Optional SFTP networking is authorized for user-configured backups and remote playback; automatic backup is off by default. Do not add app accounts, analytics, ads, or other network services without discussing them. Android backups are disabled; uninstalling removes local recordings, SSH identity, and preferences but leaves server copies intact. Do not include private recordings, identifying logs, or machine-specific paths in documentation, issues, or screenshots.
Keep `README.md`, `PRIVACY.md`, and screenshots aligned with changes to behavior, setup, permissions, or limitations. Code and original artwork use MIT; maintain `THIRD_PARTY_NOTICES.md` and relevant notices when adding dependencies or assets. The design is inspired by Samsung's Spatial Number face, but no Samsung font or wallpaper is bundled; use original or appropriately licensed assets.
+2 -1
View File
@@ -25,6 +25,7 @@ Recording-service changes also need the device tests. Use a disposable emulator:
- Keep microphone activity visible to the user. Recording should begin with an explicit action.
- Preserve saved audio and bookmarks when changing recording or storage behavior.
- Respect disabled system animations and battery-saving mode.
- Do not introduce accounts, networking, or analytics without discussing the change first.
- SFTP backup and remote playback are opt-in network features. Preserve fingerprint verification, encrypted key storage, cancellation, checksums, local retention, and charging/network preferences. Test against disposable server folders and recordings.
- Do not introduce app accounts, additional network services, or analytics without discussing the change first.
Do not include local IDE/device configuration, credentials, signing keys, build output, or personal audio in a pull request. Avoid attaching private recordings or identifying information to issues. Contributions are covered by the repository's [MIT license](LICENSE).
+6 -2
View File
@@ -3,11 +3,15 @@
Remember records audio only after the user starts capture and grants microphone access.
- Recordings and bookmark metadata are stored in the app's private local storage.
- The app has no internet permission, accounts, analytics, advertising, or upload feature.
- 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.
- 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.
- Recording uses a microphone foreground service so it can continue when the screen is off. An ongoing recording notification includes a Save action when notifications are allowed.
- Playback pauses when the playback activity leaves the foreground.
- Renaming updates a recording's local metadata. Deletion removes the recording after confirmation.
- Uninstalling the app removes its recordings and preferences. Export and phone transfer are not implemented.
- Uninstalling the app removes local recordings, preferences, playback cache, and the stored SSH identity. It does not delete server backups. You will need to authorize a new watch public key after reinstalling. Restoring backups into the local library and phone transfer are not implemented.
Developer tools and test runs can access the debug app's files. Use disposable emulator recordings for testing, and do not publish private audio or logs in issues or pull requests.
+27 -3
View File
@@ -20,6 +20,7 @@ Screenshots from a Wear OS round-screen emulator:
- Floating rounded numerals show captured minutes; the background sweep shows seconds within the current minute.
- A live microphone edge meter and an interactive bookmark/playback edge.
- Device and app storage monitoring with a large proportional chart.
- Optional SFTP backups to your own server, a transfer queue, scheduled uploads, and remote playback.
- Optional minute limits: save and stop, or save each clip and start the next at zero.
- Native controls, spoken descriptions for custom visuals, and rotary input.
@@ -30,7 +31,9 @@ The appearance is inspired by Samsung's [Spatial Number watch face](https://gala
**Experimental: suitable for development and evaluation.** Build, lint, unit tests, and recording integration tests have passed locally. The UI has been checked on a Wear OS round-screen emulator; recording integration tests used a separate Android emulator. Physical Galaxy Watch 7 validation is still pending.
- Captures microphone sound, not internal system audio or call audio.
- Recordings stay on the watch. Export, phone transfer, and transcription are not implemented.
- Recordings stay on the watch unless you configure and trigger SFTP backups. Phone transfer, restore into the local library, and transcription are not implemented.
- Backup is experimental. Your real server and its 128 MB memory budget have not yet been validated.
- Backup generates Ed25519 watch keys and pins the server fingerprint. Existing RSA watch keys remain usable until explicitly replaced. Password login and private-key import are not implemented; RSA, ECDSA, and Ed25519 server host keys are supported.
- Playback pauses when you leave the playback activity.
- A brief gap can occur between automatically split clips.
- Each clip has a 500 MB safety cap; reaching it saves the clip and stops the session.
@@ -116,6 +119,27 @@ Turn the limit off for unlimited recording by time, or turn it on and choose **1
Under **At the limit**, choose **Save & stop** to end the recording, or **Save & start next** to continue with a new clip at zero. Split clips have numbered titles and their own bookmarks. Paused time does not count. Changes apply to the next recording session, including all its parts. The 500 MB safety cap applies in either mode.
## Backup
Open **Settings → Backup**. Dedicated pages keep setup, transfer status, remote listening, and scheduling separate.
<p>
<img src="docs/backup-overview.png" width="240" alt="Backup overview with backed-up and waiting counts and Back up now" />
<img src="docs/backup-trust.png" width="240" alt="Server approval with Trust server and Cancel buttons, without fingerprint typing" />
<img src="docs/backup-server.png" width="240" alt="Server settings with address, port, and username fields" />
<img src="docs/backup-automatic.png" width="240" alt="Automatic backup disabled, with charging and unmetered preferences enabled" />
</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).
- **Transfers:** shows saved recordings and their status. **Back up / Retry** queues unfinished or changed recordings. **Pause all backups** 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.
- **Advanced:** choose 1/3/5 retry attempts, a 20/40/60-second connection timeout, or clear the playback cache. Server identity shows the remembered fingerprint; Forget trust pauses backups and allows a verified server-key change to be approved again.
Uploads use one SFTP connection at a time and bounded buffers, without a database, HTTP backend, shell commands, or compression. Interrupted audio uploads resume; the completed remote audio is read back and SHA-256 checked before publishing metadata and marking it backed up. This integrity check costs an additional full-file download. Each clip has its own audio file and JSON manifest containing title, duration, bookmarks, byte count, and checksum. Metadata changes queue another backup. Receipts are scoped to server address, account, folder, and pinned host key. A receipt records a successful transfer; it does not continuously check whether a server copy was subsequently removed.
The watch's private SSH key is encrypted using Android Keystore. SSH encrypts transport; audio and metadata on your server are **not encrypted at rest**. End-to-end encryption, exact-time scheduling, bandwidth caps, remote deletion, and restoration into the local library are not implemented. Automatic backup checks periodically for finished clips; saving a clip does not force an immediate upload. Interrupted jobs retain partial files for a later retry, subject to the configured retry limit.
## Tests and automated checks
Local checks:
@@ -130,13 +154,13 @@ Device tests require a **disposable** emulator with a microphone. They create au
./gradlew :app:connectedDebugAndroidTest
```
Coverage includes duration formatting, limit boundaries, pause exclusion, real one-minute automatic stop and split rollover, playable file output, bookmarks, settings persistence/navigation, storage accounting, and clip rename/delete behavior.
Coverage includes backup destination validation, encrypted watch-key persistence, backup-page navigation, manifest safety, and (with an opt-in disposable SFTP fixture) resumable transfers, checksum verification, host-key rejection, actual scheduled uploads, scheduling constraints, and cached remote playback/background pause. Network fixture instructions are in [docs/backup.md](docs/backup.md). Coverage also includes duration formatting, limit boundaries, pause exclusion, real one-minute automatic stop and split rollover, playable file output, bookmarks, settings persistence/navigation, storage accounting, and clip rename/delete behavior.
[Android checks](.github/workflows/android.yml) runs on pushes, pull requests, and manual dispatch. It verifies the wrapper, builds the debug app, runs lint and unit tests, and compiles device tests. It uploads check reports and a debug APK with a 14-day retention period. Device tests are run locally; the workflow does not claim to run them. The workflow uses pinned action commits and read-only repository permissions. Its first hosted run will happen after the repository is pushed to GitHub.
## Privacy, contributions, and license
Recordings remain in the app's private local storage. There are no accounts, analytics, ads, or upload features, and no internet permission. See [PRIVACY.md](PRIVACY.md).
Recordings use private local storage, with optional uploads to your own SFTP server. Automatic backups are off by default. There are no app accounts, analytics, or ads. See [PRIVACY.md](PRIVACY.md).
See [CONTRIBUTING.md](CONTRIBUTING.md) for development and pull-request guidance. Keep private audio, credentials, signing keys, local IDE/device configuration, and build output out of the repository.
+10
View File
@@ -8,8 +8,18 @@ The checked-in `gradlew`, `gradlew.bat`, and `gradle/wrapper/gradle-wrapper.jar`
The wrapper configuration pins the Gradle distribution and its official SHA-256 checksum. The included JAR checksum also matches Gradle's published checksum. These generated wrapper files are not relicensed under MIT.
## JSch SSH/SFTP library
The app includes [mwiede/JSch 2.28.8](https://github.com/mwiede/jsch/tree/jsch-2.28.8), a maintained fork of JCraft's JSch, under its BSD-style license. Its copyright, conditions, and disclaimer are retained in [licenses/JSch.txt](licenses/JSch.txt) and in the app's bundled license assets. JSch is not relicensed under MIT.
## Bouncy Castle cryptography
[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.
## Resolved dependencies and platform resources
Android APIs, Kotlin runtime libraries, the Android Gradle Plugin, and test libraries are obtained through the Android SDK or Gradle rather than copied as source into this repository. Their own license notices apply. Dependency coordinates and versions are listed in `gradle/libs.versions.toml` and `app/build.gradle.kts`.
The app uses Android's installed system fonts. No Samsung font, watch-face asset, or wallpaper is bundled. The Spatial Number appearance is referenced as design inspiration; the numeral paths and other app artwork are drawn in project code. Screenshots in `docs/` show the app running in an emulator.
The optional Python SFTP test fixture uses separately installed Paramiko and cryptography packages under their upstream licenses. These development-only packages are not bundled in the Android app.
+2
View File
@@ -35,6 +35,8 @@ android {
}
dependencies {
implementation(libs.jsch)
implementation(libs.bcprov)
testImplementation(libs.junit)
androidTestImplementation(libs.androidx.espresso.core)
androidTestImplementation(libs.androidx.junit)
@@ -0,0 +1,302 @@
package meghdad.remember
import android.app.job.JobScheduler
import android.Manifest
import android.media.MediaRecorder
import android.media.MediaPlayer
import android.content.Intent
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.action.ViewActions.click
import androidx.test.espresso.matcher.ViewMatchers.withText
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Assert.*
import org.junit.Assume.assumeTrue
import org.junit.Test
import org.junit.runner.RunWith
import java.io.File
import java.util.UUID
@RunWith(AndroidJUnit4::class)
class BackupTest {
private val instrumentation = InstrumentationRegistry.getInstrumentation()
private val context = instrumentation.targetContext
private val settings get() = BackupSettings(context)
private fun restorePreferences(previous: Map<String, *>) {
val editor = settings.preferences.edit().clear()
previous.forEach { (key, value) -> when (value) {
is String -> editor.putString(key, value)
is Boolean -> editor.putBoolean(key, value)
is Int -> editor.putInt(key, value)
is Long -> editor.putLong(key, value)
} }
editor.commit()
}
@Test fun backupPagesAreReachableAndAutomaticUploadsDefaultOff() {
val activity = instrumentation.startActivitySync(Intent(context, BackupActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
try {
instrumentation.runOnMainSync {
fun descendants(view: View): List<View> = listOf(view) + if (view is ViewGroup)
(0 until view.childCount).flatMap { descendants(view.getChildAt(it)) } else emptyList()
fun button(label: String) = descendants(activity.window.decorView).filterIsInstance<Button>().first { it.text == label }
listOf("Server", "Transfers", "Server recordings", "Automatic backup", "Advanced").forEach {
button(it).performClick(); button("Back").performClick()
}
}
assertFalse(settings.automatic)
} finally { instrumentation.runOnMainSync { activity.finish() } }
}
@Test fun encryptedWatchKeyPersistsWithoutPlaintextPrivateKeyInPreferences() {
val public = settings.generateKey()
assertTrue(public.startsWith("ssh-ed25519 "))
assertEquals(public, BackupSettings(context).generateKey())
val privateKey = settings.privateKey()
try {
assertTrue(privateKey.toString(Charsets.UTF_8).contains("OPENSSH PRIVATE KEY"))
assertFalse(settings.preferences.getString("key", "")!!.contains("PRIVATE KEY"))
} finally { privateKey.fill(0) }
}
@Test fun manifestsPreserveTitlesAndBookmarksAndRejectTraversal() {
val clip = Clip(UUID.randomUUID().toString(), "A thought", 1000, 20000, listOf(1000, 12000))
assertEquals(clip, parseRemoteClip(clipManifest(clip, 4096, "a".repeat(64))).clip)
assertThrows(IllegalArgumentException::class.java) {
parseRemoteClip(clipManifest(clip.copy(id = "../../private"), 4096, "a".repeat(64)))
}
}
@Test fun discoveryDoesNotSaveTrustOrRequireAWatchKey() {
val args = InstrumentationRegistry.getArguments()
val expected = args.getString("sftpFingerprint")
assumeTrue("Disposable SFTP fixture not configured", expected != null)
val previous = settings.preferences.all
val pending = BackupServer("127.0.0.1", args.getString("sftpPort", "2222").toInt(), "backup-test", "/remember", "")
try {
settings.save(pending)
settings.preferences.edit().remove("key").remove("public_key").commit()
val found = ServerTrustProbe(pending, 20).use { it.fetch() }
assertEquals(expected, found)
assertEquals("", settings.server().fingerprint)
assertNull(settings.publicKey())
assertThrows(IllegalArgumentException::class.java) { BackupTransport(context).use { it.connect() } }
} finally { restorePreferences(previous) }
}
@Test fun connectAndTrustRequiresApprovalAndBlocksChangedIdentity() {
val args = InstrumentationRegistry.getArguments()
val expected = args.getString("sftpFingerprint")
assumeTrue("Disposable SFTP fixture not configured", expected != null)
val previous = settings.preferences.all
val pending = BackupServer("127.0.0.1", args.getString("sftpPort", "2222").toInt(), "backup-test", "/remember", "")
var activity: android.app.Activity? = null
fun descendants(view: View): List<View> = listOf(view) + if (view is ViewGroup)
(0 until view.childCount).flatMap { descendants(view.getChildAt(it)) } else emptyList()
fun press(label: String) = instrumentation.runOnMainSync {
descendants(activity!!.window.decorView).filterIsInstance<Button>().first { it.text == label }.performClick()
}
fun await(condition: () -> Boolean) {
val end = android.os.SystemClock.elapsedRealtime() + 10000
while (!condition() && android.os.SystemClock.elapsedRealtime() < end) android.os.SystemClock.sleep(50)
assertTrue("Trust flow did not reach expected state", condition())
}
fun dialogVisible() = instrumentation.uiAutomation.rootInActiveWindow
?.findAccessibilityNodeInfosByText("Trust this server?")?.any { it.text?.toString() == "Trust this server?" } == true
try {
settings.save(pending)
settings.preferences.edit().remove("key").remove("public_key").commit()
activity = instrumentation.startActivitySync(Intent(context, BackupActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
press("Server")
instrumentation.runOnMainSync {
assertEquals("Fingerprint must not require typing", 4, descendants(activity!!.window.decorView).filterIsInstance<EditText>().size)
}
press("Connect & trust"); await { dialogVisible() }
assertEquals("", settings.server().fingerprint)
if (args.getString("saveTrustScreenshot") == "true") {
instrumentation.uiAutomation.waitForIdle(200, 3000)
instrumentation.uiAutomation.takeScreenshot()?.let { bitmap ->
File(context.cacheDir, "trust-dialog.png").outputStream().use { bitmap.compress(android.graphics.Bitmap.CompressFormat.PNG, 100, it) }
bitmap.recycle()
}
}
onView(withText(android.R.string.cancel)).perform(click())
assertEquals("", settings.server().fingerprint)
press("Connect & trust"); await { dialogVisible() }
press("View fingerprint")
onView(withText(expected)).check(matches(isDisplayed()))
assertEquals("Viewing the fingerprint must not approve it", "", settings.server().fingerprint)
press("Back"); await { dialogVisible() }
if (args.getString("saveTrustScreenshot") == "true") {
instrumentation.uiAutomation.waitForIdle(200, 3000)
instrumentation.uiAutomation.takeScreenshot()?.let { bitmap ->
File(context.cacheDir, "trust-dialog.png").outputStream().use { bitmap.compress(android.graphics.Bitmap.CompressFormat.PNG, 100, it) }
bitmap.recycle()
}
}
onView(withText("Trust server")).perform(click())
await { settings.server().fingerprint == expected }
val wrong = "SHA256:" + "A".repeat(43)
settings.save(settings.server().copy(fingerprint = wrong))
press("Connect & trust")
val busyField = BackupActivity::class.java.getDeclaredField("busy").apply { isAccessible = true }
await { var busy = true; instrumentation.runOnMainSync { busy = busyField.getBoolean(activity) }; !busy }
assertEquals("Changed identity must retain the existing pin", wrong, settings.server().fingerprint)
assertFalse(dialogVisible())
} finally {
instrumentation.runOnMainSync { activity?.finish() }
restorePreferences(previous)
}
}
@Test fun rsaIdentityIsRetainedUntilExplicitEd25519Replacement() {
val previous = settings.preferences.all
val rsa = com.jcraft.jsch.KeyPair.genKeyPair(SshCrypto.client(), com.jcraft.jsch.KeyPair.RSA, 2048)
val privateBytes = java.io.ByteArrayOutputStream().also { rsa.writePrivateKey(it) }.toByteArray()
try {
val public = java.io.ByteArrayOutputStream().also { rsa.writePublicKey(it, "migration-fixture") }.toString("UTF-8")
val encrypt = BackupSettings::class.java.getDeclaredMethod("encrypt", ByteArray::class.java).apply { isAccessible = true }
settings.preferences.edit().putString("key", encrypt.invoke(settings, privateBytes) as String).putString("public_key", public).commit()
assertEquals(public, settings.generateKey())
val retained = settings.privateKey()
try { assertArrayEquals(privateBytes, retained) } finally { retained.fill(0) }
val replaced = settings.generateKey(replace = true)
assertTrue(replaced.startsWith("ssh-ed25519 "))
assertEquals(replaced, BackupSettings(context).generateKey())
val key = settings.privateKey()
try { assertTrue(key.toString(Charsets.UTF_8).contains("OPENSSH PRIVATE KEY")) }
finally { key.fill(0) }
} finally { privateBytes.fill(0); rsa.dispose(); restorePreferences(previous) }
}
@Test fun manualJobBacksUpSavedAudioAndAutomaticJobsKeepConstraints() {
val args = InstrumentationRegistry.getArguments()
val fingerprint = args.getString("sftpFingerprint")
assumeTrue("Disposable SFTP fixture not configured", fingerprint != null)
assumeTrue("Do not test during recording", RecordingService.activeId == null)
val previous = settings.preferences.all
val store = Recordings(context)
val clip = Clip(UUID.randomUUID().toString(), "Scheduled fixture", 1000, 10000, listOf(1000))
val scheduler = context.getSystemService(JobScheduler::class.java)
settings.save(BackupServer("127.0.0.1", args.getString("sftpPort", "2222").toInt(), "backup-test", "/remember", fingerprint!!))
settings.generateKey()
store.audio(clip.id).writeBytes(ByteArray(65536) { (it % 251).toByte() }); store.save(clip)
try {
BackupWork.start(context)
val end = android.os.SystemClock.elapsedRealtime() + 60_000
while (settings.receipt(clip.id) == null && android.os.SystemClock.elapsedRealtime() < end) android.os.SystemClock.sleep(100)
assertEquals(backupVersion(clip, store.audio(clip.id)), settings.receipt(clip.id))
settings.preferences.edit().putBoolean("automatic", true).putBoolean("charging", true).putBoolean("unmetered", true).putInt("hours", 24).commit()
BackupWork.schedule(context)
val job = scheduler.getPendingJob(72)!!
assertTrue(job.isRequireCharging)
assertTrue(job.isPersisted)
assertTrue(job.requiredNetwork!!.hasCapability(android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED))
assertEquals(24 * 60 * 60_000L, job.intervalMillis)
BackupWork.cancel(context)
assertNull(scheduler.getPendingJob(72))
assertFalse(settings.automatic)
assertTrue("Backup must retain local audio", store.audio(clip.id).exists())
} finally {
BackupWork.cancel(context); store.delete(clip)
restorePreferences(previous)
}
}
@Test fun remoteAudioPlaysFromVerifiedCacheAndPausesInBackground() {
val args = InstrumentationRegistry.getArguments()
val fingerprint = args.getString("sftpFingerprint")
assumeTrue("Disposable SFTP fixture not configured", fingerprint != null)
assumeTrue("Do not test during recording", RecordingService.activeId == null)
val previous = settings.preferences.all
val audio = File(context.cacheDir, "remote-playback-fixture.m4a")
var activity: android.app.Activity? = null
var foreground: android.app.Activity? = null
settings.save(BackupServer("127.0.0.1", args.getString("sftpPort", "2222").toInt(), "backup-test", "/remember", fingerprint!!))
settings.generateKey()
instrumentation.uiAutomation.grantRuntimePermission(context.packageName, Manifest.permission.RECORD_AUDIO)
try {
activity = instrumentation.startActivitySync(Intent(context, BackupActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
val recorder = MediaRecorder(context)
try {
recorder.setAudioSource(MediaRecorder.AudioSource.MIC)
recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC)
recorder.setOutputFile(audio.absolutePath)
recorder.prepare(); recorder.start(); android.os.SystemClock.sleep(3000); recorder.stop()
} finally { recorder.release() }
val id = UUID.randomUUID().toString()
val clip = Clip(id, "Playback fixture ${id.take(8)}", 1000, 3000, listOf(1000))
BackupTransport(context).use { client -> client.connect(); client.upload(audio, clip) { _, _ -> } }
fun descendants(view: View): List<View> = listOf(view) + if (view is ViewGroup)
(0 until view.childCount).flatMap { descendants(view.getChildAt(it)) } else emptyList()
fun click(prefix: String) = instrumentation.runOnMainSync {
descendants(activity!!.window.decorView).filterIsInstance<Button>().first { it.text.startsWith(prefix) }.performClick()
}
fun await(timeout: Long = 10000, condition: () -> Boolean) {
val end = android.os.SystemClock.elapsedRealtime() + timeout
var ready = false
while (!ready && android.os.SystemClock.elapsedRealtime() < end) {
instrumentation.runOnMainSync { ready = condition() }; if (!ready) android.os.SystemClock.sleep(50)
}
assertTrue("Remote playback did not reach expected state", ready)
}
click("Server recordings"); click("Refresh")
await { descendants(activity!!.window.decorView).filterIsInstance<Button>().any { it.text.startsWith(clip.title) } }
click(clip.title); click("Download & play")
val playerField = BackupActivity::class.java.getDeclaredField("player").apply { isAccessible = true }
val readyField = BackupActivity::class.java.getDeclaredField("playbackReady").apply { isAccessible = true }
await { readyField.getBoolean(activity) && (playerField.get(activity) as? MediaPlayer)?.isPlaying == true }
foreground = instrumentation.startActivitySync(Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
instrumentation.runOnMainSync { assertFalse((playerField.get(activity) as MediaPlayer).isPlaying) }
assertEquals(audio.inputStream().use { digestStream(it) }, File(context.cacheDir, "server-playback.m4a").inputStream().use { digestStream(it) })
} finally {
instrumentation.runOnMainSync { foreground?.finish(); activity?.finish() }
audio.delete(); File(context.cacheDir, "server-playback.m4a").delete()
restorePreferences(previous)
}
}
/** Opt-in: point ONLY at a disposable SFTP fixture, never at a personal backup folder. */
@Test fun sftpResumesVerifiesAndRejectsChangedHostKey() {
val args = InstrumentationRegistry.getArguments()
val fingerprint = args.getString("sftpFingerprint")
assumeTrue("Disposable SFTP fixture not configured", fingerprint != null)
val previous = settings.preferences.all
val fixture = BackupServer("127.0.0.1", args.getString("sftpPort", "2222").toInt(), "backup-test", "/remember", fingerprint!!)
val file = File(context.cacheDir, "backup-fixture.bin")
val downloaded = File(context.cacheDir, "backup-downloaded.bin")
val clip = Clip(UUID.randomUUID().toString(), "Disposable test", 1000, 20000, listOf(1000, 5000))
file.outputStream().use { output -> repeat(64) { output.write(ByteArray(32768) { (it % 251).toByte() }) } }
settings.save(fixture); settings.generateKey()
try {
var interrupted = false
BackupTransport(context).use { client ->
client.connect()
try { client.upload(file, clip) { sent, _ -> if (sent > 32768) error("Simulated interruption") } }
catch (_: Exception) { interrupted = true }
}
assertTrue(interrupted)
var firstProgress = 0L
BackupTransport(context).use { client ->
client.connect()
client.upload(file, clip) { sent, total ->
if (firstProgress == 0L) firstProgress = sent
assertTrue(sent <= total)
}
assertTrue("Expected resumed transfer", firstProgress > 32768)
val remote = client.list().single { it.clip.id == clip.id }
assertEquals(clip, remote.clip)
client.download(remote, downloaded) { _, _ -> }
assertEquals(file.inputStream().use { digestStream(it) }, downloaded.inputStream().use { digestStream(it) })
assertThrows(IllegalArgumentException::class.java) { client.download(remote.copy(digest = "0".repeat(64)), downloaded) { _, _ -> } }
assertEquals("Failed verification must preserve the previous cached file", file.length(), downloaded.length())
client.upload(file, clip.copy(title = "Renamed")) { _, _ -> }
assertEquals("Renamed", client.list().single { it.clip.id == clip.id }.clip.title)
}
settings.save(fixture.copy(fingerprint = "SHA256:" + "A".repeat(43)))
assertThrows(Exception::class.java) { BackupTransport(context).use { it.connect() } }
} finally {
file.delete(); downloaded.delete()
// Previous settings may be incomplete, so restore their fields without validating them.
restorePreferences(previous)
}
}
}
+5
View File
@@ -7,6 +7,9 @@
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application android:allowBackup="false" android:dataExtractionRules="@xml/data_extraction_rules" android:icon="@drawable/ic_remember"
android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/Theme.Remember">
<meta-data android:name="com.google.android.wearable.standalone" android:value="true" />
@@ -17,5 +20,7 @@
</intent-filter>
</activity>
<service android:name=".RecordingService" android:exported="false" android:foregroundServiceType="microphone" />
<activity android:name=".BackupActivity" android:exported="false" android:taskAffinity="" />
<service android:name=".BackupWorker" android:permission="android.permission.BIND_JOB_SERVICE" android:exported="true" />
</application>
</manifest>
@@ -0,0 +1,15 @@
MIT License (https://opensource.org/licenses/MIT)
Copyright (c) 2000-2026 The Legion of the Bouncy Castle Inc. (https://www.bouncycastle.org).
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sub license, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: The above copyright notice and this
permission notice shall be included in all copies or substantial portions of the Software.
**THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.**
+30
View File
@@ -0,0 +1,30 @@
JSch 0.0.* was released under the GNU LGPL license. Later, we have switched
over to a BSD-style license.
------------------------------------------------------------------------------
Copyright (c) 2002-2015 Atsuhiko Yamanaka, JCraft,Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,462 @@
package meghdad.remember
import android.app.Activity
import android.app.AlertDialog
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.media.MediaPlayer
import android.os.*
import android.text.InputType
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.widget.*
import java.io.File
import java.text.DateFormat
import java.util.Date
import java.util.concurrent.Executors
import kotlin.math.roundToInt
/** Backup navigation is independent of capture; opening it never stops RecordingService. */
class BackupActivity : Activity() {
private val lime = Color.rgb(199, 234, 24)
private val muted = Color.rgb(164, 175, 143)
private lateinit var settings: BackupSettings
private lateinit var body: LinearLayout
private lateinit var scroll: ScrollView
private var page = "overview"
private var busy = false
private val executor = Executors.newSingleThreadExecutor()
private val handler = Handler(Looper.getMainLooper())
@Volatile private var client: BackupTransport? = null
@Volatile private var trustProbe: ServerTrustProbe? = null
private var player: MediaPlayer? = null
private var playbackReady = false
private var resumed = false
private var selected: RemoteClip? = null
private var remoteClips: List<RemoteClip> = emptyList()
private var serverDraft: BackupServer? = null
private var pendingTrust: BackupServer? = null
private var summary: TextView? = null
private var progress: TextView? = null
private var playbackButton: Button? = null
private var seek: SeekBar? = null
private val rows = mutableMapOf<String, TextView>()
private var localClips: List<Clip> = emptyList()
private val tick = object : Runnable {
override fun run() {
if (page == "overview") summary?.text = settings.preferences.getString("summary", "Ready when you are")
if (page == "transfers") rows.forEach { (id, view) ->
val clip = localClips.find { it.id == id }
if (clip != null) view.text = transferState(clip)
}
player?.takeIf { playbackReady }?.let { p -> runCatching {
seek?.progress = p.currentPosition
playbackButton?.text = if (p.isPlaying) "Pause" else "Play"
progress?.text = timeLabel(p.currentPosition.toLong())
} }
handler.postDelayed(this, 1000)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
settings = BackupSettings(this)
if (Build.VERSION.SDK_INT >= 33) onBackInvokedDispatcher.registerOnBackInvokedCallback(0) { back() }
render()
}
override fun onResume() { super.onResume(); resumed = true; handler.post(tick) }
override fun onPause() { resumed = false; handler.removeCallbacks(tick); if (playbackReady) player?.pause(); super.onPause() }
override fun onDestroy() { trustProbe?.close(); client?.close(); executor.shutdownNow(); player?.release(); super.onDestroy() }
private fun dp(value: Int) = (value * resources.displayMetrics.density).roundToInt()
private fun text(value: String, size: Float = 12f, color: Int = Color.WHITE): TextView = TextView(this).apply {
text = value; textSize = size; setTextColor(color); gravity = Gravity.CENTER
setPadding(dp(3), dp(5), dp(3), dp(5)); body.addView(this, LinearLayout.LayoutParams(-1, -2))
}
private fun button(label: String, action: () -> Unit): Button = Button(this).apply {
text = label; textSize = 12f; isAllCaps = false; setTextColor(Color.WHITE)
background = GradientDrawable().apply { setColor(Color.rgb(43, 52, 32)); cornerRadius = dp(24).toFloat() }
stateListAnimator = null
setOnClickListener { action() }
body.addView(this, LinearLayout.LayoutParams(-1, dp(48)).apply { setMargins(0, dp(4), 0, dp(4)) })
}
private fun navigate(target: String) {
if (busy) { toast(getString(R.string.backup_wait_for_the_current_action_or_cancel_it)); return }
player?.release(); player = null
playbackReady = false
page = target; render()
}
private fun render() {
rows.clear(); summary = null; progress = null; playbackButton = null; seek = null
scroll = ScrollView(this).apply { isFillViewport = true; isVerticalScrollBarEnabled = false; setBackgroundColor(Color.rgb(13, 17, 11)) }
body = LinearLayout(this).apply {
orientation = LinearLayout.VERTICAL; gravity = Gravity.CENTER_HORIZONTAL
// Keep controls inside a round watch's usable area even on emulator images
// that omit the round configuration qualifier.
setPadding(dp(28), dp(28), dp(28), dp(36))
}
scroll.addView(body); setContentView(scroll)
scroll.setOnGenericMotionListener { _, event ->
if (event.action == MotionEvent.ACTION_SCROLL) {
scroll.smoothScrollBy(0, (-event.getAxisValue(MotionEvent.AXIS_SCROLL) * dp(35)).toInt()); true
} else false
}
when (page) {
"server" -> serverPage()
"trust" -> trustPage()
"trust_fingerprint" -> {
title(getString(R.string.backup_server_identity))
text(pendingTrust?.fingerprint.orEmpty(), 12f, muted)
button(getString(R.string.backup_back)) { navigate("trust") }
}
"transfers" -> transfersPage()
"remote" -> remotePage()
"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") } }
else -> overview()
}
}
private fun title(value: String) { text(value.uppercase(), 10f, lime) }
private fun overview() {
title(getString(R.string.backup_backup))
text(getString(R.string.backup_keep_your_moments), 16f)
val clips = Recordings(this).list()
val backed = clips.count { settings.receipt(it.id) == backupVersion(it, Recordings(this).audio(it.id)) }
text("$backed backed up\n${clips.size - backed} waiting", 16f, lime)
button(getString(R.string.backup_back_up_now)) { startBackup() }.apply {
background = GradientDrawable().apply {
setColor(Color.rgb(35, 44, 20)); cornerRadius = dp(24).toFloat(); setStroke(dp(1), lime)
}
}
val time = settings.preferences.getLong("last_success", 0)
text(if (time == 0L) "No completed backup yet" else "Last backup\n${DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(Date(time))}", 10f, muted)
summary = text(settings.preferences.getString("summary", "Ready when you are")!!, 11f, muted)
button(getString(R.string.backup_server)) { navigate("server") }
button(getString(R.string.backup_transfers)) { navigate("transfers") }
button(getString(R.string.backup_server_recordings)) { navigate("remote") }
button(getString(R.string.backup_automatic_backup)) { navigate("automatic") }
button(getString(R.string.backup_advanced)) { navigate("advanced") }
button(getString(R.string.backup_back)) { finish() }
}
private fun field(label: String, value: String, type: Int = InputType.TYPE_CLASS_TEXT): EditText {
text(label, 11f, muted)
return EditText(this).apply {
setText(value); setTextColor(Color.WHITE); textSize = 12f; inputType = type
contentDescription = label; setSelectAllOnFocus(true)
body.addView(this, LinearLayout.LayoutParams(-1, -2))
}
}
private fun serverPage() {
title(getString(R.string.backup_server))
val server = serverDraft?.withRememberedTrust(settings.server()) ?: settings.server()
val host = field(getString(R.string.backup_address), server.host, InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI)
val port = field(getString(R.string.backup_port), server.port.toString(), InputType.TYPE_CLASS_NUMBER)
val user = field(getString(R.string.backup_username), server.user)
val folder = field(getString(R.string.backup_backup_folder), server.folder, InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI)
fun draft(): BackupServer = BackupServer(host.text.toString().trim(), port.text.toString().toIntOrNull() ?: 0,
user.text.toString().trim(), folder.text.toString().trim(), "").withRememberedTrust(settings.server())
val trustStatus = text(getString(if (server.fingerprint.isEmpty()) R.string.backup_server_untrusted else R.string.backup_server_trusted), 11f, lime)
fun updateTrustStatus() { trustStatus.text = getString(if (draft().fingerprint.isEmpty()) R.string.backup_server_untrusted else R.string.backup_server_trusted) }
val endpointWatcher = object : android.text.TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { updateTrustStatus() }
override fun afterTextChanged(s: android.text.Editable?) = Unit
}
host.addTextChangedListener(endpointWatcher); port.addTextChangedListener(endpointWatcher)
fun save(candidate: BackupServer): Boolean = persistServer(candidate).also { if (it) updateTrustStatus() }
fun testConnection() { runRemote("Connecting…") { it.test(); "Connected. Backup folder is accessible." } }
button(getString(R.string.backup_connect_trust)) {
val candidate = draft()
runCatching { candidate.validateConfiguration() }.onSuccess {
serverDraft = candidate
runTask(getString(R.string.backup_reading_server_identity), {
check(BackupGate.lock.tryLock()) { "A backup is running. Pause transfers first." }
try {
ServerTrustProbe(candidate, settings.timeout).use { probe ->
trustProbe = probe; probe.fetch()
}
} finally { trustProbe = null; BackupGate.lock.unlock() }
}) { found ->
if (draft().copy(fingerprint = "") != candidate.copy(fingerprint = "")) {
toast(getString(R.string.backup_server_details_changed))
} else if (candidate.fingerprint.isNotEmpty() && candidate.fingerprint != found) {
toast(getString(R.string.backup_server_key_changed))
} else if (candidate.fingerprint == found) {
if (save(candidate)) testConnection()
} else {
pendingTrust = candidate.copy(fingerprint = found)
page = "trust"; render()
}
}
}.onFailure { toast(it.message ?: "Check server settings") }
}
button(getString(R.string.backup_save_server)) {
if (save(draft())) {
if (settings.server().fingerprint.isNotEmpty()) BackupWork.schedule(this)
navigate("overview")
}
}
button(getString(R.string.backup_test_connection)) {
val candidate = draft()
runCatching { candidate.validate() }.onSuccess { if (save(candidate)) testConnection() }
.onFailure { toast(it.message ?: "Use Connect & trust first") }
}
button(if (settings.publicKey() == null) "Create watch key" else "Show watch key") {
runTask("Preparing key…", { settings.generateKey() }) { key ->
showPublicKey(key)
}
}
if (settings.publicKey()?.startsWith("ssh-rsa ") == true) {
button(getString(R.string.backup_replace_ed25519)) {
AlertDialog.Builder(this).setTitle(R.string.backup_replace_ed25519)
.setMessage(R.string.backup_replace_key_message)
.setPositiveButton(R.string.backup_replace_key_confirm) { _, _ ->
runTask("Preparing key…", {
BackupWork.cancel(this)
settings.generateKey(replace = true)
}) { key -> render(); showPublicKey(key) }
}.setNegativeButton(android.R.string.cancel, null).show()
}
}
progress = text("", 10f, muted)
button(getString(R.string.backup_back)) { navigate("overview") }
}
private fun persistServer(candidate: BackupServer): Boolean = try {
candidate.validateConfiguration()
check(!busy) { "Wait for the current action" }
check(BackupGate.lock.tryLock()) { "Pause transfers before changing the server" }
try {
if (candidate.fingerprint.isEmpty()) BackupWork.cancel(this)
settings.save(candidate)
} finally { BackupGate.lock.unlock() }
serverDraft = null; remoteClips = emptyList(); selected = null
true
} catch (error: Exception) { toast(error.message ?: "Check server settings"); false }
private fun cancelTrust() { pendingTrust = null; page = "server"; render() }
private fun trustPage() {
val candidate = pendingTrust ?: run { page = "server"; serverPage(); return }
text(getString(R.string.backup_trust_server_title), 17f, lime)
text(getString(R.string.backup_trust_server_address, candidate.host, candidate.port), 14f)
text(getString(R.string.backup_remember_server), 11f, muted)
button(getString(R.string.backup_trust_server_confirm)) {
if (persistServer(candidate)) {
pendingTrust = null; page = "server"; render()
if (settings.publicKey() != null) runRemote("Connecting…") { it.test(); "Connected. Backup folder is accessible." }
else toast(getString(R.string.backup_server_trusted_create_key))
}
}.setTextColor(lime)
button(getString(android.R.string.cancel)) { cancelTrust() }
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()
}
@Deprecated("Framework document picker result")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 20 && resultCode == RESULT_OK) runCatching {
contentResolver.openOutputStream(data?.data ?: error("No file selected"))!!.use { it.write(settings.publicKey()!!.toByteArray()) }
}.onSuccess { toast(getString(R.string.backup_public_key_exported)) }.onFailure { toast(getString(R.string.backup_could_not_export_key)) }
}
private fun transferState(clip: Clip): String = if (settings.receipt(clip.id) == backupVersion(clip, Recordings(this).audio(clip.id))) "Backed up" else settings.status(clip.id).let {
if (it == "Backed up") "Waiting · changed" else it
}
private fun transfersPage() {
title(getString(R.string.backup_transfers))
val clips = Recordings(this).list()
localClips = clips
if (clips.isEmpty()) text(getString(R.string.backup_save_a_recording_to_begin), 14f)
clips.forEach { clip ->
text(clip.title, 14f)
rows[clip.id] = text(transferState(clip), 11f, lime)
}
button(getString(R.string.backup_back_up_retry)) { startBackup() }
button(getString(R.string.backup_pause_all_backups)) {
BackupWork.cancel(this)
clips.forEach { if (transferState(it) != "Backed up") settings.status(it.id, "Waiting") }
toast(getString(R.string.backup_backups_paused_automatic_backup_is_off))
}
text(getString(R.string.backup_copies_stay_on_the_server_when_you_delete_local_recordings), 10f, muted)
button(getString(R.string.backup_back)) { navigate("overview") }
}
private fun startBackup() {
runCatching { BackupWork.start(this) }.onSuccess { toast(getString(R.string.backup_backup_queued_opens_when_connected)) }
.onFailure { toast(it.message ?: "Configure the server first") }
}
private fun remotePage() {
title(getString(R.string.backup_server_recordings))
button(getString(R.string.backup_refresh)) {
runTask("Loading recordings…", { withRemote { it.list() } }) { remoteClips = it; render() }
}
if (remoteClips.isEmpty()) text(getString(R.string.backup_tap_refresh_to_browse_your_backups), 12f, muted)
remoteClips.forEach { remote ->
val date = DateFormat.getDateInstance(DateFormat.SHORT).format(Date(remote.clip.created))
button("${remote.clip.title}\n$date · ${timeLabel(remote.clip.duration)}") { selected = remote; navigate("playback") }.apply {
maxLines = 2; ellipsize = android.text.TextUtils.TruncateAt.END
}
}
progress = text("", 10f, muted)
button(getString(R.string.backup_back)) { navigate("overview") }
}
private fun playbackPage() {
val remote = selected ?: return
title(getString(R.string.backup_server_playback))
text(remote.clip.title, 17f)
text("${timeLabel(remote.clip.duration)} · ${remote.clip.marks.size} bookmarks", 11f, muted)
text(getString(R.string.backup_audio_downloads_to_a_temporary_watch_cache_before_playing), 10f, muted)
progress = text(getString(R.string.backup_ready_to_download), 11f, lime)
playbackButton = button(getString(R.string.backup_download_play)) {
if (player != null) { if (playbackReady) player!!.let { if (it.isPlaying) it.pause() else it.start() }; return@button }
val file = File(cacheDir, "server-playback.m4a")
runTask("Preparing audio…", {
require(StatFs(cacheDir.absolutePath).availableBytes > remote.bytes + 16 * 1024 * 1024) { "Not enough free space for playback" }
var lastProgress = 0L
withRemote { client -> client.download(remote, file) { sent, total ->
val now = SystemClock.elapsedRealtime()
if (now - lastProgress > 500) {
lastProgress = now
handler.post { if (!isDestroyed && page == "playback") progress?.text = getString(R.string.backup_download_progress, sent * 100 / total) }
}
} }
file
}) { downloaded ->
runCatching {
player = MediaPlayer().apply {
setDataSource(downloaded.absolutePath)
setOnPreparedListener { p -> playbackReady = true; seek?.max = p.duration; if (resumed) p.start() }
setOnErrorListener { _, _, _ -> player?.release(); player = null; playbackReady = false; toast(getString(R.string.backup_could_not_play_audio)); true }
prepareAsync()
}
}.onFailure { toast(getString(R.string.backup_could_not_play_audio)) }
}
}
seek = SeekBar(this).apply {
contentDescription = "Playback position"
setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(bar: SeekBar?, value: Int, fromUser: Boolean) { if (fromUser && playbackReady) runCatching { player?.seekTo(value) } }
override fun onStartTrackingTouch(bar: SeekBar?) = Unit
override fun onStopTrackingTouch(bar: SeekBar?) = Unit
}); body.addView(this, LinearLayout.LayoutParams(-1, dp(40)))
}
remote.clip.marks.forEach { mark -> button("Bookmark · ${timeLabel(mark)}") { runCatching { player?.seekTo(mark.coerceAtMost(Int.MAX_VALUE.toLong()).toInt()) } } }
button(getString(R.string.backup_cancel_download)) { client?.close() }
button(getString(R.string.backup_back)) { navigate("remote") }
}
private fun toggle(label: String, value: Boolean, change: (Boolean) -> Unit) {
Switch(this).apply {
text = label; textSize = 12f; setTextColor(Color.WHITE); isChecked = value
setOnCheckedChangeListener { _, checked -> change(checked) }
body.addView(this, LinearLayout.LayoutParams(-1, dp(52)))
}
}
private fun automaticPage() {
title(getString(R.string.backup_automatic_backup))
toggle("Enable", settings.automatic) {
settings.preferences.edit().putBoolean("automatic", it).apply()
runCatching { BackupWork.schedule(this) }.onFailure { error ->
settings.preferences.edit().putBoolean("automatic", false).apply(); toast(error.message ?: "Configure server first"); render()
}
}
toggle("While charging", settings.charging) { updateOption("charging", it) }
toggle("Unmetered only", settings.unmetered) { updateOption("unmetered", it) }
button("Check every ${settings.hours} hours") {
choose("Backup interval", arrayOf("Every hour", "Every 6 hours", "Daily")) { index ->
settings.preferences.edit().putInt("hours", intArrayOf(1, 6, 24)[index]).apply(); BackupWork.schedule(this); render()
}
}
text(getString(R.string.backup_runs_when_conditions_allow_the_watch_may_delay_background), 10f, muted)
button(getString(R.string.backup_back)) { navigate("overview") }
}
private fun updateOption(key: String, value: Boolean) { settings.preferences.edit().putBoolean(key, value).apply(); BackupWork.schedule(this) }
private fun advancedPage() {
title(getString(R.string.backup_advanced))
button("Retry attempts · ${settings.attempts}") { choose("Retry attempts", arrayOf("1", "3", "5")) { index ->
settings.preferences.edit().putInt("attempts", intArrayOf(1, 3, 5)[index]).apply(); render()
} }
button("Connection timeout · ${settings.timeout}s") { choose("Connection timeout", arrayOf("20 seconds", "40 seconds", "60 seconds")) { index ->
settings.preferences.edit().putInt("timeout", intArrayOf(20, 40, 60)[index]).apply(); render()
} }
button(getString(R.string.backup_clear_playback_cache)) {
player?.release(); player = null; playbackReady = false
File(cacheDir, "server-playback.m4a").delete(); File(cacheDir, "server-playback.m4a.download").delete()
toast(getString(R.string.backup_playback_cache_cleared))
}
text(getString(R.string.backup_one_transfer_at_a_time_interrupted_uploads_resume_and_are), 10f, muted)
if (settings.server().fingerprint.isNotEmpty()) button(getString(R.string.backup_server_identity)) {
val trusted = settings.server()
AlertDialog.Builder(this).setTitle(R.string.backup_server_identity)
.setMessage("${trusted.host}:${trusted.port}\n\n${trusted.fingerprint}")
.setPositiveButton(R.string.backup_forget_trust) { _, _ ->
AlertDialog.Builder(this).setTitle(R.string.backup_forget_trust)
.setMessage(R.string.backup_forget_trust_message)
.setPositiveButton(R.string.backup_forget_trust) { _, _ ->
runTask("Pausing backups…", {
BackupWork.cancel(this)
check(BackupGate.lock.tryLock(5, java.util.concurrent.TimeUnit.SECONDS)) { "Wait for transfers to stop" }
try { settings.save(trusted.copy(fingerprint = "")) } finally { BackupGate.lock.unlock() }
}) { remoteClips = emptyList(); selected = null; render(); toast(getString(R.string.backup_trust_forgotten)) }
}.setNegativeButton(android.R.string.cancel, null).show()
}.setNegativeButton(android.R.string.cancel, null).show()
}
button(getString(R.string.backup_open_source_licenses)) { navigate("licenses") }
button(getString(R.string.backup_back)) { navigate("overview") }
}
private fun choose(title: String, values: Array<String>, action: (Int) -> Unit) { AlertDialog.Builder(this).setTitle(title).setItems(values) { _, index -> action(index) }.show() }
private fun <T> runTask(message: String, task: () -> T, done: (T) -> Unit) {
if (busy) { toast(getString(R.string.backup_an_action_is_already_running)); return }
busy = true; progress?.text = message
executor.execute {
val result = runCatching { task() }
handler.post {
busy = false
if (isDestroyed) return@post
result.onSuccess { progress?.text = ""; done(it) }.onFailure {
val message = friendlyError(it)
progress?.text = message; toast(message)
}
}
}
}
private fun <T> withRemote(action: (BackupTransport) -> T): T {
check(BackupGate.lock.tryLock()) { "A backup is running. Pause transfers first." }
try {
return BackupTransport(this) { check(!isDestroyed && !Thread.currentThread().isInterrupted) { "Cancelled" } }.use {
client = it; it.connect(); action(it)
}
} finally { client = null; BackupGate.lock.unlock() }
}
private fun runRemote(message: String, action: (BackupTransport) -> String) { runTask(message, { withRemote(action) }) { toast(it); progress?.text = it } }
private fun friendlyError(error: Throwable): String {
val message = error.message.orEmpty()
return when {
error is IllegalArgumentException || error is IllegalStateException -> message
message.contains("HostKey", true) || message.contains("host key", true) -> "Server fingerprint does not match. Check it with your administrator."
message.contains("Auth fail", true) -> "Key rejected. Authorize the watch public key on the server."
else -> "Connection failed. Check address, connection, permissions, and backup folder."
}
}
private fun toast(message: String) { Toast.makeText(this, message, Toast.LENGTH_LONG).show() }
private fun back() {
when (page) {
"overview" -> finish()
"trust" -> cancelTrust()
"trust_fingerprint" -> navigate("trust")
else -> navigate(when (page) { "playback" -> "remote"; "licenses" -> "advanced"; else -> "overview" })
}
}
@android.annotation.SuppressLint("GestureBackNavigation")
@Deprecated("Framework back navigation")
override fun onBackPressed() { back() }
}
@@ -0,0 +1,96 @@
package meghdad.remember
import android.content.Context
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.util.Base64
import com.jcraft.jsch.KeyPair
import java.io.ByteArrayOutputStream
import java.security.KeyStore
import java.security.MessageDigest
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec
data class BackupServer(val host: String, val port: Int, val user: String, val folder: String, val fingerprint: String) {
fun validateConfiguration() {
require(host.isNotBlank() && host.none { it.isWhitespace() || it == '/' }) { "Enter a server address without ssh://" }
require(port in 1..65535) { "Port must be 1–65535" }
require(user.isNotBlank()) { "Enter a username" }
require(folder.startsWith('/') && folder != "/" && folder.none { it == '\u0000' || it == '*' || it == '?' || it == '[' || it == '\\' } && folder.split('/').none { it == ".." }) { "Use an absolute backup folder without wildcards or .." }
require(fingerprint.isEmpty() || fingerprint.matches(Regex("SHA256:[A-Za-z0-9+/]{43}"))) { "Invalid server fingerprint" }
}
fun validate() {
validateConfiguration()
require(fingerprint.isNotEmpty()) { "Use Connect & trust on the Server page first" }
}
fun withRememberedTrust(previous: BackupServer): BackupServer = copy(
fingerprint = if (host == previous.host && port == previous.port) previous.fingerprint else "")
val identity: String get() = sha256("$host:$port\n$user\n$folder\n$fingerprint".toByteArray())
}
fun sha256(bytes: ByteArray): String = MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) }
/** Secrets are encrypted with a non-exportable Android Keystore wrapping key. */
class BackupSettings(context: Context) {
val preferences = context.getSharedPreferences("backup", Context.MODE_PRIVATE)
fun server() = BackupServer(preferences.getString("host", "")!!, preferences.getInt("port", 22),
preferences.getString("user", "")!!, preferences.getString("folder", "/remember")!!,
preferences.getString("fingerprint", "")!!)
fun save(server: BackupServer) {
server.validateConfiguration()
val changed = server.identity != server().identity
val editor = preferences.edit().putString("host", server.host).putInt("port", server.port).putString("user", server.user)
.putString("folder", server.folder.trimEnd('/')).putString("fingerprint", server.fingerprint)
if (changed) editor.putString("summary", "Ready when you are").putLong("last_success", 0)
editor.apply()
}
private fun wrappingKey(): SecretKey {
val store = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
return (store.getKey("remember-backup", null) as? SecretKey) ?: KeyGenerator.getInstance("AES", "AndroidKeyStore").apply {
init(KeyGenParameterSpec.Builder("remember-backup", KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM).setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE).build())
}.generateKey()
}
private fun encrypt(bytes: ByteArray): String {
val cipher = Cipher.getInstance("AES/GCM/NoPadding").apply { init(Cipher.ENCRYPT_MODE, wrappingKey()) }
return Base64.encodeToString(cipher.iv + cipher.doFinal(bytes), Base64.NO_WRAP)
}
fun privateKey(): ByteArray {
val data = Base64.decode(preferences.getString("key", null) ?: error("Generate a watch key first"), Base64.NO_WRAP)
return Cipher.getInstance("AES/GCM/NoPadding").run {
init(Cipher.DECRYPT_MODE, wrappingKey(), GCMParameterSpec(128, data.copyOfRange(0, 12)))
doFinal(data.copyOfRange(12, data.size))
}
}
fun publicKey(): String? = preferences.getString("public_key", null)
fun generateKey(replace: Boolean = false): String {
// Showing an existing public key must not pause an active transfer.
if (!replace) publicKey()?.let { return it }
check(BackupGate.lock.tryLock(5, java.util.concurrent.TimeUnit.SECONDS)) { "Pause transfers before changing the watch key" }
try {
if (!replace) publicKey()?.let { return it }
val pair = KeyPair.genKeyPair(SshCrypto.client(), KeyPair.ED25519)
try {
val privateBytes = ByteArrayOutputStream().also { pair.writeOpenSSHv1PrivateKey(it, null as ByteArray?) }.toByteArray()
val public = ByteArrayOutputStream().also { pair.writePublicKey(it, "remember-watch") }.toString("UTF-8")
try { check(preferences.edit().putString("key", encrypt(privateBytes)).putString("public_key", public).commit()) }
finally { privateBytes.fill(0) }
return public
} finally { pair.dispose() }
} finally { BackupGate.lock.unlock() }
}
val automatic get() = preferences.getBoolean("automatic", false)
val charging get() = preferences.getBoolean("charging", true)
val unmetered get() = preferences.getBoolean("unmetered", true)
val hours get() = preferences.getInt("hours", 24)
val attempts get() = preferences.getInt("attempts", 3)
val timeout get() = preferences.getInt("timeout", 20)
fun receipt(id: String): String? = preferences.getString("receipt_${server().identity}_$id", null)
fun receipt(id: String, version: String) {
check(preferences.edit().putString("receipt_${server().identity}_$id", version).commit()) { "Could not save backup status" }
}
fun status(id: String): String = preferences.getString("status_${server().identity}_$id", "Waiting")!!
fun status(id: String, text: String) { preferences.edit().putString("status_${server().identity}_$id", text).apply() }
}
@@ -0,0 +1,187 @@
package meghdad.remember
import android.content.Context
import com.jcraft.jsch.*
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.io.InputStream
import java.security.MessageDigest
data class RemoteClip(val clip: Clip, val bytes: Long, val digest: String)
fun clipManifest(clip: Clip, bytes: Long, digest: String): String = JSONObject()
.put("version", 1).put("id", clip.id).put("title", clip.title).put("created", clip.created)
.put("duration", clip.duration).put("marks", JSONArray(clip.marks)).put("bytes", bytes).put("sha256", digest).toString()
fun parseRemoteClip(text: String): RemoteClip {
val json = JSONObject(text)
require(json.getInt("version") == 1)
val id = json.getString("id")
require(id.matches(Regex("[a-fA-F0-9-]{36}")))
val bytes = json.getLong("bytes")
require(bytes in 1..500L * 1024 * 1024)
val digest = json.getString("sha256")
require(digest.matches(Regex("[a-f0-9]{64}")))
val duration = json.getLong("duration")
require(duration >= 0)
val marks = json.optJSONArray("marks") ?: JSONArray()
require(marks.length() <= 10000)
return RemoteClip(Clip(id, json.getString("title").take(200), json.getLong("created"), duration,
(0 until marks.length()).map { marks.getLong(it).coerceIn(0, duration) }), bytes, digest)
}
fun digestStream(input: InputStream, check: () -> Unit = {}, maximumBytes: Long = Long.MAX_VALUE): String {
val digest = MessageDigest.getInstance("SHA-256")
val buffer = ByteArray(32 * 1024)
var total = 0L
while (true) {
check()
val count = input.read(buffer)
if (count < 0) break
total += count
require(total <= maximumBytes) { "Audio exceeds its expected size" }
digest.update(buffer, 0, count)
}
return digest.digest().joinToString("") { "%02x".format(it) }
}
/** One authenticated session, bounded buffers, and no remote shell commands. */
class BackupTransport(context: Context, private val check: () -> Unit = {}) : AutoCloseable {
private val settings = BackupSettings(context)
private val server = settings.server().also { it.validate() }
private var session: Session? = null
private var channel: ChannelSftp? = null
@Volatile private var closed = false
private val sftp get() = channel ?: error("Not connected")
fun connect() {
check()
check(!closed) { "Connection cancelled" }
val ssh = SshCrypto.client()
ssh.hostKeyRepository = SshHostTrust.repository(server.fingerprint)
val key = settings.privateKey()
try { ssh.addIdentity("remember-watch", key, null, null) } finally { key.fill(0) }
val connection = ssh.getSession(server.user, server.host, server.port)
session = connection
connection.apply {
setConfig("StrictHostKeyChecking", "yes")
// Keep the previous RSA/ECDSA host-key preference for existing fingerprint pins.
// Ed25519 remains available for servers offering only that host-key type.
setConfig("server_host_key", SshHostTrust.ALGORITHMS)
setConfig("PreferredAuthentications", "publickey")
setConfig("compression.s2c", "none"); setConfig("compression.c2s", "none")
timeout = settings.timeout * 1000
connect(settings.timeout * 1000)
}
check()
check(!closed) { "Connection cancelled" }
val files = connection.openChannel("sftp") as ChannelSftp
channel = files
files.apply {
setBulkRequests(4)
connect(settings.timeout * 1000)
cd(server.folder)
}
check()
check(!closed) { "Connection cancelled" }
}
fun test(): String { check(); return sftp.pwd() }
private fun size(path: String): Long? = try { sftp.lstat(path).size } catch (e: SftpException) {
if (e.id == ChannelSftp.SSH_FX_NO_SUCH_FILE) null else throw e
}
fun upload(file: File, clip: Clip, stage: (String) -> Unit = {}, progress: (Long, Long) -> Unit): String {
check()
stage("Checking audio")
val digest = file.inputStream().use { digestStream(it, check) }
val manifest = clipManifest(clip, file.length(), digest)
val remote = "${clip.id}.m4a"
val partial = "$remote.upload"
stage("Checking server copy")
// Verify existing final audio too: metadata may have changed after an earlier backup.
val finalMatches = size(remote) == file.length() && sftp.get(remote).use { digestStream(it, check, file.length()) } == digest
if (!finalMatches) {
var offset = size(partial) ?: 0L
if (offset > file.length()) { sftp.rm(partial); offset = 0 }
var transferred = offset
val monitor = object : SftpProgressMonitor {
override fun init(op: Int, src: String?, dest: String?, max: Long) = Unit
override fun count(count: Long): Boolean {
check(); transferred += count; progress(transferred, file.length()); return true
}
override fun end() = Unit
}
file.inputStream().use { input ->
// JSch's InputStream RESUME overload skips the remote size itself.
sftp.put(input, partial, monitor, ChannelSftp.RESUME)
}
check()
stage("Verifying backup")
if (sftp.get(partial).use { digestStream(it, check, file.length()) } != digest) {
sftp.rm(partial)
error("Upload verification failed. Retry the recording.")
}
if (size(remote) != null) sftp.rm(remote)
sftp.rename(partial, remote)
}
check()
stage("Updating details")
manifest.byteInputStream().use { sftp.put(it, "${clip.id}.json.upload", ChannelSftp.OVERWRITE) }
if (size("${clip.id}.json") != null) sftp.rm("${clip.id}.json")
// Metadata is the commit marker; remote browsers ignore unfinished uploads.
sftp.rename("${clip.id}.json.upload", "${clip.id}.json")
return sha256(manifest.toByteArray())
}
fun list(): List<RemoteClip> {
val entries = mutableListOf<ChannelSftp.LsEntry>()
try {
sftp.ls("*.json", ChannelSftp.LsEntrySelector { entry ->
entries.add(entry)
if (entries.size >= 1000) ChannelSftp.LsEntrySelector.BREAK else ChannelSftp.LsEntrySelector.CONTINUE
})
} catch (e: SftpException) { if (e.id != ChannelSftp.SSH_FX_NO_SUCH_FILE) throw e }
return entries.mapNotNull { item ->
check()
if (!item.filename.matches(Regex("[a-fA-F0-9-]{36}\\.json")) || item.attrs.size > 128 * 1024) return@mapNotNull null
runCatching {
val remote = parseRemoteClip(sftp.get(item.filename).use { it.readBytesLimited(128 * 1024).toString(Charsets.UTF_8) })
require(item.filename == "${remote.clip.id}.json")
require(size("${remote.clip.id}.m4a") == remote.bytes)
remote
}.getOrNull()
}.sortedByDescending { it.clip.created }
}
fun download(remote: RemoteClip, destination: File, progress: (Long, Long) -> Unit) {
val temporary = File(destination.parentFile, "${destination.name}.download")
try {
sftp.get("${remote.clip.id}.m4a").use { input -> temporary.outputStream().use { output ->
val buffer = ByteArray(32 * 1024)
var total = 0L
while (true) {
check()
val count = input.read(buffer)
if (count < 0) break
total += count
require(total <= remote.bytes) { "Remote audio size changed" }
output.write(buffer, 0, count); progress(total, remote.bytes)
}
require(total == remote.bytes) { "Incomplete download" }
} }
require(temporary.inputStream().use { digestStream(it, check) } == remote.digest) { "Audio verification failed" }
check(destination.exists().not() || destination.delete())
check(temporary.renameTo(destination))
} finally { temporary.delete() }
}
override fun close() { closed = true; channel?.disconnect(); session?.disconnect(); channel = null; session = null }
}
private fun InputStream.readBytesLimited(limit: Int): ByteArray {
val output = java.io.ByteArrayOutputStream()
val buffer = ByteArray(4096)
while (true) {
val count = read(buffer)
if (count < 0) break
require(output.size() + count <= limit) { "Metadata is too large" }
output.write(buffer, 0, count)
}
return output.toByteArray()
}
@@ -0,0 +1,144 @@
package meghdad.remember
import android.content.Context
import android.app.job.JobInfo
import android.app.job.JobParameters
import android.app.job.JobScheduler
import android.app.job.JobService
import android.content.ComponentName
import java.io.File
import java.util.concurrent.TimeUnit
import java.util.concurrent.locks.ReentrantLock
object BackupGate { val lock = ReentrantLock() }
fun backupVersion(clip: Clip, file: File): String = sha256(
"${clip.id}\n${clip.title}\n${clip.created}\n${clip.duration}\n${clip.marks}\n${file.length()}\n${file.lastModified()}".toByteArray())
object BackupWork {
private const val MANUAL = 71
private const val AUTOMATIC = 72
fun start(context: Context) {
val settings = BackupSettings(context)
settings.server().validate()
require(settings.publicKey() != null) { "Generate and authorize the watch key first" }
val scheduler = context.getSystemService(JobScheduler::class.java)
if (scheduler.getPendingJob(MANUAL) != null) return
settings.preferences.edit().putInt("attempt_71", 0).putString("summary", "Waiting for connection").apply()
check(scheduler.schedule(JobInfo.Builder(MANUAL, ComponentName(context, BackupWorker::class.java))
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY).setPersisted(true)
.setBackoffCriteria(30_000, JobInfo.BACKOFF_POLICY_EXPONENTIAL).build()) == JobScheduler.RESULT_SUCCESS) { "Could not queue backup" }
}
fun cancel(context: Context) {
val scheduler = context.getSystemService(JobScheduler::class.java)
scheduler.cancel(MANUAL); scheduler.cancel(AUTOMATIC)
BackupSettings(context).preferences.edit().putBoolean("automatic", false).putString("summary", "Backups paused").apply()
}
fun schedule(context: Context) {
val settings = BackupSettings(context)
val scheduler = context.getSystemService(JobScheduler::class.java)
if (!settings.automatic) { scheduler.cancel(AUTOMATIC); return }
settings.server().validate()
require(settings.publicKey() != null) { "Generate and authorize the watch key first" }
check(scheduler.schedule(JobInfo.Builder(AUTOMATIC, ComponentName(context, BackupWorker::class.java))
.setPeriodic(TimeUnit.HOURS.toMillis(settings.hours.toLong()))
.setRequiresCharging(settings.charging).setPersisted(true)
.setRequiredNetworkType(if (settings.unmetered) JobInfo.NETWORK_TYPE_UNMETERED else JobInfo.NETWORK_TYPE_ANY)
.setBackoffCriteria(30_000, JobInfo.BACKOFF_POLICY_EXPONENTIAL).build()) == JobScheduler.RESULT_SUCCESS) { "Could not schedule backups" }
}
}
class BackupWorker : JobService() {
private data class Running(val runner: BackupRunner, val thread: Thread)
private val running = mutableMapOf<Int, Running>()
override fun onStartJob(params: JobParameters): Boolean {
val runner = BackupRunner(applicationContext)
val thread = Thread {
val retry = runner.performBackup(params.jobId)
android.os.Handler(mainLooper).post {
if (running[params.jobId]?.runner === runner) {
running.remove(params.jobId)
if (!runner.stopped) jobFinished(params, retry)
}
}
}
running[params.jobId] = Running(runner, thread)
thread.start()
return true
}
override fun onStopJob(params: JobParameters): Boolean {
running.remove(params.jobId)?.let { it.runner.stop(); it.thread.interrupt() }
return params.stopReason != JobParameters.STOP_REASON_CANCELLED_BY_APP
}
override fun onDestroy() {
running.values.forEach { it.runner.stop(); it.thread.interrupt() }; running.clear()
super.onDestroy()
}
}
private class BackupRunner(private val applicationContext: Context) {
@Volatile var stopped = false
private set
fun stop() { stopped = true; transport?.close() }
@Volatile private var transport: BackupTransport? = null
private fun ensureRunning() {
check(!stopped && !Thread.currentThread().isInterrupted) { "Backup paused" }
}
fun performBackup(jobId: Int): Boolean {
if (!BackupGate.lock.tryLock()) return true
val settings = BackupSettings(applicationContext)
var current: String? = null
val start = android.os.SystemClock.elapsedRealtime()
try {
settings.server().validate()
val store = Recordings(applicationContext)
val clips = store.list().filter { settings.receipt(it.id) != backupVersion(it, store.audio(it.id)) }
if (clips.isEmpty()) {
settings.preferences.edit().putInt("attempt_$jobId", 0).putString("summary", "Everything is backed up").apply()
return false
}
settings.preferences.edit().putString("summary", "Connecting…").apply()
BackupTransport(applicationContext) {
ensureRunning()
check(android.os.SystemClock.elapsedRealtime() - start < 8 * 60_000) { "Backup will continue in another attempt" }
}.use { client ->
transport = client
client.connect()
for (clip in clips) {
ensureRunning()
current = clip.id
val file = store.audio(clip.id)
if (!file.exists()) continue
val version = backupVersion(clip, file)
settings.status(clip.id, "Uploading")
var lastProgress = 0L
client.upload(file, clip, stage = { stage ->
settings.status(clip.id, stage)
settings.preferences.edit().putString("summary", stage).apply()
}) { sent, total ->
val now = android.os.SystemClock.elapsedRealtime()
if (now - lastProgress > 500) {
val percentage = (sent * 100 / total.coerceAtLeast(1)).coerceIn(0, 100)
settings.status(clip.id, "Uploading · $percentage%")
settings.preferences.edit().putString("summary", "Uploading · $percentage%").apply()
lastProgress = now
}
}
// A simultaneous rename should be uploaded again, not silently acknowledged.
settings.receipt(clip.id, version)
settings.status(clip.id, "Backed up")
}
}
settings.preferences.edit().putInt("attempt_$jobId", 0).putLong("last_success", System.currentTimeMillis()).putString("summary", "Backup complete").apply()
return false
} catch (_: Exception) {
val message = if (stopped) "Waiting" else "Failed · check connection and server settings"
current?.let { settings.status(it, message) }
settings.preferences.edit().putString("summary", if (stopped) "Backup paused" else message).apply()
val attempts = settings.preferences.getInt("attempt_$jobId", 0) + 1
val retry = !stopped && attempts < settings.attempts
settings.preferences.edit().putInt("attempt_$jobId", if (retry) attempts else 0).apply()
return retry
} finally { transport?.close(); transport = null; BackupGate.lock.unlock() }
}
}
@@ -243,6 +243,7 @@ class MainActivity : Activity() {
text("Make it yours.", 17f)
button("Storage") { screen = "storage"; render() }.apply { layoutParams.height = dp(56) }
button("Recording limit") { screen = "limits"; render() }.apply { layoutParams.height = dp(56) }
button("Backup") { startActivity(Intent(this, BackupActivity::class.java)) }.apply { layoutParams.height = dp(56) }
button(if (active) "Back to recording" else "Back") { screen = "home"; render() }
}
private fun storage() {
@@ -0,0 +1,13 @@
package meghdad.remember
import com.jcraft.jsch.JSch
/** Use the lightweight BC primitives directly, without replacing Android's JCA providers. */
object SshCrypto {
init {
JSch.setConfig("keypairgen.eddsa", "com.jcraft.jsch.bc.KeyPairGenEdDSA")
JSch.setConfig("keypairgen_fromprivate.eddsa", "com.jcraft.jsch.bc.KeyPairGenEdDSA")
JSch.setConfig("ssh-ed25519", "com.jcraft.jsch.bc.SignatureEd25519")
}
fun client(): JSch = JSch()
}
@@ -0,0 +1,54 @@
package meghdad.remember
import com.jcraft.jsch.*
import java.security.MessageDigest
import java.util.Base64
object SshHostTrust {
const val ALGORITHMS = "ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,rsa-sha2-512,rsa-sha2-256,ssh-ed25519"
fun fingerprint(key: ByteArray): String = "SHA256:" + Base64.getEncoder().withoutPadding()
.encodeToString(MessageDigest.getInstance("SHA-256").digest(key))
/** An unapproved discovery key is always rejected before authentication. */
fun repository(expected: String?, observed: (String) -> Unit = {}): HostKeyRepository = object : HostKeyRepository {
override fun check(host: String?, key: ByteArray): Int {
val actual = fingerprint(key)
observed(actual)
return when {
expected == null -> HostKeyRepository.NOT_INCLUDED
actual == expected -> HostKeyRepository.OK
else -> HostKeyRepository.CHANGED
}
}
override fun add(key: HostKey?, ui: UserInfo?) = Unit
override fun remove(host: String?, type: String?) = Unit
override fun remove(host: String?, type: String?, key: ByteArray?) = Unit
override fun getKnownHostsRepositoryID() = "Remember approved server"
override fun getHostKey(): Array<HostKey> = emptyArray()
override fun getHostKey(host: String?, type: String?): Array<HostKey> = emptyArray()
}
}
class ServerTrustProbe(private val server: BackupServer, private val timeout: Int) : AutoCloseable {
@Volatile private var connection: Session? = null
@Volatile private var closed = false
fun fetch(): String {
server.validateConfiguration()
check(!closed) { "Connection cancelled" }
var discovered: String? = null
val ssh = SshCrypto.client()
ssh.hostKeyRepository = SshHostTrust.repository(null) { discovered = it }
val session = ssh.getSession(server.user, server.host, server.port)
connection = session
try {
session.setConfig("StrictHostKeyChecking", "yes")
session.setConfig("server_host_key", SshHostTrust.ALGORITHMS)
session.timeout = timeout * 1000
try { session.connect(timeout * 1000) }
catch (error: JSchException) { if (discovered == null) throw error }
check(!closed) { "Connection cancelled" }
return discovered ?: error("Could not read the server identity")
} finally { session.disconnect(); connection = null }
}
override fun close() { closed = true; connection?.disconnect() }
}
+62 -1
View File
@@ -1 +1,62 @@
<resources><string name="app_name">Remember</string></resources>
<resources>
<string name="app_name">Remember</string>
<string name="backup_download_progress">Downloading · %1$d%%</string>
<string name="backup_address">Address</string>
<string name="backup_advanced">Advanced</string>
<string name="backup_an_action_is_already_running">An action is already running</string>
<string name="backup_audio_downloads_to_a_temporary_watch_cache_before_playing">Audio downloads to a temporary watch cache before playing.</string>
<string name="backup_automatic_backup">Automatic backup</string>
<string name="backup_back">Back</string>
<string name="backup_back_up_now">Back up now</string>
<string name="backup_back_up_retry">Back up / Retry</string>
<string name="backup_backup">Backup</string>
<string name="backup_backup_folder">Backup folder</string>
<string name="backup_backup_queued_opens_when_connected">Backup queued. Opens when connected.</string>
<string name="backup_backups_paused_automatic_backup_is_off">Backups paused. Automatic backup is off.</string>
<string name="backup_cancel_download">Cancel download</string>
<string name="backup_clear_playback_cache">Clear playback cache</string>
<string name="backup_copies_stay_on_the_server_when_you_delete_local_recordings">Copies stay on the server when you delete local recordings.</string>
<string name="backup_could_not_export_key">Could not export key</string>
<string name="backup_could_not_play_audio">Could not play audio</string>
<string name="backup_download_play">Download &amp; play</string>
<string name="backup_keep_your_moments">Keep your moments.</string>
<string name="backup_one_transfer_at_a_time_interrupted_uploads_resume_and_are">One transfer at a time. Interrupted uploads resume and are verified before completion. Local files are retained. SSH protects transfers; server files are not encrypted at rest.</string>
<string name="backup_open_source_licenses">Open-source licenses</string>
<string name="backup_pause_all_backups">Pause all backups</string>
<string name="backup_playback_cache_cleared">Playback cache cleared</string>
<string name="backup_port">Port</string>
<string name="backup_public_key_copied">Public key copied</string>
<string name="backup_public_key_exported">Public key exported</string>
<string name="backup_ready_to_download">Ready to download</string>
<string name="backup_refresh">Refresh</string>
<string name="backup_runs_when_conditions_allow_the_watch_may_delay_background">Runs when conditions allow. The watch may delay background work to save battery. Unmetered does not guarantee Wi-Fi.</string>
<string name="backup_save_a_recording_to_begin">Save a recording to begin.</string>
<string name="backup_save_server">Save server</string>
<string name="backup_server">Server</string>
<string name="backup_server_playback">Server playback</string>
<string name="backup_server_recordings">Server recordings</string>
<string name="backup_tap_refresh_to_browse_your_backups">Tap Refresh to browse your backups.</string>
<string name="backup_test_connection">Test connection</string>
<string name="backup_transfers">Transfers</string>
<string name="backup_username">Username</string>
<string name="backup_wait_for_the_current_action_or_cancel_it">Wait for the current action, or cancel it</string>
<string name="backup_replace_ed25519">Replace with Ed25519</string>
<string name="backup_replace_key_message">This pauses backups and replaces the watch key. Add the new public key to your server before starting backups again.</string>
<string name="backup_replace_key_confirm">Replace key</string>
<string name="backup_connect_trust">Connect &amp; trust</string>
<string name="backup_reading_server_identity">Reading server identity…</string>
<string name="backup_server_untrusted">Trust this server to connect</string>
<string name="backup_server_trusted">Server trusted</string>
<string name="backup_server_details_changed">Server details changed. Connect again.</string>
<string name="backup_server_key_changed">Server identity changed. Connection blocked. Check with your administrator before forgetting its old identity.</string>
<string name="backup_trust_server_title">Trust this server?</string>
<string name="backup_trust_server_confirm">Trust server</string>
<string name="backup_server_trusted_create_key">Server trusted. Create and authorize the watch key, then test the connection.</string>
<string name="backup_server_identity">Server identity</string>
<string name="backup_forget_trust">Forget trust</string>
<string name="backup_forget_trust_message">This pauses backups and removes the remembered server identity. Only approve a replacement identity after checking a legitimate server change.</string>
<string name="backup_trust_forgotten">Trust forgotten. Use Connect &amp; trust on the Server page.</string>
<string name="backup_trust_server_address">%1$s:%2$d</string>
<string name="backup_remember_server">Remember this server.</string>
<string name="backup_view_fingerprint">View fingerprint</string>
</resources>
@@ -0,0 +1,35 @@
package meghdad.remember
import org.junit.Assert.*
import org.junit.Test
class BackupServerTest {
private fun server() = BackupServer("example.test", 22, "backup", "/remember", "SHA256:" + "A".repeat(43))
@Test fun rejectsUnsafeOrIncompleteServerDetails() {
val invalid = listOf(server().copy(host = "ssh://example.test"), server().copy(port = 0),
server().copy(user = ""), server().copy(folder = "/"), server().copy(folder = "/remember/../other"),
server().copy(folder = "/remember/*"), server().copy(fingerprint = ""))
invalid.forEach { candidate ->
assertThrows(IllegalArgumentException::class.java) { candidate.validate() }
}
server().validate()
}
@Test fun backupReceiptsAreScopedToTheDestinationAndHostKey() {
val original = server()
assertNotEquals(original.identity, original.copy(folder = "/other").identity)
assertNotEquals(original.identity, original.copy(user = "other").identity)
assertNotEquals(original.identity, original.copy(fingerprint = "SHA256:" + "B".repeat(43)).identity)
assertEquals(original.identity, original.copy().identity)
}
@Test fun savedConfigurationCanBeUntrustedButTransfersRequireApproval() {
val pending = server().copy(fingerprint = "")
pending.validateConfiguration()
assertThrows(IllegalArgumentException::class.java) { pending.validate() }
}
@Test fun changingTheEndpointClearsTrustButChangingTheAccountDoesNot() {
val trusted = server()
assertEquals("", trusted.copy(host = "other.test").withRememberedTrust(trusted).fingerprint)
assertEquals("", trusted.copy(port = 2222).withRememberedTrust(trusted).fingerprint)
assertEquals(trusted.fingerprint, trusted.copy(user = "other", folder = "/other").withRememberedTrust(trusted).fingerprint)
}
}
@@ -0,0 +1,26 @@
package meghdad.remember
import com.jcraft.jsch.KeyPair
import org.junit.Assert.*
import org.junit.Test
import java.io.ByteArrayOutputStream
class SshCryptoTest {
@Test fun ed25519OpenSshIdentityReloadsAndSignsWithTheAndroidCompatibleBackend() {
val client = SshCrypto.client()
val pair = KeyPair.genKeyPair(client, KeyPair.ED25519)
val bytes = ByteArrayOutputStream().also { pair.writeOpenSSHv1PrivateKey(it, null as ByteArray?) }.toByteArray()
try {
assertTrue(bytes.toString(Charsets.UTF_8).startsWith("-----BEGIN OPENSSH PRIVATE KEY-----"))
val restored = KeyPair.load(client, bytes, null)
try {
assertEquals(KeyPair.ED25519, restored.keyType)
assertArrayEquals(pair.publicKeyBlob, restored.publicKeyBlob)
val message = "backup authentication".toByteArray()
val verifier = pair.verifier
verifier.update(message)
assertTrue(verifier.verify(restored.getSignature(message)))
} finally { restored.dispose() }
} finally { bytes.fill(0); pair.dispose() }
}
}
@@ -0,0 +1,22 @@
package meghdad.remember
import com.jcraft.jsch.HostKeyRepository
import org.junit.Assert.*
import org.junit.Test
class SshHostTrustTest {
@Test fun discoveryReportsTheFingerprintButNeverApprovesTheKey() {
val key = byteArrayOf(1, 2, 3)
var observed: String? = null
val repository = SshHostTrust.repository(null) { observed = it }
assertEquals(HostKeyRepository.NOT_INCLUDED, repository.check("server.test", key))
assertEquals(SshHostTrust.fingerprint(key), observed)
assertEquals(HostKeyRepository.NOT_INCLUDED, repository.check("server.test", key))
}
@Test fun authenticationAcceptsOnlyThePreviouslyApprovedKey() {
val original = byteArrayOf(1, 2, 3)
val repository = SshHostTrust.repository(SshHostTrust.fingerprint(original))
assertEquals(HostKeyRepository.OK, repository.check("server.test", original))
assertEquals(HostKeyRepository.CHANGED, repository.check("server.test", byteArrayOf(4, 5, 6)))
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

+70
View File
@@ -0,0 +1,70 @@
# SFTP backup setup
Remember needs an existing SSH server with SFTP enabled. No database or custom application server is required. Use a dedicated backup account and folder. The implementation streams one file at a time, but actual memory and CPU consumption must be measured on your server before relying on its 128 MB budget.
## Server preparation
1. Create a dedicated account using your operating system's normal account tools. Give it read/write access to a folder reserved for Remember. Avoid using an administrator or root account.
2. Ensure that the SSH server supports SFTP and Ed25519 public-key authentication. New watch identities use Ed25519. Existing RSA watch keys are preserved; use **Replace with Ed25519** on the Server page to migrate, then authorize the new public key and re-enable backups. This operation pauses backups. RSA, ECDSA, and Ed25519 server host keys are supported; ECDSA/RSA remain preferred when a server offers multiple host-key types, preserving existing fingerprint pins.
3. The watch can fetch the fingerprint automatically with **Connect & trust**; no fingerprint typing is required. First-time approval trusts the server reached on that connection. For stronger assurance, open **View fingerprint** on the approval screen and compare it with one obtained through a trusted administrative connection before approving. For example, on an OpenSSH server offering an ECDSA host key:
```sh
ssh-keygen -lf /etc/ssh/ssh_host_ecdsa_key.pub -E sha256
```
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 **Backup → Advanced → Server identity → Forget trust** and approve the new identity. Forgetting trust pauses backups and turns automatic backup off.
4. In Remember, open **Settings → Backup → 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.
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
Match User remember-backup
ForceCommand internal-sftp
AllowTcpForwarding no
X11Forwarding no
PermitTTY no
```
This block restricts session capabilities; it does not itself confine filesystem access. Use filesystem permissions or a properly configured chroot for confinement. A chroot has additional root-ownership requirements and changes the absolute folder path visible to the app. Validate SSH configuration before reloading it and keep an administrative session available.
## Watch setup
Enter the address without `ssh://`, SSH port, account name, and an **existing absolute folder path** as seen by that SFTP account. Remember does not create the root backup folder. Choose **Connect & trust**, review the server identity, and tap **Trust server**. The app saves the fingerprint automatically. Cancel leaves the server untrusted; discovery sends no watch credentials. If a previously trusted server presents a different key, it is blocked. **Save server** can store an untrusted draft, but uploads remain disabled until approval. The watch public key must be authorized before **Test connection** can succeed.
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.
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
Each recording uses its stable ID for `<id>.m4a` and `<id>.json`. The JSON manifest includes a schema version, title, creation time, duration, bookmark timestamps, audio byte count, and SHA-256. Audio is uploaded to `<id>.m4a.upload`, resumed after interruptions, and read back for verification. Metadata is published last as the completion marker. Failed verification removes the app's incomplete audio upload so a retry can start cleanly. No remote shell or checksum command is used.
Verification requires downloading the uploaded audio once, so account for both directions when budgeting bandwidth. SSH compression is disabled for the already-compressed audio. Backups never erase local recordings. Local deletion leaves server copies intact. Successful local receipts do not detect a later manual deletion on the server; remote browsing reflects the current folder contents.
Server recordings downloads a selected file into a single temporary playback cache and verifies its checksum before playback. At least the full recording size plus 16 MB free space is required. The browser loads up to 1,000 manifests per folder. Files created by other applications or unsupported/corrupt manifests are ignored.
SSH protects transfers but does not encrypt the audio and metadata stored on the server. Restore into the local library, client-side backup encryption, remote deletion, bandwidth limits, and exact-clock-time scheduling are future work.
## Testing
Never point integration tests at personal backup storage. The network tests are opt-in and require a disposable loopback SFTP fixture offering the account `backup-test`, folder `/remember`, and a known RSA/ECDSA/Ed25519 host fingerprint. A loopback-only fixture is included in `tools/sftp_fixture.py`. It creates a fresh temporary folder, accepts only the test account with an Ed25519 identity, and deletes its server files when stopped. Prepare it in a temporary Python environment (Python 3.9+):
```sh
python3 -m venv /tmp/remember-sftp-env
/tmp/remember-sftp-env/bin/pip install paramiko==5.0.0
/tmp/remember-sftp-env/bin/python tools/sftp_fixture.py --state-file /tmp/remember-sftp-state.json
```
The state JSON contains the fixture fingerprint and authentication-attempt count. Discovery-only testing should leave the count at zero. With the fixture listening on host port 2222, connect only the intended disposable emulator:
```sh
adb -s TEST_SERIAL reverse tcp:2222 tcp:2222
adb -s TEST_SERIAL install -r app/build/outputs/apk/debug/app-debug.apk
adb -s TEST_SERIAL install -r app/build/outputs/apk/androidTest/debug/app-debug-androidTest.apk
adb -s TEST_SERIAL shell am instrument -w \
-e class meghdad.remember.BackupTest \
-e sftpPort 2222 \
-e sftpFingerprint SHA256:FIXTURE_FINGERPRINT \
meghdad.remember.test/androidx.test.runner.AndroidJUnitRunner
```
The `connectAndTrustRequiresApprovalAndBlocksChangedIdentity` test exercises Cancel, explicit approval, and changed-key rejection. Add `-e saveTrustScreenshot true` to save a test approval-screen screenshot in the target app's cache. Without the fingerprint argument, network tests are skipped; UI, metadata, and key-storage tests still run. The manual-job test requires the disposable emulator to have a network connection. These tests create server files and local fixtures, change server settings, and cancel backup jobs. The server fixture should be discarded after the run.
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 49 KiB

After

Width:  |  Height:  |  Size: 47 KiB

+4
View File
@@ -3,8 +3,12 @@ agp = "9.2.1"
junit = "4.13.2"
junitVersion = "1.3.0"
espressoCore = "3.7.0"
jsch = "2.28.8"
bcprov = "1.86"
[libraries]
jsch = { group = "com.github.mwiede", name = "jsch", version.ref = "jsch" }
bcprov = { group = "org.bouncycastle", name = "bcprov-jdk18on", version.ref = "bcprov" }
junit = { group = "junit", name = "junit", version.ref = "junit" }
androidx-junit = { group = "androidx.test.ext", name = "junit", version.ref = "junitVersion" }
androidx-espresso-core = { group = "androidx.test.espresso", name = "espresso-core", version.ref = "espressoCore" }
+15
View File
@@ -0,0 +1,15 @@
MIT License (https://opensource.org/licenses/MIT)
Copyright (c) 2000-2026 The Legion of the Bouncy Castle Inc. (https://www.bouncycastle.org).
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sub license, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: The above copyright notice and this
permission notice shall be included in all copies or substantial portions of the Software.
**THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.**
+30
View File
@@ -0,0 +1,30 @@
JSch 0.0.* was released under the GNU LGPL license. Later, we have switched
over to a BSD-style license.
------------------------------------------------------------------------------
Copyright (c) 2002-2015 Atsuhiko Yamanaka, JCraft,Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+166
View File
@@ -0,0 +1,166 @@
"""Disposable, loopback-only SFTP fixture for Android backup integration tests.
Requires Paramiko. Accepts any valid Ed25519 identity for backup-test, offers
an Ed25519 host key, and exposes only a freshly created temporary directory.
Never use this fixture as a production server.
"""
import argparse
import base64
import hashlib
import io
import json
import os
from pathlib import Path
import signal
import socket
import tempfile
import threading
import paramiko
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from cryptography.hazmat.primitives.serialization import Encoding, NoEncryption, PrivateFormat
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--port", type=int, default=2222)
parser.add_argument("--state-file", type=Path, required=True)
args = parser.parse_args()
stop = threading.Event()
for sig in (signal.SIGINT, signal.SIGTERM):
signal.signal(sig, lambda *_: stop.set())
private = Ed25519PrivateKey.generate().private_bytes(Encoding.PEM, PrivateFormat.OpenSSH, NoEncryption())
host_key = paramiko.Ed25519Key(file_obj=io.StringIO(private.decode()))
fingerprint = "SHA256:" + base64.b64encode(hashlib.sha256(host_key.asbytes()).digest()).decode().rstrip("=")
state = {"fingerprint": fingerprint, "port": args.port, "auth_attempts": 0}
state_lock = threading.Lock()
def write_state():
temporary = args.state_file.with_name(args.state_file.name + ".tmp")
temporary.write_text(json.dumps(state))
temporary.replace(args.state_file)
def record_auth():
with state_lock:
state["auth_attempts"] += 1
write_state()
class Server(paramiko.ServerInterface):
def check_auth_none(self, username):
record_auth()
return paramiko.AUTH_FAILED
def check_auth_publickey(self, username, key):
record_auth()
return paramiko.AUTH_SUCCESSFUL if username == "backup-test" and key.get_name() == "ssh-ed25519" else paramiko.AUTH_FAILED
def get_allowed_auths(self, username):
return "publickey"
def check_channel_request(self, kind, chanid):
return paramiko.OPEN_SUCCEEDED if kind == "session" else paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED
with tempfile.TemporaryDirectory(prefix="remember-sftp-fixture-") as directory:
root = Path(directory).resolve()
(root / "remember").mkdir()
class SFTP(paramiko.SFTPServerInterface):
def local(self, path):
result = (root / path.lstrip("/")).resolve()
if not result.is_relative_to(root):
raise PermissionError("Outside fixture root")
return result
def canonicalize(self, path):
return "/" + str(self.local(path).relative_to(root))
def stat(self, path):
try:
return paramiko.SFTPAttributes.from_stat(self.local(path).stat())
except OSError as error:
return paramiko.SFTPServer.convert_errno(error.errno)
lstat = stat
def list_folder(self, path):
try:
result = []
for file in self.local(path).iterdir():
item = paramiko.SFTPAttributes.from_stat(file.stat())
item.filename = file.name
result.append(item)
return result
except OSError as error:
return paramiko.SFTPServer.convert_errno(error.errno)
def open(self, path, flags, attr):
try:
fd = os.open(self.local(path), flags, 0o600)
mode = "r+b" if flags & os.O_RDWR else ("wb" if flags & os.O_WRONLY else "rb")
file = os.fdopen(fd, mode)
handle = paramiko.SFTPHandle(flags)
if not flags & os.O_WRONLY:
handle.readfile = file
if flags & (os.O_WRONLY | os.O_RDWR):
handle.writefile = file
return handle
except OSError as error:
return paramiko.SFTPServer.convert_errno(error.errno)
def remove(self, path):
try:
self.local(path).unlink()
return paramiko.SFTP_OK
except OSError as error:
return paramiko.SFTPServer.convert_errno(error.errno)
def rename(self, old, new):
try:
self.local(old).rename(self.local(new))
return paramiko.SFTP_OK
except OSError as error:
return paramiko.SFTPServer.convert_errno(error.errno)
transports = []
threads = []
def serve(connection):
transport = paramiko.Transport(connection)
transports.append(transport)
transport.add_server_key(host_key)
transport.set_subsystem_handler("sftp", paramiko.SFTPServer, SFTP)
try:
transport.start_server(server=Server())
while transport.is_active() and not stop.wait(0.1):
pass
except (EOFError, OSError, paramiko.SSHException):
pass
finally:
transport.close()
with socket.socket() as listener:
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listener.bind(("127.0.0.1", args.port))
listener.listen(5)
listener.settimeout(0.5)
write_state()
print("Loopback-only disposable SFTP fixture ready", flush=True)
try:
while not stop.is_set():
try:
connection, _ = listener.accept()
except socket.timeout:
continue
thread = threading.Thread(target=serve, args=(connection,), daemon=True)
threads.append(thread)
thread.start()
finally:
for transport in transports:
transport.close()
for thread in threads:
thread.join(timeout=2)
if __name__ == "__main__":
main()