Archived
The Android app: a Compose shell over the tested client
Sign in, register with a recovery code shown once, browse, switch area,
upload, download through a share sheet, and create password-protected
links. All of it sits on :client, which is already exercised end to end
by filesctl against both a self-hosted stack and files.flamenet.io.
The area banner is always on screen rather than tucked into a menu. Which
area you are working in decides where a new file lands and who can ever
read it, and finding that out afterwards is too late.
Rows this session cannot decrypt are shown, and say so. Hiding them would
be a lie about what the server knows.
⚠️ Not compiled. The Android SDK is not installed on the development
machine, so this module has never been through a build — noted in the
README rather than left for someone to discover.
This commit is contained in:
@@ -70,3 +70,18 @@ The engine and the wire layer are complete and verified, including against the
|
||||
iOS engine: one uploads, the other downloads, and the bytes match.
|
||||
|
||||
The Jetpack Compose app is in progress.
|
||||
|
||||
## Building the app
|
||||
|
||||
`app/` is a Jetpack Compose module and needs the Android SDK. The engine and
|
||||
client do not:
|
||||
|
||||
```bash
|
||||
gradle :engine:test :client:build # no SDK required
|
||||
gradle :app:assembleDebug # SDK required
|
||||
```
|
||||
|
||||
⚠️ **The SDK is not installed on the development machine yet**, so `app/` has
|
||||
not been compiled. Everything below it has: the engine and the wire layer are
|
||||
tested, and `filesctl` runs full round trips against both a self-hosted stack
|
||||
and `files.flamenet.io`. What is unverified is the Compose layer on top.
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
// The Android app shell. Everything below it — the cryptography and the wire
|
||||
// layer — lives in :engine and :client, which are plain JVM libraries so they
|
||||
// can be tested without any of this.
|
||||
plugins {
|
||||
id("com.android.application") version "8.7.3"
|
||||
kotlin("android") version "2.4.10"
|
||||
id("org.jetbrains.kotlin.plugin.compose") version "2.4.10"
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "io.flamenet.files"
|
||||
compileSdk = 35
|
||||
|
||||
defaultConfig {
|
||||
applicationId = "io.flamenet.files"
|
||||
minSdk = 26 // X25519 through JCA needs API 26.
|
||||
targetSdk = 35
|
||||
versionCode = 1
|
||||
versionName = "0.1"
|
||||
}
|
||||
|
||||
buildFeatures { compose = true }
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
}
|
||||
kotlin { compilerOptions { jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17) } }
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
isMinifyEnabled = true
|
||||
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(project(":engine"))
|
||||
implementation(project(":client"))
|
||||
implementation(platform("androidx.compose:compose-bom:2024.12.01"))
|
||||
implementation("androidx.compose.material3:material3")
|
||||
implementation("androidx.compose.ui:ui")
|
||||
implementation("androidx.compose.material:material-icons-extended")
|
||||
implementation("androidx.activity:activity-compose:1.9.3")
|
||||
implementation("androidx.core:core-ktx:1.15.0")
|
||||
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.8.7")
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.9.0")
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
|
||||
<application
|
||||
android:allowBackup="false"
|
||||
android:label="@string/app_name"
|
||||
android:supportsRtl="true"
|
||||
android:theme="@style/Theme.FlamenetFiles">
|
||||
|
||||
<!--
|
||||
allowBackup is off deliberately. There is nothing here worth backing
|
||||
up — no keys are persisted — and a backup of an app like this is a
|
||||
copy of state the user believes is only in memory.
|
||||
-->
|
||||
|
||||
<activity
|
||||
android:name=".app.MainActivity"
|
||||
android:exported="true"
|
||||
android:windowSoftInputMode="adjustResize">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
<!--
|
||||
Handing a decrypted file to another app needs a content URI; a
|
||||
file:// URI has been illegal since API 24. Scoped to the cache
|
||||
directory, and granted per-share rather than standing.
|
||||
-->
|
||||
<provider
|
||||
android:name="androidx.core.content.FileProvider"
|
||||
android:authorities="${applicationId}.files"
|
||||
android:exported="false"
|
||||
android:grantUriPermissions="true">
|
||||
<meta-data
|
||||
android:name="android.support.FILE_PROVIDER_PATHS"
|
||||
android:resource="@xml/file_paths" />
|
||||
</provider>
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -0,0 +1,319 @@
|
||||
package io.flamenet.files.app
|
||||
|
||||
import android.content.Intent
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.ArrowBack
|
||||
import androidx.compose.material.icons.filled.Description
|
||||
import androidx.compose.material.icons.filled.Folder
|
||||
import androidx.compose.material.icons.filled.MoreVert
|
||||
import androidx.compose.material.icons.filled.Shield
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalClipboardManager
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontStyle
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.content.FileProvider
|
||||
import io.flamenet.files.client.FilesSession
|
||||
import kotlinx.coroutines.launch
|
||||
import java.io.File
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun Browse(model: FilesViewModel, state: UiState) {
|
||||
val scope = rememberCoroutineScope()
|
||||
val context = LocalContext.current
|
||||
var showingMenu by remember { mutableStateOf(false) }
|
||||
var showingAreas by remember { mutableStateOf(false) }
|
||||
var newFolder by remember { mutableStateOf(false) }
|
||||
var folderName by remember { mutableStateOf("") }
|
||||
var sharing by remember { mutableStateOf<FilesSession.Entry?>(null) }
|
||||
|
||||
val picker = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.OpenDocument(),
|
||||
) { uri ->
|
||||
uri ?: return@rememberLauncherForActivityResult
|
||||
scope.launch {
|
||||
val name = uri.lastPathSegment?.substringAfterLast('/') ?: "file"
|
||||
val bytes = context.contentResolver.openInputStream(uri)?.use { it.readBytes() }
|
||||
if (bytes == null) return@launch
|
||||
model.upload(bytes, name)
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(Unit) { model.refresh() }
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text(state.path.lastOrNull()?.second ?: "All files") },
|
||||
navigationIcon = {
|
||||
if (state.path.isNotEmpty()) {
|
||||
IconButton(onClick = model::goBack) {
|
||||
Icon(Icons.Default.ArrowBack, contentDescription = "Back")
|
||||
}
|
||||
} else {
|
||||
IconButton(onClick = { showingAreas = true }) {
|
||||
Icon(Icons.Default.Shield, contentDescription = "Area")
|
||||
}
|
||||
// Only labels the clearance permits are offered, so
|
||||
// nobody discovers the limit by being refused.
|
||||
DropdownMenu(showingAreas, onDismissRequest = { showingAreas = false }) {
|
||||
model.selectableLabels().forEach { label ->
|
||||
DropdownMenuItem(
|
||||
text = {
|
||||
Text(
|
||||
model.nameFor(label) +
|
||||
if (label == state.label) " ✓" else "",
|
||||
)
|
||||
},
|
||||
onClick = { showingAreas = false; model.use(label) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
actions = {
|
||||
IconButton(onClick = { showingMenu = true }) {
|
||||
Icon(Icons.Default.MoreVert, contentDescription = "More")
|
||||
}
|
||||
DropdownMenu(showingMenu, onDismissRequest = { showingMenu = false }) {
|
||||
DropdownMenuItem(
|
||||
text = { Text("Upload a file") },
|
||||
onClick = { showingMenu = false; picker.launch(arrayOf("*/*")) },
|
||||
)
|
||||
DropdownMenuItem(
|
||||
text = { Text("New folder") },
|
||||
onClick = { showingMenu = false; newFolder = true },
|
||||
)
|
||||
HorizontalDivider()
|
||||
DropdownMenuItem(
|
||||
text = { Text("Sign out") },
|
||||
onClick = { showingMenu = false; model.signOut() },
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
Column(Modifier.padding(padding)) {
|
||||
// Always visible, never a hidden mode. Which area you are working
|
||||
// in decides where a new file lands and who can ever read it, and
|
||||
// finding that out afterwards is too late.
|
||||
state.label?.let {
|
||||
Surface(tonalElevation = 2.dp, modifier = Modifier.fillMaxWidth()) {
|
||||
Text(
|
||||
"Working at ${model.nameFor(it)}. New files are filed here.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (state.entries.isEmpty()) {
|
||||
Column(
|
||||
Modifier.fillMaxSize().padding(40.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Center,
|
||||
) {
|
||||
Text("Nothing here yet", style = MaterialTheme.typography.titleMedium)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(
|
||||
"Files you add are encrypted on this device before they leave it.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
LazyColumn {
|
||||
items(state.entries, key = { it.id }) { entry ->
|
||||
Row(entry, model, onShare = { sharing = entry })
|
||||
HorizontalDivider()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (newFolder) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { newFolder = false; folderName = "" },
|
||||
title = { Text("New folder") },
|
||||
text = {
|
||||
OutlinedTextField(
|
||||
value = folderName,
|
||||
onValueChange = { folderName = it },
|
||||
singleLine = true,
|
||||
label = { Text("Name") },
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
model.createFolder(folderName)
|
||||
folderName = ""
|
||||
newFolder = false
|
||||
}) { Text("Create") }
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { newFolder = false; folderName = "" }) { Text("Cancel") }
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
sharing?.let { entry ->
|
||||
ShareDialog(entry, model) { sharing = null }
|
||||
}
|
||||
}
|
||||
|
||||
/** One row. A file this session cannot decrypt still appears, and says so. */
|
||||
@Composable
|
||||
private fun Row(entry: FilesSession.Entry, model: FilesViewModel, onShare: () -> Unit) {
|
||||
val scope = rememberCoroutineScope()
|
||||
val context = LocalContext.current
|
||||
|
||||
ListItem(
|
||||
leadingContent = {
|
||||
Icon(
|
||||
if (entry.isFolder) Icons.Default.Folder else Icons.Default.Description,
|
||||
contentDescription = null,
|
||||
)
|
||||
},
|
||||
headlineContent = {
|
||||
if (entry.name != null) {
|
||||
Text(entry.name!!)
|
||||
} else {
|
||||
// Visible to the database, unreadable here. Saying so is more
|
||||
// honest than hiding the row — and hiding it would be a lie
|
||||
// about what the server knows.
|
||||
Text("Encrypted for another key", fontStyle = FontStyle.Italic)
|
||||
}
|
||||
},
|
||||
supportingContent = { Text(model.nameFor(entry.label)) },
|
||||
trailingContent = {
|
||||
if (!entry.isFolder && entry.name != null) {
|
||||
TextButton(onClick = onShare) { Text("Link") }
|
||||
}
|
||||
},
|
||||
modifier = Modifier.clickable {
|
||||
if (entry.isFolder) {
|
||||
model.open(entry)
|
||||
} else if (entry.name != null) {
|
||||
scope.launch {
|
||||
val bytes = model.download(entry) ?: return@launch
|
||||
// Plaintext on disk for as long as this file exists, which
|
||||
// is why it goes to the cache directory and is handed
|
||||
// straight to a share sheet rather than left lying around.
|
||||
val file = File(context.cacheDir, entry.name!!)
|
||||
file.writeBytes(bytes)
|
||||
val uri = FileProvider.getUriForFile(
|
||||
context, "${context.packageName}.files", file,
|
||||
)
|
||||
context.startActivity(
|
||||
Intent.createChooser(
|
||||
Intent(Intent.ACTION_SEND).apply {
|
||||
type = "*/*"
|
||||
putExtra(Intent.EXTRA_STREAM, uri)
|
||||
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
},
|
||||
entry.name,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Making a link.
|
||||
*
|
||||
* The copy matters more than the controls. A share link here is not what people
|
||||
* expect a share link to be: it is useless to anyone not cleared for the file's
|
||||
* area, which is a feature and a surprise.
|
||||
*/
|
||||
@Composable
|
||||
private fun ShareDialog(entry: FilesSession.Entry, model: FilesViewModel, onDismiss: () -> Unit) {
|
||||
val scope = rememberCoroutineScope()
|
||||
val clipboard = LocalClipboardManager.current
|
||||
var usePassword by remember { mutableStateOf(false) }
|
||||
var password by remember { mutableStateOf("") }
|
||||
var link by remember { mutableStateOf<String?>(null) }
|
||||
var busy by remember { mutableStateOf(false) }
|
||||
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(entry.name ?: "Share") },
|
||||
text = {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
val current = link
|
||||
if (current != null) {
|
||||
Text(current, fontFamily = FontFamily.Monospace,
|
||||
style = MaterialTheme.typography.bodySmall)
|
||||
Text(
|
||||
"The part after # never leaves the recipient's browser, so the server storing this link cannot open it.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
} else {
|
||||
androidx.compose.foundation.layout.Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Checkbox(usePassword, onCheckedChange = { usePassword = it })
|
||||
Text("Require a password")
|
||||
}
|
||||
if (usePassword) {
|
||||
OutlinedTextField(
|
||||
value = password,
|
||||
onValueChange = { password = it },
|
||||
label = { Text("Password") },
|
||||
singleLine = true,
|
||||
visualTransformation = PasswordVisualTransformation(),
|
||||
)
|
||||
}
|
||||
Text(
|
||||
if (usePassword) {
|
||||
"Send it separately from the link — a password in the same message is not a second factor. It is never sent to the server, so nobody can test a guess against it."
|
||||
} else {
|
||||
"Anyone cleared for this area who has the link can open the file."
|
||||
},
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
Text(
|
||||
"This link only works for people cleared for ${model.nameFor(entry.label)}. Forwarding it to anyone else gives them nothing.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
val current = link
|
||||
if (current != null) {
|
||||
TextButton(onClick = { clipboard.setText(AnnotatedString(current)) }) {
|
||||
Text("Copy link")
|
||||
}
|
||||
} else {
|
||||
TextButton(
|
||||
enabled = !busy && (!usePassword || password.isNotEmpty()),
|
||||
onClick = {
|
||||
busy = true
|
||||
scope.launch {
|
||||
link = model.createShare(entry, if (usePassword) password else null)
|
||||
busy = false
|
||||
}
|
||||
},
|
||||
) { Text(if (busy) "Working…" else "Create link") }
|
||||
}
|
||||
},
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text("Done") } },
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
package io.flamenet.files.app
|
||||
|
||||
import android.content.Context
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import io.flamenet.files.client.AccountsClient
|
||||
import io.flamenet.files.client.ClientException
|
||||
import io.flamenet.files.client.Clearance
|
||||
import io.flamenet.files.client.FilesApi
|
||||
import io.flamenet.files.client.FilesSession
|
||||
import io.flamenet.files.client.Http
|
||||
import io.flamenet.files.client.Wire
|
||||
import io.flamenet.files.client.clearanceFrom
|
||||
import io.flamenet.files.engine.Identity
|
||||
import io.flamenet.files.engine.Label
|
||||
import io.flamenet.files.engine.Recovery
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
enum class SignInMode(val label: String) {
|
||||
SIGN_IN("Unlock"),
|
||||
REGISTER("Create account"),
|
||||
RECOVER("Recover"),
|
||||
}
|
||||
|
||||
sealed interface Phase {
|
||||
data object SignedOut : Phase
|
||||
data class Working(val what: String) : Phase
|
||||
data class RecoveryCode(val code: String) : Phase
|
||||
data object Browsing : Phase
|
||||
}
|
||||
|
||||
data class UiState(
|
||||
val phase: Phase = Phase.SignedOut,
|
||||
val server: String = "https://files.flamenet.io",
|
||||
val handle: String = "",
|
||||
val error: String? = null,
|
||||
val config: Wire.ServerConfig? = null,
|
||||
val vocabulary: Wire.Vocabulary = Wire.Vocabulary(),
|
||||
val clearance: Clearance? = null,
|
||||
val label: Label? = null,
|
||||
val path: List<Pair<String, String>> = emptyList(),
|
||||
val entries: List<FilesSession.Entry> = emptyList(),
|
||||
)
|
||||
|
||||
/**
|
||||
* Everything the interface needs, in one place.
|
||||
*
|
||||
* Deliberately holds no persistence beyond the server address and the handle.
|
||||
* The session keeps the identity key and the label keys in memory; closing the
|
||||
* app forgets them and the next launch asks for the passphrase again. That is
|
||||
* the intended behaviour, not an omission — a key cached on disk is a key an
|
||||
* unlocked phone hands to whoever is holding it.
|
||||
*/
|
||||
class FilesViewModel(context: Context) : ViewModel() {
|
||||
private val prefs = context.getSharedPreferences("flamenet-files", Context.MODE_PRIVATE)
|
||||
|
||||
private val _state = MutableStateFlow(
|
||||
UiState(
|
||||
server = prefs.getString("server", "https://files.flamenet.io")!!,
|
||||
handle = prefs.getString("handle", "")!!,
|
||||
),
|
||||
)
|
||||
val state: StateFlow<UiState> = _state.asStateFlow()
|
||||
|
||||
private var session: FilesSession? = null
|
||||
|
||||
val folderID: String? get() = _state.value.path.lastOrNull()?.first
|
||||
|
||||
fun setServer(value: String) {
|
||||
prefs.edit().putString("server", value).apply()
|
||||
_state.update { it.copy(server = value) }
|
||||
}
|
||||
|
||||
fun setHandle(value: String) {
|
||||
prefs.edit().putString("handle", value).apply()
|
||||
_state.update { it.copy(handle = value) }
|
||||
}
|
||||
|
||||
fun dismissError() = _state.update { it.copy(error = null) }
|
||||
|
||||
fun nameFor(label: Label): String = _state.value.vocabulary.name(label)
|
||||
|
||||
/**
|
||||
* Every label this clearance permits, as the picker offers them.
|
||||
*
|
||||
* Built from the vocabulary rather than from the whole lattice: 2^64
|
||||
* compartment combinations is not a menu, and only named areas are ones
|
||||
* anybody can reason about.
|
||||
*/
|
||||
fun selectableLabels(): List<Label> {
|
||||
val clearance = _state.value.clearance ?: return emptyList()
|
||||
val vocabulary = _state.value.vocabulary
|
||||
val bits = vocabulary.compartments.map { it.bit }.sorted()
|
||||
return vocabulary.levels.map { it.ordinal }.sorted().flatMap { level ->
|
||||
(listOf(emptyList<Int>()) + bits.map { listOf(it) }).map { subset ->
|
||||
Label(level, subset.toSet())
|
||||
}
|
||||
}.filter(clearance::permits)
|
||||
}
|
||||
|
||||
fun probe() = launchIO {
|
||||
try {
|
||||
val config = FilesApi.config(_state.value.server)
|
||||
_state.update { it.copy(config = config) }
|
||||
} catch (error: Exception) {
|
||||
_state.update { it.copy(error = error.message) }
|
||||
}
|
||||
}
|
||||
|
||||
fun signIn(passphrase: String, mode: SignInMode, recoveryCode: String = "") = launchIO {
|
||||
_state.update {
|
||||
it.copy(
|
||||
phase = Phase.Working(
|
||||
if (mode == SignInMode.REGISTER) "Creating your account…" else "Deriving keys…",
|
||||
),
|
||||
error = null,
|
||||
)
|
||||
}
|
||||
try {
|
||||
val server = _state.value.server
|
||||
val handle = _state.value.handle
|
||||
val config = FilesApi.config(server)
|
||||
val accounts = AccountsClient(config.accountsURL)
|
||||
|
||||
var freshCode: String? = null
|
||||
var enrolledKey: java.security.PrivateKey? = null
|
||||
|
||||
when (mode) {
|
||||
SignInMode.REGISTER -> {
|
||||
// Built before the account exists so both land in one
|
||||
// transaction. Registering first and enrolling after left a
|
||||
// window where a backgrounded app stranded a handle that
|
||||
// was taken, unusable, and impossible to enrol into.
|
||||
val generated = Recovery.generate()
|
||||
val pair = Identity.generate()
|
||||
accounts.register(
|
||||
handle, passphrase, generated.entropy,
|
||||
Wire.NewIdentity(
|
||||
publicKey = Http.b64(Identity.exportPublicKey(pair.public)),
|
||||
protectedRecord = FilesSession.encodeRecord(
|
||||
Identity.protect(pair.private, passphrase),
|
||||
),
|
||||
recoveryRecord = FilesSession.encodeRecord(
|
||||
Identity.protectWithRecovery(pair.private, generated.entropy),
|
||||
),
|
||||
),
|
||||
)
|
||||
freshCode = generated.code
|
||||
enrolledKey = pair.private
|
||||
}
|
||||
SignInMode.RECOVER -> {
|
||||
accounts.rotate(
|
||||
handle, Recovery.decode(recoveryCode),
|
||||
passphrase, Recovery.generate().entropy,
|
||||
)
|
||||
}
|
||||
SignInMode.SIGN_IN -> Unit
|
||||
}
|
||||
|
||||
val token = accounts.signIn(handle, passphrase).token
|
||||
val clearance = clearanceFrom(token)
|
||||
val api = FilesApi(server, token)
|
||||
|
||||
val opened = when (mode) {
|
||||
SignInMode.REGISTER -> FilesSession.enrolled(
|
||||
api, accounts, token, enrolledKey!!, clearance, freshCode,
|
||||
)
|
||||
SignInMode.RECOVER -> FilesSession.recover(
|
||||
api, accounts, token, recoveryCode, passphrase,
|
||||
clearance, Recovery.generate().entropy,
|
||||
)
|
||||
SignInMode.SIGN_IN -> FilesSession.open(
|
||||
api, accounts, token, passphrase, clearance,
|
||||
)
|
||||
}
|
||||
|
||||
session = opened
|
||||
opened.loadLabelKeys()
|
||||
val vocabulary = api.vocabulary()
|
||||
opened.use(clearance.minimum)
|
||||
|
||||
_state.update {
|
||||
it.copy(
|
||||
config = config,
|
||||
clearance = clearance,
|
||||
vocabulary = vocabulary,
|
||||
label = clearance.minimum,
|
||||
phase = opened.recoveryCode?.let(Phase::RecoveryCode) ?: Phase.Browsing,
|
||||
)
|
||||
}
|
||||
if (opened.recoveryCode == null) refresh()
|
||||
} catch (error: Exception) {
|
||||
session = null
|
||||
_state.update { it.copy(phase = Phase.SignedOut, error = friendly(error)) }
|
||||
}
|
||||
}
|
||||
|
||||
fun acknowledgeRecoveryCode() = launchIO {
|
||||
session?.recoveryCode = null
|
||||
_state.update { it.copy(phase = Phase.Browsing) }
|
||||
refresh()
|
||||
}
|
||||
|
||||
fun signOut() {
|
||||
session = null
|
||||
_state.update {
|
||||
it.copy(
|
||||
phase = Phase.SignedOut, clearance = null, label = null,
|
||||
path = emptyList(), entries = emptyList(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun refresh() = launchIO {
|
||||
val current = session ?: return@launchIO
|
||||
try {
|
||||
val entries = current.list(folderID)
|
||||
_state.update { it.copy(entries = entries) }
|
||||
} catch (error: Exception) {
|
||||
_state.update { it.copy(error = friendly(error)) }
|
||||
}
|
||||
}
|
||||
|
||||
fun open(entry: FilesSession.Entry) {
|
||||
if (!entry.isFolder) return
|
||||
_state.update { it.copy(path = it.path + (entry.id to (entry.name ?: "Folder"))) }
|
||||
refresh()
|
||||
}
|
||||
|
||||
fun goBack() {
|
||||
_state.update { it.copy(path = it.path.dropLast(1)) }
|
||||
refresh()
|
||||
}
|
||||
|
||||
fun use(label: Label) = launchIO {
|
||||
val current = session ?: return@launchIO
|
||||
try {
|
||||
current.use(label)
|
||||
// Changing area changes what exists, so the breadcrumb cannot
|
||||
// survive it: a folder id from one label may be invisible in
|
||||
// another, and 404 is the correct answer rather than an error.
|
||||
_state.update { it.copy(label = label, path = emptyList()) }
|
||||
refresh()
|
||||
} catch (error: Exception) {
|
||||
_state.update { it.copy(error = friendly(error)) }
|
||||
}
|
||||
}
|
||||
|
||||
fun createFolder(name: String) = launchIO {
|
||||
val current = session ?: return@launchIO
|
||||
try {
|
||||
current.createFolder(name, folderID)
|
||||
refresh()
|
||||
} catch (error: Exception) {
|
||||
_state.update { it.copy(error = friendly(error)) }
|
||||
}
|
||||
}
|
||||
|
||||
fun upload(bytes: ByteArray, name: String) = launchIO {
|
||||
val current = session ?: return@launchIO
|
||||
_state.update { it.copy(phase = Phase.Working("Encrypting $name…")) }
|
||||
try {
|
||||
current.upload(bytes, name, folderID)
|
||||
_state.update { it.copy(phase = Phase.Browsing) }
|
||||
refresh()
|
||||
} catch (error: Exception) {
|
||||
_state.update { it.copy(phase = Phase.Browsing, error = friendly(error)) }
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun download(entry: FilesSession.Entry): ByteArray? = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
session?.download(entry.node)
|
||||
} catch (error: Exception) {
|
||||
_state.update { it.copy(error = friendly(error)) }
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun createShare(entry: FilesSession.Entry, password: String?): String? =
|
||||
withContext(Dispatchers.IO) {
|
||||
val current = session ?: return@withContext null
|
||||
val site = _state.value.config?.siteURL ?: return@withContext null
|
||||
try {
|
||||
current.createShare(entry, password = password?.takeIf(String::isNotEmpty))
|
||||
.url(site)
|
||||
} catch (error: Exception) {
|
||||
_state.update { it.copy(error = friendly(error)) }
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
private fun friendly(error: Throwable): String =
|
||||
(error as? ClientException)?.message ?: error.message ?: "Something went wrong."
|
||||
|
||||
private fun launchIO(block: suspend () -> Unit) {
|
||||
viewModelScope.launch(Dispatchers.IO) { block() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
package io.flamenet.files.app
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.*
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalClipboardManager
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.ViewModelProvider
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import io.flamenet.files.client.FilesSession
|
||||
import io.flamenet.files.engine.Label
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
class MainActivity : ComponentActivity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
val context = applicationContext
|
||||
setContent {
|
||||
MaterialTheme {
|
||||
val model: FilesViewModel = viewModel(
|
||||
factory = object : ViewModelProvider.Factory {
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
override fun <T : ViewModel> create(modelClass: Class<T>): T =
|
||||
FilesViewModel(context) as T
|
||||
},
|
||||
)
|
||||
Root(model)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun Root(model: FilesViewModel) {
|
||||
val state by model.state.collectAsState()
|
||||
|
||||
state.error?.let { message ->
|
||||
AlertDialog(
|
||||
onDismissRequest = model::dismissError,
|
||||
confirmButton = { TextButton(onClick = model::dismissError) { Text("OK") } },
|
||||
title = { Text("Something went wrong") },
|
||||
text = { Text(message) },
|
||||
)
|
||||
}
|
||||
|
||||
when (val phase = state.phase) {
|
||||
is Phase.SignedOut -> SignIn(model, state)
|
||||
is Phase.Working -> Working(phase.what)
|
||||
is Phase.RecoveryCode -> RecoveryCode(phase.code, model::acknowledgeRecoveryCode)
|
||||
is Phase.Browsing -> Browse(model, state)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Says what is slow and why.
|
||||
*
|
||||
* The stretch takes several seconds on a phone, on purpose. Without a reason on
|
||||
* screen, a deliberate cost reads as a broken app.
|
||||
*/
|
||||
@Composable
|
||||
fun Working(what: String) {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxSize().padding(40.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Center,
|
||||
) {
|
||||
CircularProgressIndicator()
|
||||
Spacer(Modifier.height(20.dp))
|
||||
Text(what, style = MaterialTheme.typography.titleMedium)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(
|
||||
"This takes a few seconds on purpose — it's what makes a short passphrase hard to attack.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun SignIn(model: FilesViewModel, state: UiState) {
|
||||
var mode by remember { mutableStateOf(SignInMode.SIGN_IN) }
|
||||
var passphrase by remember { mutableStateOf("") }
|
||||
var recoveryCode by remember { mutableStateOf("") }
|
||||
var showingServer by remember { mutableStateOf(false) }
|
||||
|
||||
LaunchedEffect(Unit) { model.probe() }
|
||||
|
||||
Column(
|
||||
modifier = Modifier.fillMaxSize().padding(24.dp).imePadding(),
|
||||
verticalArrangement = Arrangement.spacedBy(14.dp),
|
||||
) {
|
||||
Spacer(Modifier.height(28.dp))
|
||||
Text("Flamenet Files", style = MaterialTheme.typography.headlineMedium)
|
||||
|
||||
OutlinedTextField(
|
||||
value = state.handle,
|
||||
onValueChange = model::setHandle,
|
||||
label = { Text("Handle") },
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
OutlinedTextField(
|
||||
value = passphrase,
|
||||
onValueChange = { passphrase = it },
|
||||
label = { Text(if (mode == SignInMode.RECOVER) "New passphrase" else "Passphrase") },
|
||||
singleLine = true,
|
||||
visualTransformation = PasswordVisualTransformation(),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
if (mode == SignInMode.RECOVER) {
|
||||
OutlinedTextField(
|
||||
value = recoveryCode,
|
||||
onValueChange = { recoveryCode = it },
|
||||
label = { Text("Recovery code") },
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
|
||||
Text(
|
||||
when (mode) {
|
||||
SignInMode.SIGN_IN ->
|
||||
"Your passphrase never leaves this device. It builds your keys here."
|
||||
SignInMode.REGISTER ->
|
||||
"Choose something long. There is no way to reset it — you'll get a recovery code once, and that is the only way back in."
|
||||
SignInMode.RECOVER ->
|
||||
"Your recovery code unlocks the same keys your passphrase did, so nothing needs re-encrypting. A fresh code is issued and the old one stops working."
|
||||
},
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
|
||||
Button(
|
||||
onClick = { model.signIn(passphrase, mode, recoveryCode) },
|
||||
enabled = state.handle.isNotBlank() && passphrase.isNotEmpty() &&
|
||||
(mode != SignInMode.RECOVER || recoveryCode.isNotBlank()),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) { Text(mode.label) }
|
||||
|
||||
SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) {
|
||||
SignInMode.entries.forEachIndexed { index, option ->
|
||||
SegmentedButton(
|
||||
selected = mode == option,
|
||||
onClick = { mode = option },
|
||||
shape = SegmentedButtonDefaults.itemShape(index, SignInMode.entries.size),
|
||||
) { Text(option.label) }
|
||||
}
|
||||
}
|
||||
|
||||
// Behind a disclosure: almost nobody changes it, and a URL field at the
|
||||
// top of a sign-in screen makes a simple product look administrative.
|
||||
TextButton(onClick = { showingServer = !showingServer }) {
|
||||
Text(if (showingServer) "Hide server" else "Server")
|
||||
}
|
||||
if (showingServer) {
|
||||
OutlinedTextField(
|
||||
value = state.server,
|
||||
onValueChange = model::setServer,
|
||||
label = { Text("Server") },
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
state.config?.let {
|
||||
Text(
|
||||
"Accounts: ${Uri.parse(it.accountsURL).host}",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
}
|
||||
TextButton(onClick = model::probe) { Text("Check") }
|
||||
}
|
||||
Text(
|
||||
"Your server decides which account service to trust. Self-hosted deployments use their own.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Shown once, and it says so. */
|
||||
@Composable
|
||||
fun RecoveryCode(code: String, onAcknowledge: () -> Unit) {
|
||||
val clipboard = LocalClipboardManager.current
|
||||
Column(
|
||||
modifier = Modifier.fillMaxSize().padding(28.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Center,
|
||||
) {
|
||||
Text("Write this down now", style = MaterialTheme.typography.headlineSmall)
|
||||
Spacer(Modifier.height(12.dp))
|
||||
Text(
|
||||
"This is the only way back in if you forget your passphrase. It is not stored anywhere, this is the only time it will ever be shown, and we cannot send it again.",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
Spacer(Modifier.height(22.dp))
|
||||
Surface(
|
||||
tonalElevation = 3.dp,
|
||||
shape = MaterialTheme.shapes.medium,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
// Monospaced and generously spaced, because this gets copied onto
|
||||
// paper by hand and a wrapped group is a transcription error.
|
||||
Text(
|
||||
code,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
textAlign = TextAlign.Center,
|
||||
modifier = Modifier.padding(18.dp).fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(22.dp))
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
OutlinedButton(onClick = { clipboard.setText(AnnotatedString(code)) }) { Text("Copy") }
|
||||
Button(onClick = onAcknowledge) { Text("I've written it down") }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="app_name">Flamenet Files</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<style name="Theme.FlamenetFiles" parent="android:Theme.Material.Light.NoActionBar" />
|
||||
</resources>
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
Only the cache directory, and only what this app wrote there. A decrypted file
|
||||
is handed to another app through a share sheet and nothing wider is exposed.
|
||||
-->
|
||||
<paths>
|
||||
<cache-path name="downloads" path="." />
|
||||
</paths>
|
||||
@@ -1,3 +1,19 @@
|
||||
pluginManagement {
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
gradlePluginPortal()
|
||||
}
|
||||
}
|
||||
|
||||
dependencyResolutionManagement {
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
}
|
||||
|
||||
rootProject.name = "flamenet-files-android"
|
||||
include(":engine")
|
||||
include(":client")
|
||||
include(":app")
|
||||
|
||||
Reference in New Issue
Block a user